_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q180800
StorageClientUtils.safeMethod
test
private static Object safeMethod(Object target, String methodName, Object[] args, @SuppressWarnings("rawtypes") Class[] argsTypes) { if (target != null) { try { Method m = target.getClass().getMethod(methodName, argsTypes); if (!m.isAccessible()) { m.setAccessible(true); } return m.invoke(target, args); } catch (Throwable e) { LOGGER.info("Failed to invoke method " + methodName + " " + target, e); } } return null; }
java
{ "resource": "" }
q180801
StorageClientUtils.deleteTree
test
public static void deleteTree(ContentManager contentManager, String path) throws AccessDeniedException, StorageClientException { Content content = contentManager.get(path); if (content != null) { for (String childPath : content.listChildPaths()) { deleteTree(contentManager, childPath); } } contentManager.delete(path); }
java
{ "resource": "" }
q180802
AbstractDao.updateOne
test
@Override public void updateOne(E object, String... properties) { if (object.getId() == null) { throw new RuntimeException("Not a Persisted entity"); } if (properties == null || properties.length == 0) { entityManager.merge(object); return; } // for performance reason its better to mix getting fields, their values // and making query all in one loop // in one iteration StringBuilder sb = new StringBuilder(); sb.append("Update " + clazz.getName() + " SET "); // cache of fieldName --> value Map<String, Object> cache = new HashMap<String, Object>(); for (String prop : properties) { try { Field field = object.getClass().getDeclaredField(prop); field.setAccessible(true); Object value = field.get(object); if (value instanceof Collection) { // value = new LinkedList<>((Collection< ? extends Object>) value); throw new RuntimeException("Collection property is not suppotred."); } cache.put(prop, value); // ignore first comma if (cache.size() > 1) { sb.append(" ,"); } sb.append(prop); sb.append(" = :"); sb.append(prop); } catch (Exception e) { // TODO: use fine grain exceptions // FIX: NEXT RELEASE I hope :) throw new RuntimeException(e); } } // this means nothing will be updated so hitting db is unnecessary if (cache.size() == 0) return; sb.append(" WHERE id = " + object.getId()); Query query = entityManager.createQuery(sb.toString()); for (Entry<String, Object> entry : cache.entrySet()) { query.setParameter(entry.getKey(), entry.getValue()); } query.executeUpdate(); }
java
{ "resource": "" }
q180803
KeepAliveManager.setPingInterval
test
public void setPingInterval(long newPingInterval) { if (pingInterval == newPingInterval) return; // Enable the executor service if (newPingInterval > 0) enableExecutorService(); pingInterval = newPingInterval; if (pingInterval < 0) { stopPinging(); } else { schedulePingServerTask(); } }
java
{ "resource": "" }
q180804
KeepAliveManager.schedulePingServerTask
test
private synchronized void schedulePingServerTask() { enableExecutorService(); stopPingServerTask(); if (pingInterval > 0) { periodicPingTask = periodicPingExecutorService.schedule( new Runnable() { @Override public void run() { Ping ping = new Ping(); PacketFilter responseFilter = new PacketIDFilter( ping.getID()); Connection connection = weakRefConnection.get(); final PacketCollector response = pingFailedListeners .isEmpty() ? null : connection .createPacketCollector(responseFilter); connection.sendPacket(ping); if (response != null) { // Schedule a collector for the ping reply, // notify listeners if none is received. periodicPingExecutorService.schedule( new Runnable() { @Override public void run() { Packet result = response .nextResult(1); // Stop queuing results response.cancel(); // The actual result of the // reply can be ignored since we // only care if we actually got // one. if (result == null) { for (PingFailedListener listener : pingFailedListeners) { listener.pingFailed(); } } } }, SmackConfiguration .getPacketReplyTimeout(), TimeUnit.MILLISECONDS); } } }, getPingInterval(), TimeUnit.MILLISECONDS); } }
java
{ "resource": "" }
q180805
ExecS_CliParser.addAllOptions
test
public ExecS_CliParser addAllOptions(ApplicationOption<?>[] options){ if(options!=null){ for(ApplicationOption<?> option : options){ this.addOption(option); } } return this; }
java
{ "resource": "" }
q180806
ExecS_CliParser.hasOption
test
public boolean hasOption(Option option){ if(option==null){ return false; } if(this.usedOptions.contains(option.getOpt())){ return true; } if(this.usedOptions.contains(option.getLongOpt())){ return true; } return false; }
java
{ "resource": "" }
q180807
ExecS_CliParser.parse
test
public ParseException parse(String[] args){ ParseException ret = null; CommandLineParser parser = new DefaultParser(); try{ this.cmdLine = parser.parse(this.options, args); } catch(ParseException pe){ ret = pe; } return ret; }
java
{ "resource": "" }
q180808
ExecS_CliParser.usage
test
public void usage(String appName){ HelpFormatter formatter=new HelpFormatter(); formatter.printHelp(appName, null, this.options, null, false); }
java
{ "resource": "" }
q180809
ExecS_CliParser.doParse
test
static int doParse(String[] args, ExecS_CliParser cli, String appName){ Exception err = cli.parse(args); if(err!=null){ System.err.println(appName + ": error parsing command line -> " + err.getMessage()); return -1; } return 0; }
java
{ "resource": "" }
q180810
XMPPConnection.initConnection
test
private void initConnection() throws XMPPException { boolean isFirstInitialization = packetReader == null || packetWriter == null; compressionHandler = null; serverAckdCompression = false; // Set the reader and writer instance variables initReaderAndWriter(); try { if (isFirstInitialization) { packetWriter = new PacketWriter(this); packetReader = new PacketReader(this); // If debugging is enabled, we should start the thread that will // listen for // all packets and then log them. if (config.isDebuggerEnabled()) { addPacketListener(debugger.getReaderListener(), null); if (debugger.getWriterListener() != null) { addPacketSendingListener(debugger.getWriterListener(), null); } } } else { packetWriter.init(); packetReader.init(); } // Start the packet writer. This will open a XMPP stream to the // server packetWriter.startup(); // Start the packet reader. The startup() method will block until we // get an opening stream packet back from server. packetReader.startup(); // Make note of the fact that we're now connected. connected = true; if (isFirstInitialization) { // Notify listeners that a new connection has been established for (ConnectionCreationListener listener : getConnectionCreationListeners()) { listener.connectionCreated(this); } } } catch (XMPPException ex) { // An exception occurred in setting up the connection. Make sure we // shut down the // readers and writers and close the socket. if (packetWriter != null) { try { packetWriter.shutdown(); } catch (Throwable ignore) { /* ignore */ } packetWriter = null; } if (packetReader != null) { try { packetReader.shutdown(); } catch (Throwable ignore) { /* ignore */ } packetReader = null; } if (reader != null) { try { reader.close(); } catch (Throwable ignore) { /* ignore */ } reader = null; } if (writer != null) { try { writer.close(); } catch (Throwable ignore) { /* ignore */ } writer = null; } if (socket != null) { try { socket.close(); } catch (Exception e) { /* ignore */ } socket = null; } this.setWasAuthenticated(authenticated); authenticated = false; connected = false; throw ex; // Everything stoppped. Now throw the exception. } }
java
{ "resource": "" }
q180811
XMPPConnection.startTLSReceived
test
void startTLSReceived(boolean required) { if (required && config.getSecurityMode() == ConnectionConfiguration.SecurityMode.disabled) { notifyConnectionError(new IllegalStateException( "TLS required by server but not allowed by connection configuration")); return; } if (config.getSecurityMode() == ConnectionConfiguration.SecurityMode.disabled) { // Do not secure the connection using TLS since TLS was disabled return; } try { writer.write("<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\"/>"); writer.flush(); } catch (IOException e) { notifyConnectionError(e); } }
java
{ "resource": "" }
q180812
XMPPConnection.maybeGetCompressionHandler
test
private XMPPInputOutputStream maybeGetCompressionHandler() { if (compressionMethods != null) { for (XMPPInputOutputStream handler : compressionHandlers) { if (!handler.isSupported()) continue; String method = handler.getCompressionMethod(); if (compressionMethods.contains(method)) return handler; } } return null; }
java
{ "resource": "" }
q180813
XMPPConnection.requestStreamCompression
test
private void requestStreamCompression(String method) { try { writer.write("<compress xmlns='http://jabber.org/protocol/compress'>"); writer.write("<method>" + method + "</method></compress>"); writer.flush(); } catch (IOException e) { notifyConnectionError(e); } }
java
{ "resource": "" }
q180814
XMPPConnection.startStreamCompression
test
void startStreamCompression() throws Exception { serverAckdCompression = true; // Initialize the reader and writer with the new secured version initReaderAndWriter(); // Set the new writer to use packetWriter.setWriter(writer); // Send a new opening stream to the server packetWriter.openStream(); // Notify that compression is being used synchronized (this) { this.notify(); } }
java
{ "resource": "" }
q180815
XMPPConnection.notifyConnectionError
test
synchronized void notifyConnectionError(Exception e) { // Listeners were already notified of the exception, return right here. if ((packetReader == null || packetReader.done) && (packetWriter == null || packetWriter.done)) return; if (packetReader != null) packetReader.done = true; if (packetWriter != null) packetWriter.done = true; // Closes the connection temporary. A reconnection is possible shutdown(new Presence(Presence.Type.unavailable)); // Notify connection listeners of the error. for (ConnectionListener listener : getConnectionListeners()) { try { listener.connectionClosedOnError(e); } catch (Exception e2) { // Catch and print any exception so we can recover // from a faulty listener e2.printStackTrace(); } } }
java
{ "resource": "" }
q180816
XMPPConnection.notifyReconnection
test
protected void notifyReconnection() { // Notify connection listeners of the reconnection. for (ConnectionListener listener : getConnectionListeners()) { try { listener.reconnectionSuccessful(); } catch (Exception e) { // Catch and print any exception so we can recover // from a faulty listener e.printStackTrace(); } } }
java
{ "resource": "" }
q180817
SASLAuthentication.registerSASLMechanism
test
public static void registerSASLMechanism(String name, Class<? extends SASLMechanism> mClass) { implementedMechanisms.put(name, mClass); }
java
{ "resource": "" }
q180818
SASLAuthentication.getRegisterSASLMechanisms
test
public static List<Class<? extends SASLMechanism>> getRegisterSASLMechanisms() { List<Class<? extends SASLMechanism>> answer = new ArrayList<Class<? extends SASLMechanism>>(); for (String mechanismsPreference : mechanismsPreferences) { answer.add(implementedMechanisms.get(mechanismsPreference)); } return answer; }
java
{ "resource": "" }
q180819
EventBehaviourController.getOutputPluginBehaviour
test
@Override public HashMap<Integer, List<Identification>> getOutputPluginBehaviour(List<Identification> identifications) { if(outputPluginBehaviour == null) return new HashMap<>(); return outputPluginBehaviour.apply(identifications); }
java
{ "resource": "" }
q180820
NakamuraMain.info
test
static void info(String message, Throwable t) { log(System.out, "*INFO*", message, t); }
java
{ "resource": "" }
q180821
NakamuraMain.error
test
static void error(String message, Throwable t) { log(System.err, "*ERROR*", message, t); }
java
{ "resource": "" }
q180822
NakamuraMain.log
test
private static void log(PrintStream out, String prefix, String message, Throwable t) { final StringBuilder linePrefixBuilder = new StringBuilder(); synchronized (fmt) { linePrefixBuilder.append(fmt.format(new Date())); } linePrefixBuilder.append(prefix); linePrefixBuilder.append(" ["); linePrefixBuilder.append(Thread.currentThread().getName()); linePrefixBuilder.append("] "); final String linePrefix = linePrefixBuilder.toString(); out.print(linePrefix); out.println(message); if (t != null) { t.printStackTrace(new PrintStream(out) { @Override public void println(String x) { synchronized (this) { print(linePrefix); super.println(x); flush(); } } }); } }
java
{ "resource": "" }
q180823
StartEvent.createStartEvent
test
public static Optional<StartEvent> createStartEvent(Identification source) { try { StartEvent startRequest = new StartEvent(source); return Optional.of(startRequest); } catch (IllegalArgumentException e) { return Optional.empty(); } }
java
{ "resource": "" }
q180824
StartEvent.createStartEvent
test
public static Optional<StartEvent> createStartEvent(Identification source, boolean isUsingJava) { try { StartEvent startEvent; if (isUsingJava) { startEvent = new StartEvent(source); } else { startEvent = new StartEvent(source, IS_USING_NON_JAVA_OUTPUT); } return Optional.of(startEvent); } catch (IllegalArgumentException e) { return Optional.empty(); } }
java
{ "resource": "" }
q180825
ObservableWriter.notifyListeners
test
private void notifyListeners(String str) { WriterListener[] writerListeners = null; synchronized (listeners) { writerListeners = new WriterListener[listeners.size()]; listeners.toArray(writerListeners); } for (int i = 0; i < writerListeners.length; i++) { writerListeners[i].write(str); } }
java
{ "resource": "" }
q180826
ListResourceProviderImpl.providesResource
test
@Override public boolean providesResource(ResourceModel resource) { return resources.stream() .map(ResourceModel::getResourceID) .anyMatch(resourceS -> resourceS.equals(resource.getResourceID())); }
java
{ "resource": "" }
q180827
ListResourceProviderImpl.containsResourcesFromSource
test
@Override public boolean containsResourcesFromSource(String sourceID) { return resources.stream() .map(ResourceModel::getResourceID) .anyMatch(source -> source.equals(sourceID)); }
java
{ "resource": "" }
q180828
ListResourceProviderImpl.providesResource
test
@Override public boolean providesResource(List<String> resourcesIDs) { return resources.stream() .map(ResourceModel::getResourceID) .anyMatch(resourcesIDs::contains); }
java
{ "resource": "" }
q180829
ListResourceProviderImpl.provideResource
test
@Override public List<ResourceModel> provideResource(String[] resourceIDs) { return resources.stream() .filter(resource -> Arrays.stream(resourceIDs) .anyMatch(resourceID -> resourceID.equals(resource.getResourceID()))) .collect(Collectors.toList()); }
java
{ "resource": "" }
q180830
CachingManagerImpl.getCached
test
protected Map<String, Object> getCached(String keySpace, String columnFamily, String key) throws StorageClientException { Map<String, Object> m = null; String cacheKey = getCacheKey(keySpace, columnFamily, key); CacheHolder cacheHolder = getFromCacheInternal(cacheKey); if (cacheHolder != null) { m = cacheHolder.get(); if (m != null) { LOGGER.debug("Cache Hit {} {} {} ", new Object[] { cacheKey, cacheHolder, m }); } } if (m == null) { m = client.get(keySpace, columnFamily, key); if (m != null) { LOGGER.debug("Cache Miss, Found Map {} {}", cacheKey, m); } putToCacheInternal(cacheKey, new CacheHolder(m), true); } return m; }
java
{ "resource": "" }
q180831
CachingManagerImpl.getCacheKey
test
private String getCacheKey(String keySpace, String columnFamily, String key) throws StorageClientException { if (client instanceof RowHasher) { return ((RowHasher) client).rowHash(keySpace, columnFamily, key); } return keySpace + ":" + columnFamily + ":" + key; }
java
{ "resource": "" }
q180832
CachingManagerImpl.removeCached
test
protected void removeCached(String keySpace, String columnFamily, String key) throws StorageClientException { if (sharedCache != null) { // insert a replacement. This should cause an invalidation message // to propagate in the cluster. final String cacheKey = getCacheKey(keySpace, columnFamily, key); putToCacheInternal(cacheKey, new CacheHolder(null, managerId), false); LOGGER.debug("Marked as deleted in Cache {} ", cacheKey); if (client instanceof Disposer) { // we might want to change this to register the action as a // commit handler rather than a disposable. // it depends on if we think the delete is a transactional thing // or a operational cache thing. // at the moment, I am leaning towards an operational cache // thing, since regardless of if // the session commits or not, we want this to dispose when the // session is closed, or commits. ((Disposer) client).registerDisposable(new Disposable() { @Override public void setDisposer(Disposer disposer) { } @Override public void close() { CacheHolder ch = sharedCache.get(cacheKey); if (ch != null && ch.wasLockedTo(managerId)) { sharedCache.remove(cacheKey); LOGGER.debug("Removed deleted marker from Cache {} ", cacheKey); } } }); } } client.remove(keySpace, columnFamily, key); }
java
{ "resource": "" }
q180833
CachingManagerImpl.putCached
test
protected void putCached(String keySpace, String columnFamily, String key, Map<String, Object> encodedProperties, boolean probablyNew) throws StorageClientException { String cacheKey = null; if (sharedCache != null) { cacheKey = getCacheKey(keySpace, columnFamily, key); } if (sharedCache != null && !probablyNew) { CacheHolder ch = getFromCacheInternal(cacheKey); if (ch != null && ch.isLocked(this.managerId)) { LOGGER.debug("Is Locked {} ", ch); return; // catch the case where another method creates while // something is in the cache. // this is a big assumption since if the item is not in the // cache it will get updated // there is no difference in sparsemap between create and // update, they are all insert operations // what we are really saying here is that inorder to update the // item you have to have just got it // and if you failed to get it, your update must have been a // create operation. As long as the dwell time // in the cache is longer than the lifetime of an active session // then this will be true. // if the lifetime of an active session is longer (like with a // long running background operation) // then you should expect to see race conditions at this point // since the marker in the cache will have // gone, and the marker in the database has gone, so the put // operation, must be a create operation. // To change this behavior we would need to differentiate more // strongly between new and update and change // probablyNew into certainlyNew, but that would probably break // the BASIC assumption of the whole system. // Update 2011-12-06 related to issue 136 // I am not certain this code is correct. What happens if the // session wants to remove and then add items. // the session will never get past this point, since sitting in // the cache is a null CacheHolder preventing the session // removing then adding. // also, how long should the null cache holder be placed in // there for ? // I think the solution is to bind the null Cache holder to the // instance of the caching manager that created it, // let the null Cache holder last for 10s, and during that time // only the CachingManagerImpl that created it can remove it. } } LOGGER.debug("Saving {} {} {} {} ", new Object[] { keySpace, columnFamily, key, encodedProperties }); client.insert(keySpace, columnFamily, key, encodedProperties, probablyNew); if (sharedCache != null) { // if we just added a value in, remove the key so that any stale // state (including a previously deleted object is removed) sharedCache.remove(cacheKey); } }
java
{ "resource": "" }
q180834
CF_Locator.getCfLocations
test
public Map<URI, String> getCfLocations(){ if(this.needsReRun==true){ this.locationMap.clear(); String pathSep = System.getProperty("path.separator"); String classpath = System.getProperty("java.class.path"); StringTokenizer st = new StringTokenizer(classpath, pathSep); File file = null; while(st.hasMoreTokens()){ String path = st.nextToken(); file = new File(path); this.include(file); } } this.needsReRun = false; return this.locationMap; }
java
{ "resource": "" }
q180835
CF_Locator.include
test
protected final void include(String name, File file){ if(!file.exists()){ return; } if(!file.isDirectory()){ if(this.jarFilter.size()>0){ boolean ok = false; for(String s : this.jarFilter){ if(file.getName().startsWith(s)){ ok = true; } } if(ok==false){ return; } } this.includeJar(file); return; } if(name==null){ name = ""; } else{ name += "."; } File[] dirs = file.listFiles(CF_Utils.DIRECTORIES_ONLY); for(int i=0; i<dirs.length; i++){ try{ this.locationMap.put(new URI("file://" + dirs[i].getCanonicalPath()), name + dirs[i].getName()); } catch(IOException ignore){return;} catch(URISyntaxException ignore){return;} this.include(name + dirs[i].getName(), dirs[i]); } }
java
{ "resource": "" }
q180836
CF_Locator.includeJar
test
private void includeJar(File file){ if(file.isDirectory()){ return; } URL jarURL = null; JarFile jar = null; try{ jarURL = new URL("jar:" + new URL("file:/" + file.getCanonicalPath()).toExternalForm() + "!/"); JarURLConnection conn = (JarURLConnection)jarURL.openConnection(); jar = conn.getJarFile(); } catch(MalformedURLException ignore){return;} catch(IOException ignore){return;} if(jar==null){ return; } try{ this.locationMap.put(jarURL.toURI(), ""); } catch(URISyntaxException ignore){} for(Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements();){ JarEntry entry = e.nextElement(); if(this.pkgFilter!=null && entry.getName().startsWith(this.pkgFilter)){ continue; } if(entry.isDirectory()){ if(entry.getName().toUpperCase(Locale.ENGLISH).equals("META-INF/")){ continue; } try{ this.locationMap.put(new URI(jarURL.toExternalForm() + entry.getName()), CF_Utils.getPkgName(entry)); } catch(URISyntaxException ignore){continue;} } } }
java
{ "resource": "" }
q180837
SmackConfiguration.addSaslMech
test
public static void addSaslMech(String mech) { initialize(); if (!defaultMechs.contains(mech)) { defaultMechs.add(mech); } }
java
{ "resource": "" }
q180838
SmackConfiguration.addSaslMechs
test
public static void addSaslMechs(Collection<String> mechs) { initialize(); for (String mech : mechs) { addSaslMech(mech); } }
java
{ "resource": "" }
q180839
ConsoleDebugger.createDebug
test
private void createDebug() { // Create a special Reader that wraps the main Reader and logs data to // the GUI. ObservableReader debugReader = new ObservableReader(reader); readerListener = new ReaderListener() { public void read(String str) { System.out.println(dateFormatter.format(new Date()) + " RCV (" + connection.hashCode() + "): " + str); } }; debugReader.addReaderListener(readerListener); // Create a special Writer that wraps the main Writer and logs data to // the GUI. ObservableWriter debugWriter = new ObservableWriter(writer); writerListener = new WriterListener() { public void write(String str) { System.out.println(dateFormatter.format(new Date()) + " SENT (" + connection.hashCode() + "): " + str); } }; debugWriter.addWriterListener(writerListener); // Assign the reader/writer objects to use the debug versions. The // packet reader // and writer will use the debug versions when they are created. reader = debugReader; writer = debugWriter; // Create a thread that will listen for all incoming packets and write // them to // the GUI. This is what we call "interpreted" packet data, since it's // the packet // data as Smack sees it and not as it's coming in as raw XML. listener = new PacketListener() { public void processPacket(Packet packet) { if (printInterpreted) { System.out.println(dateFormatter.format(new Date()) + " RCV PKT (" + connection.hashCode() + "): " + packet.toXML()); } } }; connListener = new ConnectionListener() { public void connectionClosed() { System.out.println(dateFormatter.format(new Date()) + " Connection closed (" + connection.hashCode() + ")"); } public void connectionClosedOnError(Exception e) { System.out.println(dateFormatter.format(new Date()) + " Connection closed due to an exception (" + connection.hashCode() + ")"); e.printStackTrace(); } public void reconnectionFailed(Exception e) { System.out.println(dateFormatter.format(new Date()) + " Reconnection failed due to an exception (" + connection.hashCode() + ")"); e.printStackTrace(); } public void reconnectionSuccessful() { System.out.println(dateFormatter.format(new Date()) + " Connection reconnected (" + connection.hashCode() + ")"); } public void reconnectingIn(int seconds) { System.out.println(dateFormatter.format(new Date()) + " Connection (" + connection.hashCode() + ") will reconnect in " + seconds); } }; }
java
{ "resource": "" }
q180840
ProxyClientServiceImpl.activate
test
protected void activate(Map<String, Object> properties) throws Exception { configProperties = properties; String[] safePostProcessorNames = (String[]) configProperties .get(SAFE_POSTPROCESSORS); if (safePostProcessorNames == null) { safeOpenProcessors.add("rss"); safeOpenProcessors.add("trustedLoginTokenProxyPostProcessor"); } else { for (String pp : safePostProcessorNames) { safeOpenProcessors.add(pp); } } // allow communications via a proxy server if command line // java parameters http.proxyHost,http.proxyPort,http.proxyUser, // http.proxyPassword have been provided. String proxyHost = System.getProperty("http.proxyHost", ""); if (!proxyHost.equals("")) { useJreProxy = true; } }
java
{ "resource": "" }
q180841
EventPropertiesAssistant.registerStandardEvents
test
private void registerStandardEvents() { CommonEvents.Descriptors.stopListener(this).ifPresent(this::registerEventListener); CommonEvents.Presence.generalLeavingListener(this).ifPresent(this::registerEventListener); CommonEvents.Presence.generalListener(this).ifPresent(this::registerEventListener); CommonEvents.Presence.leavingListener(this).ifPresent(this::registerEventListener); CommonEvents.Presence.presenceListener(this).ifPresent(this::registerEventListener); CommonEvents.Presence.strictLeavingListener(this).ifPresent(this::registerEventListener); CommonEvents.Presence.strictListener(this).ifPresent(this::registerEventListener); CommonEvents.Response.fullResponseListener(this).ifPresent(this::registerEventListener); CommonEvents.Response.majorResponseListener(this).ifPresent(this::registerEventListener); CommonEvents.Response.minorResponseListener(this).ifPresent(this::registerEventListener); CommonEvents.Type.notificationListener(this).ifPresent(this::registerEventListener); CommonEvents.Type.responseListener(this).ifPresent(this::registerEventListener); }
java
{ "resource": "" }
q180842
EventPropertiesAssistant.registerEventListener
test
public void registerEventListener(EventListener eventListener) { registerEventID(eventListener.getDescription(), eventListener.getDescriptorID(), eventListener.getDescriptor()); }
java
{ "resource": "" }
q180843
EventPropertiesAssistant.registerEventID
test
public void registerEventID(String description, String key, String value) { BufferedWriter bufferedWriter; FileOutputStream out = null; try { out = new FileOutputStream(eventPropertiesPath, true); bufferedWriter = new BufferedWriter(new OutputStreamWriter(out)); doWithLock(out.getChannel(), lock -> { unlockedReloadFile(); if (getEventID(key) != null) { return; } try { bufferedWriter.write("\n\n" + key + "_DESCRIPTION = " + description + "\n" + key + " = " + value); bufferedWriter.flush(); } catch (IOException e) { e.printStackTrace(); } }); } catch (FileNotFoundException e) { error("Unable find file", e); } finally { try { if (out != null) { out.close(); } } catch (IOException e) { error("Unable to close lock", e); } } }
java
{ "resource": "" }
q180844
EventPropertiesAssistant.doWithLock
test
private void doWithLock(FileChannel channel, Consumer<FileLock> consumer) { FileLock lock = null; try { while (lock == null) { try { lock = channel.tryLock(); } catch (OverlappingFileLockException e) { Thread.sleep(500); } } consumer.accept(lock); } catch (IOException | InterruptedException e) { error("Unable to write", e); } finally { try { if (lock != null) { lock.release(); } } catch (IOException e) { error("Unable to close lock", e); } } }
java
{ "resource": "" }
q180845
EventPropertiesAssistant.unregisterEventID
test
public void unregisterEventID(String eventKey) { properties.remove(eventKey + "_DESCRIPTION"); properties.remove(eventKey); FileOutputStream out = null; BufferedReader reader = null; BufferedWriter writer = null; try { out = new FileOutputStream(eventPropertiesPath, true); final File tempFile = new File(eventPropertiesPath + "temp.properties"); final BufferedReader readerFinal = new BufferedReader(new FileReader(eventPropertiesPath)); final BufferedWriter writerFinal = new BufferedWriter(new FileWriter(tempFile)); doWithLock(out.getChannel(), lock -> { unlockedReloadFile(); if (getEventID(eventKey) != null) { return; } try { String currentLine = readerFinal.readLine(); while(currentLine != null) { String trimmedLine = currentLine.trim(); if(trimmedLine.equals(eventKey + "_DESCRIPTION") || trimmedLine.equals(eventKey)) continue; writerFinal.write(currentLine + System.getProperty("line.separator")); currentLine = readerFinal.readLine(); } } catch (IOException e) { e.printStackTrace(); } }); reader = readerFinal; writer = writerFinal; tempFile.renameTo(new File(eventPropertiesPath)); } catch (IOException e) { error("Unable find file", e); } finally { try { if (out != null) { out.close(); } if (writer != null) { writer.close(); } if (reader != null) { reader.close(); } } catch (IOException e) { error("Unable to close lock", e); } } }
java
{ "resource": "" }
q180846
OutputExtensionArgument.canRun
test
@Override public boolean canRun(EventModel event) { //noinspection SimplifiableIfStatement if (event != null) { return event.getListResourceContainer().providesResource(getResourceIdWishList()); } return false; }
java
{ "resource": "" }
q180847
DseUtils.newDseSession
test
public static DseSession newDseSession(DseCluster cluster, String keyspace) { return cluster.connect(StringUtils.isBlank(keyspace) ? null : keyspace); }
java
{ "resource": "" }
q180848
PlayerError.createMusicPlayerError
test
public static Optional<PlayerError> createMusicPlayerError(Identification source, String error) { if (error == null || error.isEmpty()) return Optional.empty(); try { PlayerError playerError = new PlayerError(source); playerError.addResource(new MusicErrorResource(source, error)); return Optional.of(playerError); } catch (IllegalArgumentException e) { return Optional.empty(); } }
java
{ "resource": "" }
q180849
PlayerController.startPlaying
test
public void startPlaying(TrackInfo trackInfo) { Optional<Identification> ownIdentification = IdentificationManagerM.getInstance() .getIdentification(this); Optional<Identification> playerIdentification = IdentificationManagerM.getInstance() .getIdentification(player); if (!ownIdentification.isPresent() || !playerIdentification.isPresent()) { error("unable to obtain identification"); return; } StartMusicRequest.createStartMusicRequest(ownIdentification.get(), playerIdentification.get(), trackInfo, player.isUsingJava) .ifPresent(event -> fire(event, 5)); }
java
{ "resource": "" }
q180850
PlayerController.stopPlaying
test
public void stopPlaying() { Optional<Identification> ownIdentification = IdentificationManagerM.getInstance() .getIdentification(this); Optional<Identification> playerIdentification = IdentificationManagerM.getInstance() .getIdentification(player); if (!ownIdentification.isPresent()|| !playerIdentification.isPresent()) { error("unable to obtain id"); return; } StopMusic.createStopMusic(ownIdentification.get(), playerIdentification.get()) .ifPresent(event -> fire(event, 5)); }
java
{ "resource": "" }
q180851
PlayerController.command
test
public void command(String command, Playlist playlist, Progress progress, TrackInfo trackInfo, Volume volume) { Optional<Identification> ownIdentification = IdentificationManagerM.getInstance() .getIdentification(this); Optional<Identification> playerIdentification = IdentificationManagerM.getInstance() .getIdentification(player); if (!ownIdentification.isPresent()|| !playerIdentification.isPresent()) { error("unable to obtain id"); return; } Optional<PlayerCommand> playerCommand = PlayerCommand.createPlayerCommand(ownIdentification.get(), playerIdentification.get(), command, player.getCapabilities(), getContext()); if (playlist != null) { playerCommand.get().addResource(new PlaylistResource(ownIdentification.get(), playlist)); } if (progress != null) { playerCommand.get().addResource(new ProgressResource(ownIdentification.get(), progress)); } if (trackInfo != null) { playerCommand.get().addResource(new TrackInfoResource(ownIdentification.get(), trackInfo)); } if (volume != null) { playerCommand.get().addResource(new VolumeResource(ownIdentification.get(), volume)); } fire(playerCommand.get(), 5); }
java
{ "resource": "" }
q180852
BroadcasterPlaylist.createPlaylistRequest
test
public static BroadcasterPlaylist createPlaylistRequest(Identification provider, String playlistName) { HashMap<String, Object> hashMap = new HashMap<>(); hashMap.put(RESOURCE_ID, playlistName); return new BroadcasterPlaylist(provider, hashMap); }
java
{ "resource": "" }
q180853
BroadcasterPlaylist.createPlaylistAnswer
test
public static BroadcasterPlaylist createPlaylistAnswer(Identification provider, Playlist playlist) { return new BroadcasterPlaylist(provider, playlist.export()); }
java
{ "resource": "" }
q180854
UrlBuilder.append
test
public UrlBuilder append(boolean encode,String... postFix) { for (String part : postFix) { if(StringUtils.isNotBlank(part)) { if (url.charAt(url.length() - 1) != '/' && !part.startsWith("/")) { url.append('/'); } if(encode) { try { url.append(URLEncoder.encode(part, "UTF-8")); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } } else { url.append(part); } } } return this; }
java
{ "resource": "" }
q180855
UrlBuilder.queryParam
test
public UrlBuilder queryParam(String name, Boolean value) { if(value != null) { return queryParam(name, value.toString()); } else { return null; } }
java
{ "resource": "" }
q180856
UrlBuilder.queryParam
test
public UrlBuilder queryParam(String name, Number value) { if(value != null) { return queryParam(name, value.toString()); } else { return null; } }
java
{ "resource": "" }
q180857
UrlBuilder.queryParam
test
public UrlBuilder queryParam(String name, String value) { return queryParam(name, value, true); }
java
{ "resource": "" }
q180858
UrlBuilder.queryParam
test
public UrlBuilder queryParam(String name, String value, boolean encode) { if (StringUtils.isNotEmpty(value)) { if (encode) { try { value = URLEncoder.encode(value, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } } params.add(new EntryImpl(name, value)); } return this; }
java
{ "resource": "" }
q180859
PlaylistResource.getPlaylist
test
public static Optional<Playlist> getPlaylist(EventModel eventModel) { if (eventModel.getListResourceContainer().containsResourcesFromSource(ID)) { return eventModel .getListResourceContainer() .provideResource(ID) .stream() .findAny() .flatMap(Playlist::importResource); } else { return Optional.empty(); } }
java
{ "resource": "" }
q180860
LaunchNakamura.launchButtonActionPerformed
test
private void launchButtonActionPerformed(java.awt.event.ActionEvent evt) { // Launch Nakamura if (runStatus == APP_NOT_RUNNING) { System.setSecurityManager(null); try { NakamuraMain.main(savedArgs); // Update label statusLabel.setText("Nakamura is starting..."); // Notify the user JOptionPane.showMessageDialog(this, "Nakamura has been started.\nPlease allow 30-60 seconds for it to be ready.", "Information", JOptionPane.INFORMATION_MESSAGE); runStatus = APP_RUNNING; isStartupFinished(); } catch (IOException e) { statusLabel.setText("Nakamura is startup failed " + e.getMessage()); } } else { // Can't start it again... // custom title, warning icon JOptionPane.showMessageDialog(this, "Nakamura is already running.", "Warning", JOptionPane.WARNING_MESSAGE); } }
java
{ "resource": "" }
q180861
LaunchNakamura.isStartupFinished
test
private void isStartupFinished() { boolean started = false; try { while (!started) { if (exists(localhostURL)) started = true; Thread.sleep(5 * 1000); } } catch (InterruptedException e) { e.printStackTrace(); } if (started) { statusLabel.setText("Nakamura is running."); statusLabel.setForeground(Color.green); launchButton.setEnabled(false); browserButton.setEnabled(true); } }
java
{ "resource": "" }
q180862
LaunchNakamura.exists
test
public static boolean exists(String URLName) { try { HttpURLConnection.setFollowRedirects(false); // note : you may also need // HttpURLConnection.setInstanceFollowRedirects(false) HttpURLConnection con = (HttpURLConnection) new URL(URLName).openConnection(); con.setRequestMethod("HEAD"); return (con.getResponseCode() == HttpURLConnection.HTTP_OK); } catch (Exception e) { e.printStackTrace(); return false; } }
java
{ "resource": "" }
q180863
LaunchNakamura.browserButtonActionPerformed
test
private void browserButtonActionPerformed(java.awt.event.ActionEvent evt) { try { Desktop.getDesktop().browse(new URL(localhostURL).toURI()); } catch (IOException e) { System.err.println("IO Exception: " + e.getMessage()); } catch (URISyntaxException e) { System.err.println("URISyntaxException: " + e.getMessage()); } }
java
{ "resource": "" }
q180864
LaunchNakamura.createImageIcon
test
protected ImageIcon createImageIcon(String path, String description) { java.net.URL imgURL = getClass().getResource(path); if (imgURL != null) { return new ImageIcon(imgURL, description); } else { System.err.println("Couldn't find file: " + path); return null; } }
java
{ "resource": "" }
q180865
LaunchNakamura.main
test
public static void main(String args[]) { savedArgs = args; java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new LaunchNakamura().setVisible(true); } }); }
java
{ "resource": "" }
q180866
IntArray.with
test
public IntArray with(int... values) { if (values.length != this.length) throw new IllegalArgumentException("Array size mismatch"); value = values.clone(); return this; }
java
{ "resource": "" }
q180867
Presence.export
test
public HashMap<String, Object> export() { HashMap<String, Object> data = new HashMap<>(); data.put(LEVEL_DESCRIPTOR, level.name()); data.put(PRESENT_DESCRIPTOR, present); data.put(STRICT_DESCRIPTOR, strict); data.put(KNOWN_DESCRIPTOR, known); return data; }
java
{ "resource": "" }
q180868
JSONResult.get
test
public JSONResult get(int index) { if (value instanceof JSONArray) { JSONArray array = (JSONArray) value; Object result = array.get(index); return new JSONResult(result); } else if (value instanceof JSONObject) { return get(String.valueOf(index)); } return new JSONResult(null); }
java
{ "resource": "" }
q180869
JSONResult.get
test
public JSONResult get(String key) { if (value instanceof JSONObject) { JSONObject obj = (JSONObject) value; Object result = obj.get(key); return new JSONResult(result); } else if (value instanceof JSONArray) { try { int index = Integer.parseInt(key); return get(index); } catch(NumberFormatException e) { throw createException("Excpected JSONObject " + key + ":"); } } return new JSONResult(null); }
java
{ "resource": "" }
q180870
JSONResult.getInt
test
public Integer getInt(Integer defaultValue) { if (value instanceof Number) { return ((Number) value).intValue(); } if (value instanceof String) { String s = (String) value; return Integer.parseInt(s); } if (value == null) { return defaultValue; } throw createException("Expected integer:"); }
java
{ "resource": "" }
q180871
JSONResult.getDouble
test
public Double getDouble(Double defaultValue) { if (value instanceof Number) { return ((Number) value).doubleValue(); } if (value instanceof String) { String s = (String) value; return Double.parseDouble(s); } if (value == null) { return defaultValue; } throw createException("Expected number:"); }
java
{ "resource": "" }
q180872
JSONResult.getString
test
public String getString(String defaultValue) { if (value instanceof String || value instanceof Number) { return value.toString(); } if (value == null) { return null; } if (value instanceof JSONArray) { return ((JSONArray) value).toJSONString(); } if (value instanceof JSONObject) { return ((JSONObject) value).toJSONString(); } if (value == null) { return defaultValue; } throw createException("Expected string:"); }
java
{ "resource": "" }
q180873
CommandResource.createCommandResource
test
public static Optional<CommandResource> createCommandResource(Identification provider, String command, Capabilities capabilities, Context context) { CommandResource commandResource = new CommandResource(provider, command, capabilities); if (!verifyCommand(command)) { context.getLogger().error("IllegalCommand!"); return Optional.empty(); } if (!verifyCapabilities(command, capabilities)) { context.getLogger().error("Player is not able to handle Command!"); return Optional.empty(); } return Optional.of(commandResource); }
java
{ "resource": "" }
q180874
CommandResource.verifyCommand
test
public static boolean verifyCommand(String command) { return command.equals(PLAY) || command.equals(PAUSE) || command.equals(STOP) || command.equals(SELECT_TRACK) || command.equals(NEXT) || command.equals(PREVIOUS) || command.equals(CHANGE_PLAYBACK) || command.equals(CHANGE_VOLUME); }
java
{ "resource": "" }
q180875
CommandResource.verifyCapabilities
test
public static boolean verifyCapabilities(String command, Capabilities capabilities) { switch (command) { case PLAY: return capabilities.hasPlayPauseControl(); case PAUSE: return capabilities.hasPlayPauseControl(); case SELECT_TRACK: return capabilities.isAbleToSelectTrack(); case NEXT: return capabilities.hasNextPrevious(); case PREVIOUS: return capabilities.hasNextPrevious(); case JUMP: return capabilities.isAbleToJump(); case CHANGE_PLAYBACK: return capabilities.isPlaybackChangeable(); case CHANGE_VOLUME: return capabilities.canChangeVolume(); case STOP: return true; } return false; }
java
{ "resource": "" }
q180876
CommandResource.verify
test
public static boolean verify(String command, Capabilities capabilities) { return verifyCommand(command) && verifyCapabilities(command, capabilities); }
java
{ "resource": "" }
q180877
SessionManager.executeBatchAsync
test
public void executeBatchAsync(FutureCallback<ResultSet> callback, Statement... statements) throws ExceedMaxAsyncJobsException { if (!asyncSemaphore.tryAcquire()) { if (callback == null) { throw new ExceedMaxAsyncJobsException(maxSyncJobs); } else { callback.onFailure(new ExceedMaxAsyncJobsException(maxSyncJobs)); } } else { try { ResultSetFuture rsf = CqlUtils.executeBatchAsync(getSession(), statements); if (callback != null) { Futures.addCallback(rsf, wrapCallbackResultSet(callback), asyncExecutor); } } catch (Exception e) { asyncSemaphore.release(); LOGGER.error(e.getMessage(), e); } } }
java
{ "resource": "" }
q180878
CF.getSubclasses
test
public Set<Class<?>> getSubclasses(Class<?> clazz){ Set<Class<?>> ret = new HashSet<Class<?>>(); Set<Class<?>> w = null; if(clazz!=null){ this.clear(); Map<URI, String> locations = this.locator.getCfLocations(); for(Entry<URI, String> entry : locations.entrySet()){ try{ w = search(clazz, entry.getKey(), locations.get(entry.getKey())); if(w!=null && (w.size()>0)){ ret.addAll(w); } } catch(MalformedURLException ex){} } } return ret; }
java
{ "resource": "" }
q180879
CF.getSubclasses
test
public Set<Class<?>> getSubclasses(String fqcn){ if(fqcn==null){ return new HashSet<Class<?>>(); } else if(StringUtils.startsWith(fqcn, ".") || StringUtils.endsWith(fqcn, ".")){ return new HashSet<Class<?>>(); } Class<?> clazz = null; try{ clazz = Class.forName(fqcn); } catch(ClassNotFoundException ex){ this.clear(); this.errors.add(ex); return new HashSet<Class<?>>(); } return getSubclasses(clazz); }
java
{ "resource": "" }
q180880
CF.search
test
private final Set<Class<?>> search(Class<?> clazz, URI location, String packageName) throws MalformedURLException{ if(clazz==null || location==null){ return new HashSet<Class<?>>(); } File directory = new File(location.toURL().getFile()); if(directory.exists()){ return this.searchDirectory(clazz, directory, location, packageName).keySet(); } else{ return this.searchJar(clazz, location).keySet(); } }
java
{ "resource": "" }
q180881
CF.searchDirectory
test
protected final Map<Class<?>, URI> searchDirectory(Class<?> clazz, File directory, URI location, String packageName){ Map<Class<?>, URI> ret = new HashMap<>(); String[] files = directory.list(); for(int i=0; i<files.length; i++){ if(files[i].endsWith(".class")){ String classname = files[i].substring(0, files[i].length()-6); try{ Class<?> c = Class.forName(packageName + "." + classname); if(clazz.isAssignableFrom(c) && !clazz.getName().equals(packageName + "." + classname)){ ret.put(c, location); } } catch(Exception ex){ errors.add(ex); } } } return ret; }
java
{ "resource": "" }
q180882
CF.searchJar
test
protected final Map<Class<?>, URI> searchJar(Class<?> clazz, URI location){ Map<Class<?>, URI> ret = new HashMap<>(); try{ JarURLConnection conn = (JarURLConnection)location.toURL().openConnection(); JarFile jarFile = conn.getJarFile(); for(Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements();){ JarEntry entry = e.nextElement(); String entryname = entry.getName(); if(this.processed.contains(entryname)){ continue; } this.processed.add(entryname); if(!entry.isDirectory() && entryname.endsWith(".class")){ String classname = entryname.substring(0, entryname.length()-6); if(classname.startsWith("/")){ classname = classname.substring(1); } classname = classname.replace('/','.'); if(!StringUtils.startsWithAny(classname, this.excludedNames)){ try{ Class<?> c = Class.forName(classname); if(clazz.isAssignableFrom(c) && !clazz.getName().equals(classname)){ ret.put(c, location); } } catch(Exception exception){ errors.add(exception); } catch(Error error){ errors.add(error); } } } } } catch(IOException ignore){ errors.add(ignore); } return ret; }
java
{ "resource": "" }
q180883
Resource.toList
test
public List<Resource> toList() { List<Resource> resourceList = new ArrayList<>(); resourceList.add(this); return resourceList; }
java
{ "resource": "" }
q180884
HashMap3.size
test
public int size() { int result = 0; // sum over all inner maps for ( Iterator<K1> keys1 = maps.keySet().iterator(); keys1.hasNext(); ) { Map2<K2,K3,V> inner_map = maps.get(keys1.next()); result += inner_map.size(); } return result; }
java
{ "resource": "" }
q180885
PacketCollector.processPacket
test
protected void processPacket(Packet packet) { if (packet == null) { return; } if (packetFilter == null || packetFilter.accept(packet)) { while (!resultQueue.offer(packet)) { // Since we know the queue is full, this poll should never // actually block. resultQueue.poll(); } } }
java
{ "resource": "" }
q180886
VolumeResource.getVolume
test
public static Optional<Volume> getVolume(EventModel eventModel) { if (eventModel.getListResourceContainer().containsResourcesFromSource(ID)) { return eventModel .getListResourceContainer() .provideResource(ID) .stream() .map(ResourceModel::getResource) .filter(ob -> ob instanceof Integer) .map(ob -> (Integer) ob) .findAny() .flatMap(Volume::createVolume); } else { return Optional.empty(); } }
java
{ "resource": "" }
q180887
XMPPUtils.errorRSM
test
public static IQ errorRSM(IQ iq, Logger logger) { String rsmMessage = "RSM: Page Not Found"; logger.error(rsmMessage + " " + iq); return XMPPUtils.createErrorResponse(iq, rsmMessage, Condition.item_not_found, Type.cancel); }
java
{ "resource": "" }
q180888
XMPPUtils.createErrorResponse
test
public static IQ createErrorResponse(final IQ request, final String message, Condition condition, Type type) { final IQ result = request.createCopy(); result.setID(request.getID()); result.setFrom(request.getTo()); result.setTo(request.getFrom()); PacketError e = new PacketError(condition, type); if (message != null) { e.setText(message); } result.setError(e); return result; }
java
{ "resource": "" }
q180889
SelectorResource.isTarget
test
public static Optional<Boolean> isTarget(EventModel eventModel, Identifiable identifiable) { if (eventModel.getListResourceContainer() .providesResource(Collections.singletonList(SelectorResource.RESOURCE_ID))) { return Optional.of(eventModel.getListResourceContainer() .provideResource(SelectorResource.RESOURCE_ID) .stream() .map(ResourceModel::getResource) .filter(resource -> resource instanceof Identification) .map(object -> (Identification) object) .anyMatch(identifiable::isOwner)); } else { return Optional.empty(); } }
java
{ "resource": "" }
q180890
User.setLoginEnabled
test
public void setLoginEnabled(long from, long to, boolean day, TimeZone timeZone) { String enabledSetting = EnabledPeriod.getEnableValue(from, to, day, timeZone); if (enabledSetting == null) { removeProperty(LOGIN_ENABLED_PERIOD_FIELD); } else { setProperty(LOGIN_ENABLED_PERIOD_FIELD, enabledSetting); } }
java
{ "resource": "" }
q180891
SynchronizedSet.decorate
test
public static <E> Set<E> decorate(Set<E> set) { return new SynchronizedSet<E>(set); }
java
{ "resource": "" }
q180892
RosterEntry.setName
test
public void setName(String name) { // Do nothing if the name hasn't changed. if (name != null && name.equals(this.name)) { return; } this.name = name; Roster packet = new Roster(); packet.setType(IQ.Type.set); packet.addItem(new JID(user), name, ask, subscription, getGroupNames()); connection.sendPacket(packet); }
java
{ "resource": "" }
q180893
RosterEntry.updateState
test
void updateState(String name, Subscription type, Ask status) { this.name = name; this.subscription = type; this.ask = status; }
java
{ "resource": "" }
q180894
RosterEntry.getGroups
test
public Collection<RosterGroup> getGroups() { List<RosterGroup> results = new ArrayList<RosterGroup>(); // Loop through all roster groups and find the ones that contain this // entry. This algorithm should be fine for (RosterGroup group : roster.getGroups()) { if (group.contains(this)) { results.add(group); } } return Collections.unmodifiableCollection(results); }
java
{ "resource": "" }
q180895
RSMUtils.appendRSMElement
test
public static void appendRSMElement(Element queryElement, RSM rsm) { Element setElement = queryElement.addElement("set", RSM.NAMESPACE); if (rsm.getFirst() != null) { Element firstElement = setElement.addElement("first"); firstElement.addAttribute("index", rsm.getIndex().toString()); firstElement.setText(rsm.getFirst()); } if (rsm.getLast() != null) { Element lastElement = setElement.addElement("last"); lastElement.setText(rsm.getLast()); } setElement.addElement("count").setText(String.valueOf(rsm.getCount())); }
java
{ "resource": "" }
q180896
RSMUtils.parseRSM
test
public static RSM parseRSM(Element queryElement) { RSM rsm = new RSM(); Element setElement = queryElement.element("set"); if (setElement == null) { return rsm; } Element after = setElement.element("after"); if (after != null) { rsm.setAfter(after.getText()); } Element before = setElement.element("before"); if (before != null) { String beforeText = before.getText(); rsm.setBefore(beforeText == null ? "" : beforeText); } Element index = setElement.element("index"); if (index != null) { rsm.setIndex(Integer.parseInt(index.getText())); } Element max = setElement.element("max"); if (max != null) { rsm.setMax(Integer.parseInt(max.getText())); } return rsm; }
java
{ "resource": "" }
q180897
RSMUtils.filterRSMResponse
test
public static List<Identifiable> filterRSMResponse( List<Identifiable> objects, RSM rsm) throws IllegalArgumentException { String after = rsm.getAfter(); String before = rsm.getBefore(); int initialIndex = rsm.getIndex(); int lastIndex = objects.size(); if (after != null || (before != null && !before.isEmpty())) { boolean afterItemFound = false; boolean beforeItemFound = false; int i = 0; for (Identifiable object : objects) { if (after != null && after.equals(object.getId())) { initialIndex = i + 1; afterItemFound = true; } if (before != null && before.equals(object.getId())) { lastIndex = i; beforeItemFound = true; } i++; } if (after != null && !afterItemFound) { throw new IllegalArgumentException(); } if (before != null && !before.isEmpty() && !beforeItemFound) { throw new IllegalArgumentException(); } } if (rsm.getMax() != null) { if (before != null) { initialIndex = lastIndex - rsm.getMax(); } else { lastIndex = initialIndex + rsm.getMax(); } } boolean outOfRange = initialIndex > lastIndex || initialIndex < 0 || lastIndex > objects.size(); List<Identifiable> filteredList = outOfRange ? new LinkedList<Identifiable>() : objects.subList(initialIndex, lastIndex); rsm.setCount(objects.size()); rsm.setIndex(initialIndex); if (!filteredList.isEmpty()) { rsm.setFirst(filteredList.get(0).getId()); rsm.setLast(filteredList.get(filteredList.size() - 1).getId()); } return filteredList; }
java
{ "resource": "" }
q180898
LeavingEvent.createLeavingEvent
test
public static Optional<LeavingEvent> createLeavingEvent(Identification source, boolean strict, List<String> descriptors) { try { if (strict) { descriptors.add(STRICT_DESCRIPTOR); } else { descriptors.add(GENERAL_DESCRIPTOR); } descriptors.add(ID); descriptors.add(CommonEvents.Descriptors.NOT_INTERRUPT); LeavingEvent stopRequest = new LeavingEvent(source, descriptors); return Optional.of(stopRequest); } catch (IllegalArgumentException e) { return Optional.empty(); } }
java
{ "resource": "" }
q180899
UserRoster.reload
test
public void reload() { if (!connection.isAuthenticated()) { throw new IllegalStateException("Not logged in to server."); } if (connection.isAnonymous()) { throw new IllegalStateException( "Anonymous users can't have a roster."); } Roster packet = new Roster(); if (rosterStore != null && connection.isRosterVersioningSupported()) { packet.getElement().element("query") .addAttribute("ver", rosterStore.getRosterVersion()); PacketFilter filter = new PacketIDFilter(packet.getID()); connection.addPacketListener(new RosterResultListener(), filter); } connection.sendPacket(packet); }
java
{ "resource": "" }