_id
stringlengths 2
7
| title
stringlengths 3
140
| partition
stringclasses 3
values | text
stringlengths 73
34.1k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q180700
|
TimeoutMap.restart
|
test
|
public void restart()
{
// Clear the sweep thread kill flag.
sweepThreadKillFlag = false;
// Start the sweep thread running with low priority.
cacheSweepThread =
new Thread()
{
public void run()
{
sweep();
}
};
cacheSweepThread.setPriority(Thread.MIN_PRIORITY);
cacheSweepThread.start();
}
|
java
|
{
"resource": ""
}
|
q180701
|
Searches.setOf
|
test
|
public static <T> Set<T> setOf(SearchMethod<T> method)
{
Set<T> result = new HashSet<T>();
findAll(result, method);
return result;
}
|
java
|
{
"resource": ""
}
|
q180702
|
Searches.bagOf
|
test
|
public static <T> Collection<T> bagOf(SearchMethod<T> method)
{
Collection<T> result = new ArrayList<T>();
findAll(result, method);
return result;
}
|
java
|
{
"resource": ""
}
|
q180703
|
Searches.findAll
|
test
|
private static <T> void findAll(Collection<T> result, SearchMethod<T> method)
{
for (Iterator<T> i = allSolutions(method); i.hasNext();)
{
T nextSoltn = i.next();
result.add(nextSoltn);
}
}
|
java
|
{
"resource": ""
}
|
q180704
|
Filterator.nextInSequence
|
test
|
public T nextInSequence()
{
T result = null;
// Loop until a filtered element is found, or the source iterator is exhausted.
while (source.hasNext())
{
S next = source.next();
result = mapping.apply(next);
if (result != null)
{
break;
}
}
return result;
}
|
java
|
{
"resource": ""
}
|
q180705
|
BeanMemento.restoreValues
|
test
|
public static void restoreValues(Object ob, Map<String, Object> values) throws NoSuchFieldException
{
/*log.fine("public void restore(Object ob): called");*/
/*log.fine("Object to restore to has the type: " + ob.getClass());*/
// Get the class of th object to restore to.
Class obClass = ob.getClass();
// Loop over all the stored properties.
for (String propName : values.keySet())
{
// Get the cached property from this mementos store.
Object nextValue = values.get(propName);
/*log.fine("Next property to restore is: " + propName);*/
/*log.fine("Next value to restore is: " + nextValue);*/
// Used to hold the value to set.
Object paramValue;
// Used to hold the type of the value to set.
Class paramType;
// Check if the value store is a null.
if (nextValue == null)
{
paramValue = null;
paramType = null;
}
// Check if the value to store is a multi type data object.
else if (nextValue instanceof TypeConverter.MultiTypeData)
{
/*log.fine("The value to restore is a multi typed data object.");*/
TypeConverter.MultiTypeData multiValue = (TypeConverter.MultiTypeData) nextValue;
// Get the types (classes) of all the possible 'setter' methods for the property.
Set<Class> setterTypes = ReflectionUtils.findMatchingSetters(ob.getClass(), propName);
/*log.fine("setterTypes = " + setterTypes);*/
// Use the type converter to get the best matching type with the multi data.
paramType = TypeConverter.bestMatchingConversion(multiValue, setterTypes);
// Convert the multi data to an object of the appropriate type.
paramValue = TypeConverter.convert(multiValue, paramType);
}
// The value to store is not a multi type.
else
{
/*log.fine("The value to restore is a simply typed data object.");*/
// Get the type and value of the plain type to set.
paramValue = nextValue;
paramType = nextValue.getClass();
}
/*log.fine("paramValue = " + paramValue);*/
/*log.fine("paramType = " + paramType);*/
// Call the setter method with the new property value, checking first that the property has a matching
// 'setter' method.
Method setterMethod;
try
{
// Convert the first letter of the property name to upper case to match against the upper case version
// of it that will be in the setter method name. For example the property test will have a setter method
// called setTest.
String upperPropertyName = Character.toUpperCase(propName.charAt(0)) + propName.substring(1);
// Try to find an appropriate setter method on the object to call.
setterMethod = obClass.getMethod("set" + upperPropertyName, paramType);
// Call the setter method with the new property value.
Object[] params = new Object[] { paramValue };
setterMethod.invoke(ob, params);
}
catch (NoSuchMethodException e)
{
// Do nothing as properties may have getters but no setter for read only properties.
/*log.log(java.util.logging.Level.FINE, "A setter method could not be found for " + propName + ".", e);*/
/*
// The object does not have a matching setter method for the type.
NoSuchFieldException nsfe = new NoSuchFieldException("The object does not have a matching setter " +
"method 'set" + propName + "'.");
nsfe.initCause(e);
throw nsfe;
*/
}
catch (IllegalAccessException e)
{
/*log.log(java.util.logging.Level.FINE, "IllegalAccessException during call to setter method.", e);*/
}
catch (InvocationTargetException e)
{
/*log.log(java.util.logging.Level.FINE, "InvocationTargetException during call to setter method.", e);*/
}
}
}
|
java
|
{
"resource": ""
}
|
q180706
|
BeanMemento.get
|
test
|
public Object get(Class cls, String property) throws NoSuchFieldException
{
// Check that the field exists.
if (!values.containsKey(property))
{
throw new NoSuchFieldException("The property, " + property + ", does not exist on the underlying class.");
}
// Try to find a matching property cached in this memento.
return values.get(property);
}
|
java
|
{
"resource": ""
}
|
q180707
|
BeanMemento.put
|
test
|
public void put(Class cls, String property, TypeConverter.MultiTypeData value)
{
/*log.fine("public void put(String property, TypeConverter.MultiTypeData value): called");*/
/*log.fine("property = " + property);*/
/*log.fine("value = " + value);*/
// Store the multi typed data under the specified property name.
values.put(property, value);
}
|
java
|
{
"resource": ""
}
|
q180708
|
BeanMemento.put
|
test
|
public void put(Class cls, String property, Object value)
{
// Store the new data under the specified property name.
values.put(property, value);
}
|
java
|
{
"resource": ""
}
|
q180709
|
BeanMemento.capture
|
test
|
private void capture(boolean ignoreNull)
{
// Get the class of the object to build a memento for.
Class cls = ob.getClass();
// Iterate through all the public methods of the class including all super-interfaces and super-classes.
Method[] methods = cls.getMethods();
for (Method nextMethod : methods)
{
// Get the next method.
/*log.fine("nextMethod = " + nextMethod.getName());*/
// Check if the method is a 'getter' method, is public and takes no arguments.
String methodName = nextMethod.getName();
if (methodName.startsWith("get") && (methodName.length() >= 4) &&
Character.isUpperCase(methodName.charAt(3)) && Modifier.isPublic(nextMethod.getModifiers()) &&
(nextMethod.getParameterTypes().length == 0))
{
String propName = Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4);
/*log.fine(methodName + " is a valid getter method for the property " + propName + ".");*/
try
{
// Call the 'getter' method to extract the properties value.
Object[] params = new Object[] {};
Object value = nextMethod.invoke(ob, params);
/*log.fine("The result of calling the getter method is: " + value);*/
// Store the property value for the object.
if (!ignoreNull || (value != null))
{
values.put(propName, value);
}
}
catch (IllegalAccessException e)
{
/*log.log(java.util.logging.Level.FINE, "IllegalAccessException during call to getter method.", e);*/
throw new IllegalStateException(e);
}
catch (InvocationTargetException e)
{
/*log.log(java.util.logging.Level.FINE, "InvocationTargetException during call to getter method.", e);*/
throw new IllegalStateException(e);
}
}
// Should also check if the method is a 'setter' method, is public and takes exactly one argument.
}
}
|
java
|
{
"resource": ""
}
|
q180710
|
FifoStack.pop
|
test
|
public E pop()
{
E ob;
if (size() == 0)
{
return null;
}
ob = get(0);
remove(0);
return ob;
}
|
java
|
{
"resource": ""
}
|
q180711
|
SwingKeyCombinationBuilder.modifiersToString
|
test
|
private String modifiersToString(int modifiers)
{
String result = "";
if ((modifiers & InputEvent.SHIFT_MASK) != 0)
{
result += "shift ";
}
if ((modifiers & InputEvent.CTRL_MASK) != 0)
{
result += "ctrl ";
}
if ((modifiers & InputEvent.META_MASK) != 0)
{
result += "meta ";
}
if ((modifiers & InputEvent.ALT_MASK) != 0)
{
result += "alt ";
}
if ((modifiers & InputEvent.ALT_GRAPH_MASK) != 0)
{
result += "altGraph ";
}
return result;
}
|
java
|
{
"resource": ""
}
|
q180712
|
Validation.toInteger
|
test
|
public static int toInteger(String s)
{
try
{
return Integer.parseInt(s);
}
catch (NumberFormatException e)
{
// Exception noted so can be ignored.
e = null;
return 0;
}
}
|
java
|
{
"resource": ""
}
|
q180713
|
Validation.toDate
|
test
|
public static Date toDate(String s)
{
// Build a date formatter using the format specified by dateFormat
DateFormat dateFormatter = new SimpleDateFormat(dateFormat);
try
{
return dateFormatter.parse(s);
}
catch (ParseException e)
{
// Exception noted so can be ignored.
e = null;
return null;
}
}
|
java
|
{
"resource": ""
}
|
q180714
|
Validation.isDate
|
test
|
public static boolean isDate(String s)
{
// Build a date formatter using the format specified by dateFormat
DateFormat dateFormatter = new SimpleDateFormat(dateFormat);
try
{
dateFormatter.parse(s);
return true;
}
catch (ParseException e)
{
// Exception noted so can be ignored.
e = null;
return false;
}
}
|
java
|
{
"resource": ""
}
|
q180715
|
Validation.isTime
|
test
|
public static boolean isTime(String s)
{
// Build a time formatter using the format specified by timeFormat
DateFormat dateFormatter = new SimpleDateFormat(timeFormat);
try
{
dateFormatter.parse(s);
return true;
}
catch (ParseException e)
{
// Exception noted so can be ignored.
e = null;
return false;
}
}
|
java
|
{
"resource": ""
}
|
q180716
|
Validation.isDateTime
|
test
|
public static boolean isDateTime(String s)
{
DateFormat dateFormatter = new SimpleDateFormat(dateTimeFormat);
try
{
dateFormatter.parse(s);
return true;
}
catch (ParseException e)
{
// Exception noted so can be ignored.
e = null;
return false;
}
}
|
java
|
{
"resource": ""
}
|
q180717
|
TokenSource.getTokenSourceForString
|
test
|
public static TokenSource getTokenSourceForString(String stringToTokenize)
{
SimpleCharStream inputStream = new SimpleCharStream(new StringReader(stringToTokenize), 1, 1);
PrologParserTokenManager tokenManager = new PrologParserTokenManager(inputStream);
return new TokenSource(tokenManager);
}
|
java
|
{
"resource": ""
}
|
q180718
|
TokenSource.getTokenSourceForFile
|
test
|
public static TokenSource getTokenSourceForFile(File file) throws FileNotFoundException
{
// Create a token source to load the model rules from.
Reader ins = new FileReader(file);
SimpleCharStream inputStream = new SimpleCharStream(ins, 1, 1);
PrologParserTokenManager tokenManager = new PrologParserTokenManager(inputStream);
return new TokenSource(tokenManager);
}
|
java
|
{
"resource": ""
}
|
q180719
|
TokenSource.getTokenSourceForInputStream
|
test
|
public static Source getTokenSourceForInputStream(InputStream in)
{
SimpleCharStream inputStream = new SimpleCharStream(in, 1, 1);
PrologParserTokenManager tokenManager = new PrologParserTokenManager(inputStream);
return new TokenSource(tokenManager);
}
|
java
|
{
"resource": ""
}
|
q180720
|
OptimizeInstructions.isConstant
|
test
|
public boolean isConstant(WAMInstruction instruction)
{
Integer name = instruction.getFunctorNameReg1();
if (name != null)
{
FunctorName functorName = interner.getDeinternedFunctorName(name);
if (functorName.getArity() == 0)
{
return true;
}
}
return false;
}
|
java
|
{
"resource": ""
}
|
q180721
|
OptimizeInstructions.isVoidVariable
|
test
|
private boolean isVoidVariable(WAMInstruction instruction)
{
SymbolKey symbolKey = instruction.getSymbolKeyReg1();
if (symbolKey != null)
{
Integer count = (Integer) symbolTable.get(symbolKey, SymbolTableKeys.SYMKEY_VAR_OCCURRENCE_COUNT);
Boolean nonArgPositionOnly = (Boolean) symbolTable.get(symbolKey, SymbolTableKeys.SYMKEY_VAR_NON_ARG);
Integer allocation = (Integer) symbolTable.get(symbolKey, SymbolTableKeys.SYMKEY_ALLOCATION);
boolean singleton = (count != null) && count.equals(1);
boolean nonArgPosition = (nonArgPositionOnly != null) && TRUE.equals(nonArgPositionOnly);
boolean permanent =
(allocation != null) && ((byte) ((allocation & 0xff00) >> 8) == WAMInstruction.STACK_ADDR);
if (singleton && nonArgPosition && !permanent)
{
return true;
}
}
return false;
}
|
java
|
{
"resource": ""
}
|
q180722
|
OptimizeInstructions.isNonArg
|
test
|
private boolean isNonArg(WAMInstruction instruction)
{
SymbolKey symbolKey = instruction.getSymbolKeyReg1();
if (symbolKey != null)
{
Boolean nonArgPositionOnly = (Boolean) symbolTable.get(symbolKey, SymbolTableKeys.SYMKEY_FUNCTOR_NON_ARG);
if (TRUE.equals(nonArgPositionOnly))
{
return true;
}
}
return false;
}
|
java
|
{
"resource": ""
}
|
q180723
|
Clause.getChildren
|
test
|
public Iterator<Operator<Term>> getChildren(boolean reverse)
{
if ((traverser != null) && (traverser instanceof ClauseTraverser))
{
return ((ClauseTraverser) traverser).traverse(this, reverse);
}
else
{
LinkedList<Operator<Term>> resultList = null;
if (!reverse)
{
resultList = new LinkedList<Operator<Term>>();
}
else
{
resultList = new StackQueue<Operator<Term>>();
}
if (head != null)
{
resultList.add(head);
}
if (body != null)
{
for (Term bodyTerm : body)
{
resultList.add(bodyTerm);
}
}
return resultList.iterator();
}
}
|
java
|
{
"resource": ""
}
|
q180724
|
Functor.getArgument
|
test
|
public Term getArgument(int index)
{
if ((arguments == null) || (index > (arguments.length - 1)))
{
return null;
}
else
{
return arguments[index];
}
}
|
java
|
{
"resource": ""
}
|
q180725
|
Functor.getChildren
|
test
|
public Iterator<Operator<Term>> getChildren(boolean reverse)
{
if ((traverser != null) && (traverser instanceof FunctorTraverser))
{
return ((FunctorTraverser) traverser).traverse(this, reverse);
}
else
{
if (arguments == null)
{
return new LinkedList<Operator<Term>>().iterator();
}
else if (!reverse)
{
return Arrays.asList((Operator<Term>[]) arguments).iterator();
}
else
{
List<Operator<Term>> argList = new LinkedList<Operator<Term>>();
for (int i = arity - 1; i >= 0; i--)
{
argList.add(arguments[i]);
}
return argList.iterator();
}
}
}
|
java
|
{
"resource": ""
}
|
q180726
|
Functor.toStringArguments
|
test
|
protected String toStringArguments()
{
String result = "";
if (arity > 0)
{
result += "[ ";
for (int i = 0; i < arity; i++)
{
Term nextArg = arguments[i];
result += ((nextArg != null) ? nextArg.toString() : "<null>") + ((i < (arity - 1)) ? ", " : " ");
}
result += " ]";
}
return result;
}
|
java
|
{
"resource": ""
}
|
q180727
|
SqlQueryEngine.retrieveSummary
|
test
|
public <T extends MeasureAppender> T retrieveSummary(SchemaDefinition schemaDefinition, Class<T> resultClazz, QueryParameter queryParameter) throws NovieRuntimeException {
final SqlQueryBuilder<T> sqlQueryBuilder = new SqlQueryBuilder<T>(schemaDefinition, resultClazz,
queryParameter.partialCopy(QueryParameterKind.GROUPS, QueryParameterKind.PAGE));
List<T> result = executeQuery(sqlQueryBuilder);
if (result.isEmpty()) {
throw new NovieRuntimeException("Summary doesn't return any result.");
}
if (result.size() > 1) {
throw new NovieRuntimeException("Summary returns more than one result.");
}
return result.get(0);
}
|
java
|
{
"resource": ""
}
|
q180728
|
SqlQueryEngine.retrieveRecords
|
test
|
public <T extends MeasureAppender> List<T> retrieveRecords(SchemaDefinition schemaDefinition, Class<T> resultClazz, QueryParameter queryParameter) throws NovieRuntimeException {
final SqlQueryBuilder<T> sqlQueryBuilder = new SqlQueryBuilder<T>(schemaDefinition, resultClazz, queryParameter);
return executeQuery(sqlQueryBuilder);
}
|
java
|
{
"resource": ""
}
|
q180729
|
SqlQueryEngine.executeQuery
|
test
|
private <T extends MeasureAppender> List<T> executeQuery(final SqlQueryBuilder<T> sqlQueryBuilder) throws NovieRuntimeException {
sqlQueryBuilder.buildQuery();
final String queryString = sqlQueryBuilder.getQueryString();
LOG.debug(queryString);
long beforeQuery = System.currentTimeMillis();
List<T> returnValue = jdbcTemplate.query(queryString, sqlQueryBuilder.getMapSqlParameterSource(), sqlQueryBuilder);
if (LOG.isInfoEnabled()) {
LOG.info("SQL query successfully ran in " + (System.currentTimeMillis() - beforeQuery) + "ms.");
}
if (LOG.isDebugEnabled()) {
StringBuilder sb = new StringBuilder();
for (Entry<String, Object> e : sqlQueryBuilder.getMapSqlParameterSource().getValues().entrySet()) {
if (sb.length() > 0) {
sb.append(",");
}
sb.append(e.getKey());
sb.append("=");
sb.append(e.getValue());
}
sb.insert(0, "Parameters [");
sb.append("]");
LOG.debug(sb.toString());
}
return returnValue;
}
|
java
|
{
"resource": ""
}
|
q180730
|
WAMInstruction.emmitCode
|
test
|
public void emmitCode(ByteBuffer codeBuffer, WAMMachine machine) throws LinkageException
{
mnemonic.emmitCode(this, codeBuffer, machine);
}
|
java
|
{
"resource": ""
}
|
q180731
|
JavaType.setBasicType
|
test
|
private void setBasicType(Class c)
{
if (Boolean.class.equals(c))
{
type = BasicTypes.BOOLEAN;
}
else if (Character.class.equals(c))
{
type = BasicTypes.CHARACTER;
}
else if (Byte.class.equals(c))
{
type = BasicTypes.BYTE;
}
else if (Short.class.equals(c))
{
type = BasicTypes.SHORT;
}
else if (Integer.class.equals(c))
{
type = BasicTypes.INTEGER;
}
else if (Long.class.equals(c))
{
type = BasicTypes.LONG;
}
else if (Float.class.equals(c))
{
type = BasicTypes.FLOAT;
}
else if (Double.class.equals(c))
{
type = BasicTypes.DOUBLE;
}
else
{
type = BasicTypes.OTHER;
}
}
|
java
|
{
"resource": ""
}
|
q180732
|
ResolutionEngine.consultInputStream
|
test
|
public void consultInputStream(InputStream stream) throws SourceCodeException
{
// Create a token source to read from the specified input stream.
Source<Token> tokenSource = TokenSource.getTokenSourceForInputStream(stream);
getParser().setTokenSource(tokenSource);
// Consult the type checking rules and add them to the knowledge base.
while (true)
{
Sentence<S> sentence = getParser().parse();
if (sentence == null)
{
break;
}
getCompiler().compile(sentence);
}
}
|
java
|
{
"resource": ""
}
|
q180733
|
ResolutionEngine.printVariableBinding
|
test
|
public String printVariableBinding(Term var)
{
return var.toString(getInterner(), true, false) + " = " + var.getValue().toString(getInterner(), false, true);
}
|
java
|
{
"resource": ""
}
|
q180734
|
ResolutionEngine.expandResultSetToMap
|
test
|
public Iterable<Map<String, Variable>> expandResultSetToMap(Iterator<Set<Variable>> solutions)
{
return new Filterator<Set<Variable>, Map<String, Variable>>(solutions,
new Function<Set<Variable>, Map<String, Variable>>()
{
public Map<String, Variable> apply(Set<Variable> variables)
{
Map<String, Variable> results = new HashMap<String, Variable>();
for (Variable var : variables)
{
String varName = getInterner().getVariableName(var.getName());
results.put(varName, var);
}
return results;
}
});
}
|
java
|
{
"resource": ""
}
|
q180735
|
SocketReadThread.run
|
test
|
public void run() {
try {
readStream();
} catch (EOFException eof) {
// Normal disconnect
} catch (SocketException se) {
// Do nothing if the exception occured while shutting down the
// component otherwise
// log the error and try to establish a new connection
if (!shutdown) {
component.getManager().getLog().error(se);
component.connectionLost();
}
} catch (XmlPullParserException ie) {
component.getManager().getLog().error(ie);
} catch (Exception e) {
component.getManager().getLog().warn(e);
}
}
|
java
|
{
"resource": ""
}
|
q180736
|
SocketReadThread.readStream
|
test
|
private void readStream() throws Exception {
while (!shutdown) {
Element doc = reader.parseDocument().getRootElement();
if (doc == null) {
// Stop reading the stream since the server has sent an end of
// stream element and
// probably closed the connection
return;
}
Packet packet;
String tag = doc.getName();
if ("message".equals(tag)) {
packet = new Message(doc);
} else if ("presence".equals(tag)) {
packet = new Presence(doc);
} else if ("iq".equals(tag)) {
packet = getIQ(doc);
} else {
throw new XmlPullParserException(
"Unknown packet type was read: " + tag);
}
// Request the component to process the received packet
component.processPacket(packet);
}
}
|
java
|
{
"resource": ""
}
|
q180737
|
Type1UUID.getTime
|
test
|
static long getTime() {
if (RANDOM == null)
initializeForType1();
long newTime = getUUIDTime();
if (newTime <= _lastMillis) {
incrementSequence();
newTime = getUUIDTime();
}
_lastMillis = newTime;
return newTime;
}
|
java
|
{
"resource": ""
}
|
q180738
|
Type1UUID.getUUIDTime
|
test
|
private static long getUUIDTime() {
if (_currentMillis != System.currentTimeMillis()) {
_currentMillis = System.currentTimeMillis();
_counter = 0; // reset counter
}
// check to see if we have created too many uuid's for this timestamp
if (_counter + 1 >= MILLI_MULT) {
// Original algorithm threw exception. Seemed like overkill.
// Let's just increment the timestamp instead and start over...
_currentMillis++;
_counter = 0;
}
// calculate time as current millis plus offset times 100 ns ticks
long currentTime = (_currentMillis + GREG_OFFSET) * MILLI_MULT;
// return the uuid time plus the artificial tick counter incremented
return currentTime + _counter++;
}
|
java
|
{
"resource": ""
}
|
q180739
|
Player.trackInfoUpdate
|
test
|
@SuppressWarnings("unused")
public void trackInfoUpdate(Playlist playlist, TrackInfo info) {
this.playlist = playlist;
updatePlayInfo(info);
}
|
java
|
{
"resource": ""
}
|
q180740
|
Player.updatePlayInfo
|
test
|
@SuppressWarnings("unused")
public void updatePlayInfo(Playlist playlist, Progress progress, Volume volume) {
if (playlist != null)
this.playlist = playlist;
if (progress != null)
this.progress = progress;
if (volume != null)
this.volume = volume;
updatePlayInfo(playlist, progress, null, volume);
}
|
java
|
{
"resource": ""
}
|
q180741
|
Player.renderFinalOutput
|
test
|
@Override
public void renderFinalOutput(List<T> data, EventModel eventModel) {
if (StartMusicRequest.verify(eventModel, capabilities, this, activators)) {
if (isOutputRunning()) {
playerError(PlayerError.ERROR_ALREADY_PLAYING, eventModel.getSource());
} else {
handleEventRequest(eventModel);
}
} else if (eventModel.getListResourceContainer()
.providesResource(Collections.singletonList(MusicUsageResource.ID))){
if (isOutputRunning()) {
eventModel.getListResourceContainer()
.provideResource(MusicUsageResource.ID)
.forEach(resourceModel ->
playerError(PlayerError.ERROR_ALREADY_PLAYING, resourceModel.getProvider()));
} else {
handleResourceRequest(eventModel);
}
} else {
handleCommands(eventModel);
}
}
|
java
|
{
"resource": ""
}
|
q180742
|
Player.handleResourceRequest
|
test
|
private void handleResourceRequest(EventModel eventModel) {
if (MusicUsageResource.isPermanent(eventModel)) {
ResourceModel resourceModel = eventModel.getListResourceContainer()
.provideResource(MusicUsageResource.ID)
.stream()
.filter(MusicUsageResource::isPermanent)
.findAny()
.orElse(null);//should not happen
//a partially applied function which takes an Identification an returns an Optional StartMusicRequest
Function<Identification, Optional<StartMusicRequest>> getStartMusicRequest = own ->
StartMusicRequest.createStartMusicRequest(resourceModel.getProvider(), own);
//if we have a trackInfo we create it with the trackInfo as a parameter
getStartMusicRequest = TrackInfoResource.getTrackInfo(eventModel)
.map(trackInfo -> (Function<Identification, Optional<StartMusicRequest>>) own ->
StartMusicRequest.createStartMusicRequest(resourceModel.getProvider(), own, trackInfo))
.orElse(getStartMusicRequest);
//if we have a trackInfo we create it with the playlist as a parameter
getStartMusicRequest = PlaylistResource.getPlaylist(eventModel)
.map(playlist -> (Function<Identification, Optional<StartMusicRequest>>) own ->
StartMusicRequest.createStartMusicRequest(resourceModel.getProvider(), own, playlist))
.orElse(getStartMusicRequest);
//composes a new Function which appends the Volume to the result
getStartMusicRequest = getStartMusicRequest.andThen(
VolumeResource.getVolume(eventModel)
.flatMap(volume -> IdentificationManagerM.getInstance().getIdentification(this)
.map(identification -> new VolumeResource(identification, volume)))
.map(resource -> (Function<Optional<StartMusicRequest>, Optional<StartMusicRequest>>) opt ->
opt.map(event -> (StartMusicRequest) event.addResource(resource))
)
.orElse(Function.identity())::apply);
IdentificationManagerM.getInstance().getIdentification(this)
.flatMap(getStartMusicRequest::apply)
.ifPresent(this::fire);
} else {
play(eventModel);
if (!runsInPlay) {
blockRequest = lock.newCondition();
lock.lock();
try {
blockRequest.await(10, TimeUnit.MINUTES);
} catch (InterruptedException e) {
debug("interrupted", e);
} finally {
lock.unlock();
}
}
}
}
|
java
|
{
"resource": ""
}
|
q180743
|
Player.handleEventRequest
|
test
|
private void handleEventRequest(EventModel eventModel) {
playingThread = submit((Runnable) () -> {
//noinspection RedundantIfStatement
if (runsInPlay) {
isRunning = false;
} else {
isRunning = true;
}
isPlaying = true;
fireStartMusicRequest(eventModel);
})
.thenRun(() -> play(eventModel))
.thenRun(() -> {
if (runsInPlay) {
isRunning = false;
isPlaying = false;
endedSound();
}
});
}
|
java
|
{
"resource": ""
}
|
q180744
|
Player.fireStartMusicRequest
|
test
|
protected void fireStartMusicRequest(EventModel eventModel) {
Optional<Playlist> playlist = PlaylistResource.getPlaylist(eventModel);
Optional<Progress> progress = ProgressResource.getProgress(eventModel);
Optional<TrackInfo> trackInfo = TrackInfoResource.getTrackInfo(eventModel);
Optional<Volume> volume = VolumeResource.getVolume(eventModel);
startedSound(playlist.orElse(null), progress.orElse(null), trackInfo.orElse(null), volume.orElse(null), isUsingJava);
}
|
java
|
{
"resource": ""
}
|
q180745
|
PacketReader.init
|
test
|
protected void init() {
done = false;
connectionID = null;
readerThread = new Thread() {
public void run() {
parsePackets(this);
}
};
readerThread.setName("Smack Packet Reader ("
+ connection.connectionCounterValue + ")");
readerThread.setDaemon(true);
// Create an executor to deliver incoming packets to listeners. We'll
// use a single
// thread with an unbounded queue.
listenerExecutor = Executors
.newSingleThreadExecutor(new ThreadFactory() {
public Thread newThread(Runnable runnable) {
Thread thread = new Thread(runnable,
"Smack Listener Processor ("
+ connection.connectionCounterValue
+ ")");
thread.setDaemon(true);
return thread;
}
});
resetParser();
}
|
java
|
{
"resource": ""
}
|
q180746
|
PacketReader.startup
|
test
|
synchronized public void startup() throws XMPPException {
final List<Exception> errors = new LinkedList<Exception>();
AbstractConnectionListener connectionErrorListener = new AbstractConnectionListener() {
@Override
public void connectionClosedOnError(Exception e) {
errors.add(e);
}
};
connection.addConnectionListener(connectionErrorListener);
readerThread.start();
// Wait for stream tag before returning. We'll wait a couple of seconds
// before
// giving up and throwing an error.
try {
// A waiting thread may be woken up before the wait time or a notify
// (although this is a rare thing). Therefore, we continue waiting
// until either a connectionID has been set (and hence a notify was
// made) or the total wait time has elapsed.
int waitTime = SmackConfiguration.getPacketReplyTimeout();
wait(3 * waitTime);
} catch (InterruptedException ie) {
// Ignore.
}
connection.removeConnectionListener(connectionErrorListener);
if (connectionID == null) {
throw new XMPPException(
"Connection failed. No response from server.");
} else if (!errors.isEmpty()) {
throw new XMPPException(errors.iterator().next());
} else {
connection.connectionID = connectionID;
}
}
|
java
|
{
"resource": ""
}
|
q180747
|
PacketReader.shutdown
|
test
|
public void shutdown() {
// Notify connection listeners of the connection closing if done hasn't
// already been set.
if (!done) {
for (ConnectionListener listener : connection
.getConnectionListeners()) {
try {
listener.connectionClosed();
} catch (Exception e) {
// Catch and print any exception so we can recover
// from a faulty listener and finish the shutdown process
LOGGER.log(Level.ERROR,
"Error in listener while closing connection", e);
}
}
}
done = true;
// Shut down the listener executor.
listenerExecutor.shutdown();
}
|
java
|
{
"resource": ""
}
|
q180748
|
PacketReader.resetParser
|
test
|
private void resetParser() {
try {
innerReader = new XPPPacketReader();
innerReader.setXPPFactory(XmlPullParserFactory.newInstance());
innerReader.getXPPParser().setInput(connection.reader);
reset = true;
} catch (Exception xppe) {
LOGGER.log(Level.WARN, "Error while resetting parser", xppe);
}
}
|
java
|
{
"resource": ""
}
|
q180749
|
PacketReader.parsePackets
|
test
|
private void parsePackets(Thread thread) {
try {
while (!done) {
if (reset) {
startStream();
LOGGER.debug("Started xmlstream...");
reset = false;
continue;
}
Element doc = innerReader.parseDocument().getRootElement();
if (doc == null) {
connection.disconnect();
LOGGER.debug("End of xmlstream.");
continue;
}
Packet packet = null;
LOGGER.debug("Processing packet " + doc.asXML());
packet = parseFromPlugins(doc, packet);
if (packet == null) {
packet = parseFromCore(doc);
}
if (packet != null) {
processPacket(packet);
}
}
} catch (Exception e) {
if (!done && !connection.isSocketClosed()) {
connection.notifyConnectionError(e);
if (!connection.isConnected()) {
releaseConnectionIDLock();
}
}
}
}
|
java
|
{
"resource": ""
}
|
q180750
|
PacketReader.processPacket
|
test
|
private void processPacket(Packet packet) {
if (packet == null) {
return;
}
// Loop through all collectors and notify the appropriate ones.
for (PacketCollector collector : connection.getPacketCollectors()) {
collector.processPacket(packet);
}
// Deliver the incoming packet to listeners.
listenerExecutor.submit(new ListenerNotification(packet));
}
|
java
|
{
"resource": ""
}
|
q180751
|
AbstractApplicationOption.setCliOption
|
test
|
protected final void setCliOption(Option option){
if(option!=null){
this.cliOption = option;
}
if(this.cliOption.getDescription()!=null){
this.descr = this.cliOption.getDescription();
}
else{
this.cliOption.setDescription(this.descr);
}
}
|
java
|
{
"resource": ""
}
|
q180752
|
ChatManager.createChat
|
test
|
public Chat createChat(String userJID, MessageListener listener) {
return createChat(userJID, null, listener);
}
|
java
|
{
"resource": ""
}
|
q180753
|
InternalContent.internalize
|
test
|
void internalize(ContentManagerImpl contentManager, boolean readOnly) {
this.contentManager = contentManager;
updated = false;
newcontent = false;
this.readOnly = readOnly;
}
|
java
|
{
"resource": ""
}
|
q180754
|
InternalContent.reset
|
test
|
public void reset(Map<String, Object> updatedMap) {
if (!readOnly) {
this.content = ImmutableMap.copyOf(updatedMap);
updatedContent.clear();
updated = false;
LOGGER.debug("Reset to {} ", updatedMap);
}
}
|
java
|
{
"resource": ""
}
|
q180755
|
InternalContent.setProperty
|
test
|
public void setProperty(String key, Object value) {
if (readOnly) {
return;
}
if (value == null) {
throw new IllegalArgumentException("value must not be null");
}
Object o = content.get(key);
if (!value.equals(o)) {
updatedContent.put(key, value);
updated = true;
} else if (updatedContent.containsKey(key) && !value.equals(updatedContent.get(key))) {
updatedContent.put(key, value);
updated = true;
}
}
|
java
|
{
"resource": ""
}
|
q180756
|
OrFilter.addFilter
|
test
|
public void addFilter(PacketFilter filter) {
if (filter == null) {
throw new IllegalArgumentException("Parameter cannot be null.");
}
// If there is no more room left in the filters array, expand it.
if (size == filters.length) {
PacketFilter[] newFilters = new PacketFilter[filters.length + 2];
for (int i = 0; i < filters.length; i++) {
newFilters[i] = filters[i];
}
filters = newFilters;
}
// Add the new filter to the array.
filters[size] = filter;
size++;
}
|
java
|
{
"resource": ""
}
|
q180757
|
ModificationRequest.processRequest
|
test
|
public void processRequest(HttpServletRequest request) throws IOException,
FileUploadException, StorageClientException, AccessDeniedException {
boolean debug = LOGGER.isDebugEnabled();
if (ServletFileUpload.isMultipartContent(request)) {
if (debug) {
LOGGER.debug("Multipart POST ");
}
feedback.add("Multipart Upload");
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iterator = upload.getItemIterator(request);
while (iterator.hasNext()) {
FileItemStream item = iterator.next();
if (debug) {
LOGGER.debug("Got Item {}",item);
}
String name = item.getFieldName();
InputStream stream = item.openStream();
if (item.isFormField()) {
ParameterType pt = ParameterType.typeOfRequestParameter(name);
String propertyName = RequestUtils.propertyName(pt.getPropertyName(name));
RequestUtils.accumulate(stores.get(pt), propertyName, RequestUtils.toValue(name, Streams.asString(stream)));
feedback.add(pt.feedback(propertyName));
} else {
if (streamProcessor != null) {
feedback.addAll(streamProcessor.processStream(name, StorageClientUtils.getObjectName(item.getName()), item.getContentType(), stream, this));
}
}
}
if (debug) {
LOGGER.debug("No More items ");
}
} else {
if (debug) {
LOGGER.debug("Trad Post ");
}
// use traditional unstreamed operations.
@SuppressWarnings("unchecked")
Map<String, String[]> parameters = request.getParameterMap();
if (debug) {
LOGGER.debug("Traditional POST {} ", parameters);
}
Set<Entry<String, String[]>> entries = parameters.entrySet();
for (Entry<String, String[]> param : entries) {
String name = (String) param.getKey();
ParameterType pt = ParameterType.typeOfRequestParameter(name);
String propertyName = RequestUtils.propertyName(pt.getPropertyName(name));
RequestUtils.accumulate(stores.get(pt), propertyName, RequestUtils.toValue(name, param.getValue()));
feedback.add(pt.feedback(propertyName));
}
}
}
|
java
|
{
"resource": ""
}
|
q180758
|
ModificationRequest.resetProperties
|
test
|
public void resetProperties() {
for ( Entry<ParameterType, Map<String, Object>> e : stores.entrySet()) {
e.getValue().clear();
}
}
|
java
|
{
"resource": ""
}
|
q180759
|
PacketWriter.init
|
test
|
protected void init() {
this.writer = connection.writer;
done = false;
writerThread = new Thread() {
public void run() {
writePackets(this);
}
};
writerThread.setName("Smack Packet Writer ("
+ connection.connectionCounterValue + ")");
writerThread.setDaemon(true);
}
|
java
|
{
"resource": ""
}
|
q180760
|
PacketWriter.sendPacket
|
test
|
public void sendPacket(Packet packet) {
if (!done) {
// Invoke interceptors for the new packet that is about to be sent.
// Interceptors
// may modify the content of the packet.
connection.firePacketInterceptors(packet);
try {
queue.put(packet);
} catch (InterruptedException ie) {
LOGGER.log(
Level.ERROR,
"Failed to queue packet to send to server: "
+ packet.toString(), ie);
return;
}
synchronized (queue) {
queue.notifyAll();
}
// Process packet writer listeners. Note that we're using the
// sending
// thread so it's expected that listeners are fast.
connection.firePacketSendingListeners(packet);
}
}
|
java
|
{
"resource": ""
}
|
q180761
|
PacketWriter.nextPacket
|
test
|
private Packet nextPacket() {
Packet packet = null;
// Wait until there's a packet or we're done.
while (!done && (packet = queue.poll()) == null) {
try {
synchronized (queue) {
queue.wait();
}
} catch (InterruptedException ie) {
// Do nothing
}
}
return packet;
}
|
java
|
{
"resource": ""
}
|
q180762
|
PacketWriter.openStream
|
test
|
void openStream() throws IOException {
StringBuilder stream = new StringBuilder();
stream.append("<stream:stream");
stream.append(" to=\"").append(connection.getServiceName())
.append("\"");
stream.append(" xmlns=\"jabber:client\"");
stream.append(" xmlns:stream=\"http://etherx.jabber.org/streams\"");
stream.append(" version=\"1.0\">");
writer.write(stream.toString());
writer.flush();
}
|
java
|
{
"resource": ""
}
|
q180763
|
Event.getAllInformations
|
test
|
@Override
public List<String> getAllInformations() {
ArrayList<String> strings = new ArrayList<>(descriptors);
strings.add(type);
return strings;
}
|
java
|
{
"resource": ""
}
|
q180764
|
Event.containsDescriptor
|
test
|
@Override
public boolean containsDescriptor(String descriptor) {
return descriptors.contains(descriptor) || type.equals(descriptor);
}
|
java
|
{
"resource": ""
}
|
q180765
|
Event.addEventLifeCycleListener
|
test
|
@SuppressWarnings("unused")
public Event addEventLifeCycleListener(EventLifeCycle eventLifeCycle, Consumer<EventLifeCycle> cycleCallback) {
lifeCycleListeners.compute(eventLifeCycle, (unused, list) -> {
if (list == null)
list = new ArrayList<>();
list.add(cycleCallback);
return list;
});
return this;
}
|
java
|
{
"resource": ""
}
|
q180766
|
TaskEngine.shutdown
|
test
|
public void shutdown() {
if (executor != null) {
executor.shutdownNow();
executor = null;
}
if (timer != null) {
timer.cancel();
timer = null;
}
}
|
java
|
{
"resource": ""
}
|
q180767
|
Files.contentEquals
|
test
|
public static Boolean contentEquals(Path file1, Path file2) throws IOException
{
if (!java.nio.file.Files.isRegularFile(file1))
throw new IllegalArgumentException(file1 + "is not a regular file");
if (!java.nio.file.Files.isRegularFile(file2))
throw new IllegalArgumentException(file2 + "is not a regular file");
FileChannel channel1 = null;
FileChannel channel2 = null;
MappedByteBuffer buffer1 = null;
MappedByteBuffer buffer2 = null;
try
{
long size1 = java.nio.file.Files.size(file1);
long size2 = java.nio.file.Files.size(file2);
if (size1 != size2) return false;
long position = 0;
long length = Math.min(Integer.MAX_VALUE, size1 - position);
channel1 = FileChannel.open(file1);
channel2 = FileChannel.open(file2);
// Cannot map files larger than Integer.MAX_VALUE,
// so we have to do it in pieces.
while (length > 0)
{
buffer1 = channel1.map(MapMode.READ_ONLY, position, length);
buffer2 = channel2.map(MapMode.READ_ONLY, position, length);
// if (!buffer1.equals(buffer2)) return false;
// The line above is much slower than the line below.
// It should not be, but it is, possibly because it is
// loading the entire buffer into memory before comparing
// the contents. See the corresponding unit test. EK
for (int i = 0; i < length; i++) if (buffer1.get() != buffer2.get()) return false;
position += length;
length = Math.min(Integer.MAX_VALUE, size1 - position);
cleanDirectByteBuffer(buffer1); buffer1 = null;
cleanDirectByteBuffer(buffer2); buffer2 = null;
}
}
finally
{
// Is is important to clean up so we do not hold any
// file locks, in case the caller wants to do something
// else with the files.
// In terms of functional programming, holding a lock after
// returning to the caller would be an unwelcome side-effect.
cleanDirectByteBuffer(buffer1);
cleanDirectByteBuffer(buffer2);
if (channel1 != null) try
{
channel1.close();
}
catch (IOException e)
{
if (channel2 != null) channel2.close();
throw e;
}
if (channel2 != null) channel2.close();
}
return true;
}
|
java
|
{
"resource": ""
}
|
q180768
|
Files.cleanDirectByteBuffer
|
test
|
public static void cleanDirectByteBuffer(final ByteBuffer byteBuffer)
{
if (byteBuffer == null) return;
if (!byteBuffer.isDirect())
throw new IllegalArgumentException("byteBuffer isn't direct!");
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
try
{
Method cleanerMethod = byteBuffer.getClass().getMethod("cleaner");
cleanerMethod.setAccessible(true);
Object cleaner = cleanerMethod.invoke(byteBuffer);
Method cleanMethod = cleaner.getClass().getMethod("clean");
cleanMethod.setAccessible(true);
cleanMethod.invoke(cleaner);
}
catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e)
{
throw new RuntimeException("Could not clean MappedByteBuffer -- File may still be locked!");
}
return null; // nothing to return
}
});
}
|
java
|
{
"resource": ""
}
|
q180769
|
TransactionalHashMap.validEntry
|
test
|
private boolean validEntry(final Entry<K,V> entry)
{
if (auto_commit || entry == null)
return (entry != null);
String id = getCurrentThreadId();
return !((entry.is(Entry.DELETED, id)) ||
(entry.is(Entry.ADDED, null) && entry.is(Entry.NO_CHANGE, id)));
}
|
java
|
{
"resource": ""
}
|
q180770
|
TransactionalHashMap.maskNull
|
test
|
@SuppressWarnings("unchecked")
static <T> T maskNull(T key)
{
return (key == null ? (T)NULL_KEY : key);
}
|
java
|
{
"resource": ""
}
|
q180771
|
TransactionalHashMap.eq
|
test
|
static boolean eq(Object x, Object y)
{
return x == y || x.equals(y);
}
|
java
|
{
"resource": ""
}
|
q180772
|
TransactionalHashMap.getEntry
|
test
|
Entry<K,V> getEntry(Object key)
{
Object k = maskNull(key);
int hash = hash(k);
int i = indexFor(hash, table.length);
Entry<K,V> e = table[i];
while (e != null && !(e.hash == hash && validEntry(e) && eq(k, e.key)))
e = e.next;
return e;
}
|
java
|
{
"resource": ""
}
|
q180773
|
TransactionalHashMap.resize
|
test
|
@SuppressWarnings("unchecked")
void resize(int newCapacity)
{
Entry<K,V>[] oldTable = table;
int oldCapacity = oldTable.length;
if (oldCapacity == MAXIMUM_CAPACITY)
{
threshold = Integer.MAX_VALUE;
return;
}
Entry<K,V>[] newTable = new Entry[newCapacity];
transfer(newTable);
table = newTable;
threshold = (int)(newCapacity * loadFactor);
}
|
java
|
{
"resource": ""
}
|
q180774
|
TransactionalHashMap.putAll
|
test
|
@Override
public void putAll(Map<? extends K, ? extends V> m)
{
int numKeysToBeAdded = m.size();
if (numKeysToBeAdded == 0)
return;
/*
* Expand the map if the map if the number of mappings to be added
* is greater than or equal to threshold. This is conservative; the
* obvious condition is (m.size() + size) >= threshold, but this
* condition could result in a map with twice the appropriate capacity,
* if the keys to be added overlap with the keys already in this map.
* By using the conservative calculation, we subject ourself
* to at most one extra resize.
*/
if (numKeysToBeAdded > threshold)
{
int targetCapacity = (int)(numKeysToBeAdded / loadFactor + 1);
if (targetCapacity > MAXIMUM_CAPACITY)
targetCapacity = MAXIMUM_CAPACITY;
int newCapacity = table.length;
while (newCapacity < targetCapacity)
newCapacity <<= 1;
if (newCapacity > table.length)
resize(newCapacity);
}
for (Iterator<? extends Map.Entry<? extends K, ? extends V>> i = m.entrySet().iterator(); i.hasNext(); )
{
Map.Entry<? extends K, ? extends V> e = i.next();
put(e.getKey(), e.getValue());
}
}
|
java
|
{
"resource": ""
}
|
q180775
|
TransactionalHashMap.remove
|
test
|
@Override
public V remove(Object key) throws ConcurrentModificationException
{
Entry<K,V> e = removeEntryForKey(key);
return (e == null ? null : e.value);
}
|
java
|
{
"resource": ""
}
|
q180776
|
TransactionalHashMap.removeEntryForKey
|
test
|
Entry<K,V> removeEntryForKey(Object key) throws ConcurrentModificationException
{
Object k = maskNull(key);
int hash = hash(k);
int i = indexFor(hash, table.length);
Entry<K,V> prev = table[i];
Entry<K,V> e = prev;
while (e != null)
{
Entry<K,V> next = e.next;
if (e.hash == hash && validEntry(e) && eq(k, e.key))
{
if (e.is(Entry.DELETED, null) && !e.is(Entry.DELETED, getCurrentThreadId()))
throw new ConcurrentModificationException();
if (auto_commit)
{
modCount++;
size--;
if (prev == e)
table[i] = next;
else
prev.next = next;
return e;
}
else
e.setStatus(Entry.DELETED, getCurrentThreadId());
}
prev = e;
e = next;
}
return e;
}
|
java
|
{
"resource": ""
}
|
q180777
|
TransactionalHashMap.removeMapping
|
test
|
@SuppressWarnings("unchecked")
Entry<K,V> removeMapping(Object o)
{
if (!(o instanceof Map.Entry))
return null;
Map.Entry<K,V> entry = (Map.Entry<K,V>)o;
Object k = maskNull(entry.getKey());
int hash = hash(k);
int i = indexFor(hash, table.length);
Entry<K,V> prev = table[i];
Entry<K,V> e = prev;
while (e != null)
{
Entry<K,V> next = e.next;
if (e.hash == hash && validEntry(e) && e.equals(entry))
{
if (auto_commit)
{
modCount++;
size--;
if (prev == e)
table[i] = next;
else
prev.next = next;
}
else
e.setStatus(Entry.DELETED, getCurrentThreadId());
return e;
}
prev = e;
e = next;
}
return e;
}
|
java
|
{
"resource": ""
}
|
q180778
|
TransactionalHashMap.addEntry
|
test
|
void addEntry(int hash, K key, V value, int bucketIndex)
{
table[bucketIndex] = new Entry<K,V>(hash, key, value, table[bucketIndex]);
if (!auto_commit)
table[bucketIndex].setStatus(Entry.ADDED, getCurrentThreadId());
if (size++ >= threshold)
resize(2 * table.length);
}
|
java
|
{
"resource": ""
}
|
q180779
|
AugmentedMap.createDelegate
|
test
|
private static <K, V> ImmutableMap<K, V> createDelegate(
final Map<K, V> base,
final Set<? extends K> keys,
final Function<K, V> augmentation
) {
final ImmutableMap.Builder<K, V> builder = ImmutableMap.builder();
builder.putAll(base);
keys.stream()
.filter(key -> !base.containsKey(key))
.forEach(key -> builder.put(key, augmentation.apply(key)));
return builder.build();
}
|
java
|
{
"resource": ""
}
|
q180780
|
StringUtils.xmlAttribEncodeBinary
|
test
|
private static String xmlAttribEncodeBinary(String value) {
StringBuilder s = new StringBuilder();
char buf[] = value.toCharArray();
for (char c : buf) {
switch (c) {
case '<':
s.append("<");
break;
case '>':
s.append(">");
break;
case '&':
s.append("&");
break;
case '"':
s.append(""");
break;
case '\'':
s.append("'");
break;
default:
if (c <= 0x1f || (0x7f <= c && c <= 0x9f)) { // includes \t, \n,
// \r
s.append("&#x");
s.append(String.format("%X", (int) c));
s.append(';');
} else {
s.append(c);
}
}
}
return s.toString();
}
|
java
|
{
"resource": ""
}
|
q180781
|
StringUtils.encodeHex
|
test
|
public static String encodeHex(byte[] bytes) {
StringBuilder hex = new StringBuilder(bytes.length * 2);
for (byte aByte : bytes) {
if (((int) aByte & 0xff) < 0x10) {
hex.append("0");
}
hex.append(Integer.toString((int) aByte & 0xff, 16));
}
return hex.toString();
}
|
java
|
{
"resource": ""
}
|
q180782
|
StringUtils.encodeBase64
|
test
|
public static String encodeBase64(String data) {
byte[] bytes = null;
try {
bytes = data.getBytes("ISO-8859-1");
} catch (UnsupportedEncodingException uee) {
throw new IllegalStateException(uee);
}
return encodeBase64(bytes);
}
|
java
|
{
"resource": ""
}
|
q180783
|
StringUtils.encodeBase64
|
test
|
public static String encodeBase64(byte[] data, int offset, int len,
boolean lineBreaks) {
return Base64.encodeBytes(data, offset, len,
(lineBreaks ? Base64.NO_OPTIONS : Base64.DONT_BREAK_LINES));
}
|
java
|
{
"resource": ""
}
|
q180784
|
CounterIterativeCallback.iterate
|
test
|
@Override
public Integer iterate(final FilterableCollection<? extends T> c)
{
checkUsed();
// No point doing the iteration. Just return size of collection.
count = c.size();
return count;
}
|
java
|
{
"resource": ""
}
|
q180785
|
CommandHandler.setTrackSelectorController
|
test
|
public void setTrackSelectorController(Consumer<TrackInfo> controller) {
if (controller == null)
return;
selectTrack = controller;
capabilities.setAbleToSelectTrack(true);
}
|
java
|
{
"resource": ""
}
|
q180786
|
CommandHandler.setJumpProgressController
|
test
|
public void setJumpProgressController(Consumer<Progress> controller) {
if (controller == null)
return;
jumpProgress = controller;
capabilities.setAbleToJump(true);
}
|
java
|
{
"resource": ""
}
|
q180787
|
CommandHandler.setPlaybackChangeableController
|
test
|
public void setPlaybackChangeableController(Consumer<String> controller) {
if (controller == null)
return;
changePlayback = controller;
capabilities.setPlaybackChangeable(true);
}
|
java
|
{
"resource": ""
}
|
q180788
|
CommandHandler.setVolumeChangeableController
|
test
|
public void setVolumeChangeableController(Consumer<Volume> controller) {
if (controller == null)
return;
changeVolume = controller;
capabilities.setChangeVolume(true);
}
|
java
|
{
"resource": ""
}
|
q180789
|
CommandHandler.broadcastAvailablePlaylists
|
test
|
public void broadcastAvailablePlaylists(Supplier<List<String>> availablePlaylist, Function<String, Playlist> playlistForNameFunction) {
if (availablePlaylist == null || playlistForNameFunction == null)
return;
this.availablePlaylist = availablePlaylist;
this.playlistForNameFunction = playlistForNameFunction;
capabilities.setBroadcasting(true);
}
|
java
|
{
"resource": ""
}
|
q180790
|
CommandHandler.handleCommandResources
|
test
|
public void handleCommandResources(EventModel eventModel) {
List<ResourceModel<String>> resourceModels = eventModel.getListResourceContainer()
.provideResource(CommandResource.ResourceID)
.stream()
.filter(resourceModel -> resourceModel.getResource() instanceof String)
.map(resourceModel -> {
try {
//noinspection unchecked
return (ResourceModel<String>) resourceModel;
} catch (ClassCastException e) {
return null;
}
})
.filter(Objects::nonNull)
.collect(Collectors.toList());
for (ResourceModel<String> resourceModel : resourceModels) {
if (!CommandResource.verifyCommand(resourceModel.getResource()))
continue;
if (!CommandResource.verifyCapabilities(resourceModel.getResource(), capabilities)) {
musicHelper.playerError(PlayerError.ERROR_NOT_ABLE + "command: " + resourceModel.getResource(),
resourceModel.getProvider());
continue;
}
switch (resourceModel.getResource()) {
case CommandResource.PLAY: if (!musicProvider.isPlaying())
playPause.accept(resourceModel.getResource());
break;
case CommandResource.PAUSE: if (musicProvider.isPlaying())
playPause.accept(resourceModel.getResource());
break;
case CommandResource.SELECT_TRACK: handleSelectTrack(eventModel, resourceModel);
break;
case CommandResource.NEXT: nextPrevious.accept(resourceModel.getResource());
break;
case CommandResource.PREVIOUS: nextPrevious.accept(resourceModel.getResource());
break;
case CommandResource.JUMP: handleJump(eventModel, resourceModel);
break;
case CommandResource.CHANGE_PLAYBACK: changePlayback.accept(resourceModel.getResource());
break;
case CommandResource.CHANGE_VOLUME: handleVolume(eventModel, resourceModel);
break;
case CommandResource.STOP: stopCallback.run();
break;
}
}
}
|
java
|
{
"resource": ""
}
|
q180791
|
CommandHandler.handleVolume
|
test
|
private void handleVolume(EventModel eventModel, ResourceModel<String> resourceModel) {
Optional<Volume> volumeResource = VolumeResource.getVolume(eventModel);
if (!volumeResource.isPresent()) {
musicHelper.playerError(PlayerError.ERROR_ILLEGAL + "command: " + resourceModel.getResource() + "missing resource",
resourceModel.getProvider());
}
changeVolume.accept(volumeResource.get());
}
|
java
|
{
"resource": ""
}
|
q180792
|
CommandHandler.handleJump
|
test
|
private void handleJump(EventModel eventModel, ResourceModel<String> resourceModel) {
Optional<Progress> progress = ProgressResource.getProgress(eventModel);
if (!progress.isPresent()) {
musicHelper.playerError(PlayerError.ERROR_ILLEGAL + "command: " + resourceModel.getResource() + "missing resource",
resourceModel.getProvider());
}
jumpProgress.accept(progress.get());
}
|
java
|
{
"resource": ""
}
|
q180793
|
CommandHandler.handleSelectTrack
|
test
|
private void handleSelectTrack(EventModel eventModel, ResourceModel<String> resourceModel) {
Optional<TrackInfo> trackInfo = TrackInfoResource.getTrackInfo(eventModel);
if (!trackInfo.isPresent()) {
musicHelper.playerError(PlayerError.ERROR_ILLEGAL + "command: " + resourceModel.getResource() + "missing resource",
resourceModel.getProvider());
}
selectTrack.accept(trackInfo.get());
}
|
java
|
{
"resource": ""
}
|
q180794
|
CacheManagerServiceImpl.getThreadCache
|
test
|
@SuppressWarnings("unchecked")
private <V> Cache<V> getThreadCache(String name) {
Map<String, Cache<?>> threadCacheMap = threadCacheMapHolder.get();
Cache<V> threadCache = (Cache<V>) threadCacheMap.get(name);
if (threadCache == null) {
threadCache = new MapCacheImpl<V>();
threadCacheMap.put(name, threadCache);
}
return threadCache;
}
|
java
|
{
"resource": ""
}
|
q180795
|
CacheManagerServiceImpl.getRequestCache
|
test
|
@SuppressWarnings("unchecked")
private <V> Cache<V> getRequestCache(String name) {
Map<String, Cache<?>> requestCacheMap = requestCacheMapHolder.get();
Cache<V> requestCache = (Cache<V>) requestCacheMap.get(name);
if (requestCache == null) {
requestCache = new MapCacheImpl<V>();
requestCacheMap.put(name, requestCache);
}
return requestCache;
}
|
java
|
{
"resource": ""
}
|
q180796
|
StorageClientUtils.getAltField
|
test
|
public static String getAltField(String field, String streamId) {
if (streamId == null) {
return field;
}
return field + "/" + streamId;
}
|
java
|
{
"resource": ""
}
|
q180797
|
StorageClientUtils.getFilterMap
|
test
|
@SuppressWarnings("unchecked")
public static <K, V> Map<K, V> getFilterMap(Map<K, V> source, Map<K, V> modified, Set<K> include, Set<K> exclude, boolean includingRemoveProperties ) {
if ((modified == null || modified.size() == 0) && (include == null) && ( exclude == null || exclude.size() == 0)) {
if ( source instanceof ImmutableMap ) {
return source;
} else {
return ImmutableMap.copyOf(source);
}
}
Builder<K, V> filteredMap = new ImmutableMap.Builder<K, V>();
for (Entry<K, V> e : source.entrySet()) {
K k = e.getKey();
if (include == null || include.contains(k)) {
if (exclude == null || !exclude.contains(k)) {
if ( modified != null && modified.containsKey(k) ) {
V o = modified.get(k);
if (o instanceof Map) {
filteredMap.put(k,
(V) getFilterMap((Map<K, V>) o, null, null, exclude, includingRemoveProperties));
} else if ( includingRemoveProperties ) {
filteredMap.put(k, o);
} else if ( !(o instanceof RemoveProperty) ) {
filteredMap.put(k, o);
}
} else {
Object o = e.getValue();
if (o instanceof Map) {
filteredMap.put(k,
(V) getFilterMap((Map<K, V>) e.getValue(), null, null, exclude, includingRemoveProperties));
} else {
filteredMap.put(k, e.getValue());
}
}
}
}
}
if ( modified != null ) {
// process additions
for (Entry<K, V> e : modified.entrySet()) {
K k = e.getKey();
if ( !source.containsKey(k)) {
V v = e.getValue();
if ( !(v instanceof RemoveProperty) && v != null ) {
filteredMap.put(k,v);
}
}
}
}
return filteredMap.build();
}
|
java
|
{
"resource": ""
}
|
q180798
|
StorageClientUtils.shardPath
|
test
|
public static String shardPath(String id) {
String hash = insecureHash(id);
return hash.substring(0, 2) + "/" + hash.substring(2, 4) + "/" + hash.substring(4, 6) + "/"
+ id;
}
|
java
|
{
"resource": ""
}
|
q180799
|
StorageClientUtils.adaptToSession
|
test
|
public static Session adaptToSession(Object source) {
if (source instanceof SessionAdaptable) {
return ((SessionAdaptable) source).getSession();
} else {
// assume this is a JCR session of someform, in which case there
// should be a SparseUserManager
Object userManager = safeMethod(source, "getUserManager", new Object[0], new Class[0]);
if (userManager != null) {
return (Session) safeMethod(userManager, "getSession", new Object[0], new Class[0]);
}
return null;
}
}
|
java
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.