List of usage examples for java.util Queue isEmpty
boolean isEmpty();
From source file:org.opencb.commons.datastore.solr.FacetQueryParser.java
public String parseJson(String facetJson) throws IOException { Queue<Map<String, Object>> myQueue = new LinkedList<>(); Map jsonMap = new ObjectMapper().readValue(facetJson, Map.class); myQueue.add(jsonMap);/*from w ww .j a va2 s.c om*/ while (!myQueue.isEmpty()) { Map<String, Object> map = myQueue.remove(); for (Map.Entry<String, Object> entry : map.entrySet()) { if (entry.getValue() instanceof Map) { Map<String, Object> innerMap = (Map<String, Object>) entry.getValue(); // Analyse map to fill in content if (innerMap.containsKey("start")) { // Ranges innerMap.put("type", "range"); innerMap.put("gap", innerMap.get("step")); innerMap.remove("step"); } else if (innerMap.containsKey("q")) { // Query innerMap.put("type", "query"); } else if (innerMap.containsKey("field")) { // Categorical innerMap.put("type", "terms"); } // Check if there is a 'facet' field and insert all the items in the queue Object facet = innerMap.get("facet"); if (facet != null) { myQueue.add((Map<String, Object>) facet); } } } } return new ObjectMapper().writeValueAsString(jsonMap); }
From source file:se.sics.gvod.common.GraphUtil.java
private void bfs(int v, int d[]) { Queue<Integer> q = new LinkedList<Integer>(); for (int i = 0; i < n; i++) { d[i] = n; // also means that the node has not been visited }//from w ww .j a v a2 s .c om d[v] = 0; q.offer(v); q.offer(0); // depth of v while (!q.isEmpty()) { int u = q.poll(); int du = q.poll(); // depth of u for (int t = 0; t < neighbors[u].length; t++) { if (d[neighbors[u][t]] == n) { // on the first encounter, add to the queue d[neighbors[u][t]] = du + 1; q.offer(neighbors[u][t]); q.offer(du + 1); } } } }
From source file:com.github.rinde.rinsim.core.model.road.GraphRoadModel.java
/** * Determines if the {@link #doFollowPath(MovingRoadUser, Queue, TimeLapse)} * method should continue moving towards the next hop in path. This method can * be overridden to add additional constraints. * @param curLoc The current location of the moving object. * @param path The path of the moving object. * @param time The time available for moving. * @return <code>true</code> if the object should keep moving, * <code>false</code> otherwise. *//*from w w w . j ava 2s . co m*/ protected boolean keepMoving(Loc curLoc, Queue<Point> path, TimeLapse time) { return time.hasTimeLeft() && !path.isEmpty(); }
From source file:org.primeframework.mvc.util.ClassClasspathResolver.java
private Set<File> findDirectories(File dir, String locator) { // Loop over the files using tail-recursion Set<File> directories = new HashSet<File>(); Queue<File> files = new LinkedList<File>(safeListFiles(dir, DirectoryFileFilter.INSTANCE)); while (!files.isEmpty()) { File file = files.poll(); if (file.isDirectory() && file.getName().equals(locator)) { directories.add(file);/*from w ww. j ava2 s.c o m*/ } else if (file.isDirectory()) { files.addAll(safeListFiles(file, null)); } } return directories; }
From source file:com.marklogic.contentpump.DelimitedJSONReader.java
@SuppressWarnings("unchecked") protected String findUriInJSON(String line) throws JsonParseException, IOException { /* Breadth-First-Search */ Queue<Object> q = new LinkedList<Object>(); Object root = mapper.readValue(line.getBytes(), Object.class); if (root instanceof Map || root instanceof ArrayList) { q.add(root);//from ww w . j a v a 2s .co m } else { throw new UnsupportedOperationException("invalid JSON"); } while (!q.isEmpty()) { Object current = q.remove(); if (current instanceof ArrayList) { for (Object element : (ArrayList<Object>) current) { if (element instanceof Map || element instanceof ArrayList) { q.add(element); } } } else { // instanceof Map // First Match Map<String, ?> map = (Map<String, ?>) current; if (map.containsKey(uriName)) { Object uriValue = map.get(uriName); if (uriValue instanceof Number || uriValue instanceof String) { return uriValue.toString(); } else { return null; } } // Add child elements to queue Iterator<?> it = map.entrySet().iterator(); while (it.hasNext()) { Entry<String, ?> KVpair = (Entry<String, ?>) it.next(); Object pairValue = KVpair.getValue(); if (pairValue instanceof Map || pairValue instanceof ArrayList) { q.add(pairValue); } } ; } } return null; }
From source file:org.xwiki.tool.xar.XARMojo.java
/** * Adds files from a specific directory to an archive. It uses an existing package.xml to filter the files to be * added.//from ww w . jav a 2 s . c o m * * @param archiver the archive in which the files will be added * @param sourceDir the directory whose contents will be added to the archive * @param packageXml the corresponding package.xml file * @throws Exception if the files cannot be added to the archive */ private void addFilesToArchive(ZipArchiver archiver, File sourceDir, File packageXml) throws Exception { Collection<String> documentNames; getLog().info(String.format("Using the existing package.xml descriptor at [%s]", packageXml.getPath())); try { documentNames = getDocumentNamesFromXML(packageXml); } catch (Exception e) { getLog().error(String.format("The existing [%s] is invalid.", PACKAGE_XML)); throw e; } // Next, we scan the hole directory and subdirectories for documents. Queue<File> fileQueue = new LinkedList<File>(); addContentsToQueue(fileQueue, sourceDir); while (!fileQueue.isEmpty() && !documentNames.isEmpty()) { File currentFile = fileQueue.poll(); if (currentFile.isDirectory()) { addContentsToQueue(fileQueue, currentFile); } else { String documentReference = XWikiDocument.getReference(currentFile); if (documentNames.contains(documentReference)) { // building the path the current file will have within the archive // // Note: DO NOT USE String.split since it requires a regexp. Under Windows XP, the FileSeparator is // '\' when not escaped is a special character of the regexp // String archivedFilePath = // currentFile.getAbsolutePath().split(sourceDir.getAbsolutePath() + File.separator)[1]; String archivedFilePath = currentFile.getAbsolutePath() .substring((sourceDir.getAbsolutePath() + File.separator).length()); archivedFilePath = archivedFilePath.replace(File.separatorChar, '/'); archiver.addFile(currentFile, archivedFilePath); documentNames.remove(documentReference); } } } if (!documentNames.isEmpty()) { StringBuilder errorMessage = new StringBuilder("The following documents could not be found: "); for (String name : documentNames) { errorMessage.append(name); errorMessage.append(" "); } throw new Exception(errorMessage.toString()); } archiver.addFile(packageXml, PACKAGE_XML); }
From source file:net.dv8tion.jda.audio.AudioConnection.java
private void setupCombinedExecutor() { if (combinedAudioExecutor == null) { combinedAudioExecutor = Executors.newSingleThreadScheduledExecutor( r -> new Thread(r, "AudioConnection CombinedAudio Guild: " + channel.getGuild().getId())); combinedAudioExecutor.scheduleAtFixedRate(() -> { try { List<User> users = new LinkedList<>(); List<short[]> audioParts = new LinkedList<>(); if (receiveHandler != null && receiveHandler.canReceiveCombined()) { long currentTime = System.currentTimeMillis(); for (Map.Entry<User, Queue<Pair<Long, short[]>>> entry : combinedQueue.entrySet()) { User user = entry.getKey(); Queue<Pair<Long, short[]>> queue = entry.getValue(); if (queue.isEmpty()) continue; Pair<Long, short[]> audioData = queue.poll(); //Make sure the audio packet is younger than 100ms while (audioData != null && currentTime - audioData.getLeft() > queueTimeout) { audioData = queue.poll(); }// w ww.j ava2s . c om //If none of the audio packets were younger than 100ms, then there is nothing to add. if (audioData == null) { continue; } users.add(user); audioParts.add(audioData.getRight()); } if (!audioParts.isEmpty()) { int audioLength = audioParts.get(0).length; short[] mix = new short[1920]; //960 PCM samples for each channel int sample; for (int i = 0; i < audioLength; i++) { sample = 0; for (short[] audio : audioParts) { sample += audio[i]; } if (sample > Short.MAX_VALUE) mix[i] = Short.MAX_VALUE; else if (sample < Short.MIN_VALUE) mix[i] = Short.MIN_VALUE; else mix[i] = (short) sample; } receiveHandler.handleCombinedAudio(new CombinedAudio(users, mix)); } else { //No audio to mix, provide 20 MS of silence. (960 PCM samples for each channel) receiveHandler .handleCombinedAudio(new CombinedAudio(new LinkedList(), new short[1920])); } } } catch (Exception e) { LOG.log(e); } }, 0, 20, TimeUnit.MILLISECONDS); } }
From source file:org.structr.core.entity.SchemaMethod.java
private void determineSignature(final Map<String, SchemaNode> schemaNodes, final AbstractSchemaNode schemaEntity, final ActionEntry entry, final String methodName) throws FrameworkException { final App app = StructrApp.getInstance(); final Set<String> visitedTypes = new LinkedHashSet<>(); final Queue<String> typeQueue = new LinkedList<>(); final String structrPackage = "org.structr.dynamic."; // initial type addType(typeQueue, schemaEntity);// www.j ava 2 s. co m while (!typeQueue.isEmpty()) { final String typeName = typeQueue.poll(); String shortTypeName = typeName; if (typeName != null && !visitedTypes.contains(typeName)) { visitedTypes.add(typeName); if (typeName.startsWith(structrPackage)) { shortTypeName = typeName.substring(structrPackage.length()); } // try to find schema node for the given type final SchemaNode typeNode = schemaNodes.get(shortTypeName); if (typeNode != null && !typeNode.equals(schemaEntity)) { // try to identify overridden schema method from database final SchemaMethod superMethod = app.nodeQuery(SchemaMethod.class) .and(SchemaMethod.schemaNode, typeNode).and(SchemaMethod.name, methodName).getFirst(); if (superMethod != null) { final ActionEntry superEntry = superMethod.getActionEntry(schemaNodes, typeNode); entry.copy(superEntry); // done return; } // next type in queue addType(typeQueue, typeNode); } else { // no schema node for the given type found, try internal types final Class internalType = SchemaHelper.classForName(typeName); if (internalType != null) { if (getSignature(internalType, methodName, entry)) { return; } final Class superclass = internalType.getSuperclass(); if (superclass != null) { // examine superclass as well typeQueue.add(superclass.getName()); // collect interfaces for (final Class iface : internalType.getInterfaces()) { typeQueue.add(iface.getName()); } } } } } } }
From source file:za.co.jumpingbean.alfresco.repo.EmailDocumentsAction.java
public void addAttachments(final Action action, final NodeRef nodeRef, MimeMessage mimeMessage) throws MessagingException { String text = (String) action.getParameterValue(PARAM_BODY); Boolean convertToPDF = (Boolean) action.getParameterValue(PARAM_CONVERT); MimeMultipart mail = new MimeMultipart("mixed"); MimeBodyPart bodyText = new MimeBodyPart(); bodyText.setText(text);//w ww. j a va 2 s. co m mail.addBodyPart(bodyText); Queue<NodeRef> que = new LinkedList<>(); QName type = nodeService.getType(nodeRef); if (type.isMatch(ContentModel.TYPE_FOLDER) || type.isMatch(ContentModel.TYPE_CONTAINER)) { que.add(nodeRef); } else { addAttachement(nodeRef, mail, convertToPDF); } while (!que.isEmpty()) { NodeRef tmpNodeRef = que.remove(); List<ChildAssociationRef> list = nodeService.getChildAssocs(tmpNodeRef); for (ChildAssociationRef childRef : list) { NodeRef ref = childRef.getChildRef(); if (nodeService.getType(ref).isMatch(ContentModel.TYPE_CONTENT)) { addAttachement(ref, mail, convertToPDF); } else { que.add(ref); } } } mimeMessage.setContent(mail); }
From source file:it.geosolutions.geobatch.destination.action.datamigration.RasterMigrationAction.java
@Override public Queue<EventObject> execute(Queue<EventObject> events) throws ActionException { listenerForwarder.setTask("Check configuration"); checkConfiguration();//from www. j av a 2 s.c o m // Creation of a List containing the event objects final LinkedList<EventObject> ret = new LinkedList<EventObject>(); try { // Start of the operations listenerForwarder.started(); // Until the events are present, the input files are elaborated while (!events.isEmpty()) { // Each event is polled from the list EventObject event = events.poll(); if (event instanceof FileSystemEvent) { FileSystemEvent fse = (FileSystemEvent) event; File file = fse.getSource(); // Copy doProcess(FilenameUtils.getBaseName(file.getName())); } // pass the feature config to the next action ret.add(new FileSystemEvent(((FileSystemEvent) event).getSource(), FileSystemEventType.FILE_ADDED)); } listenerForwarder.completed(); return ret; } catch (Exception t) { listenerForwarder.failed(t); throw new ActionException(this, t.getMessage(), t); } }