List of usage examples for java.util Queue isEmpty
boolean isEmpty();
From source file:eu.stratosphere.nephele.jobmanager.scheduler.RecoveryLogic.java
private static void findVerticesToRestart(final ExecutionVertex failedVertex, final Set<ExecutionVertex> verticesToBeCanceled) { final Queue<ExecutionVertex> verticesToTest = new ArrayDeque<ExecutionVertex>(); final Set<ExecutionVertex> visited = new HashSet<ExecutionVertex>(); verticesToTest.add(failedVertex);//from ww w . ja v a 2 s .c o m while (!verticesToTest.isEmpty()) { final ExecutionVertex vertex = verticesToTest.poll(); // Predecessors must be either checkpoints or need to be restarted, too for (int j = 0; j < vertex.getNumberOfPredecessors(); j++) { final ExecutionVertex predecessor = vertex.getPredecessor(j); if (hasInstanceAssigned(predecessor)) { verticesToBeCanceled.add(predecessor); } if (!visited.contains(predecessor)) { verticesToTest.add(predecessor); } } visited.add(vertex); } }
From source file:com.demandware.vulnapp.util.Helpers.java
/** * Given a root dir and a file name, search all subdirectories for the file. * /* ww w .j a v a 2s .co m*/ * @return null if root or name is null, or if the file is not found. the found file otherwise */ public static File findFile(File root, String name) { if (root == null || name == null) { return null; } File foundFile = null; Queue<File> filesAndDirs = new LinkedList<File>(); filesAndDirs.add(root); while (!filesAndDirs.isEmpty() && foundFile == null) { File file = filesAndDirs.poll(); if (file.isDirectory()) { File[] files = file.listFiles(); if (files != null) { for (File f : files) { filesAndDirs.add(f); } } } else { if (file.getName().equals(name)) { foundFile = file; } } } return foundFile; }
From source file:org.jspringbot.keyword.expression.ELUtils.java
public static Object doMap(Object... args) { Object defaultValue = null;/* w w w .j a va2s. co m*/ Queue<Object> arguments = new LinkedList<Object>(); arguments.addAll(Arrays.asList(args)); Object variable = arguments.remove(); while (!arguments.isEmpty()) { if (arguments.size() > 1) { Object variableValue = arguments.remove(); Object mapValue = arguments.remove(); if (variable.equals(variableValue)) { return mapValue; } } else { // default return arguments.remove(); } } return defaultValue; }
From source file:es.darkhogg.hazelnutt.Hazelnutt.java
/** * Terminates the application in at most <i>time</i> milliseconds for * every alive thread. //from w w w .j a v a2s. c o m * * @param time Number of milliseconds to wait for each thread to terminate */ public static void terminate(long time) { Logger logger = getLogger(); logger.info("Terminating application..."); try { getFrame().dispose(); // Get the root thread group ThreadGroup rootThreadGroup = Thread.currentThread().getThreadGroup(); while (rootThreadGroup.getParent() != null) { rootThreadGroup = rootThreadGroup.getParent(); } // Declare some collections Queue<ThreadGroup> threadGroups = new LinkedList<ThreadGroup>(); Queue<Thread> threads = new LinkedList<Thread>(); // Get ALL groups threadGroups.add(rootThreadGroup); while (!threadGroups.isEmpty()) { ThreadGroup group = threadGroups.remove(); Thread[] subThreads = new Thread[group.activeCount() * 2]; //group.enumerate( subThreads ); for (Thread subThread : subThreads) { if (subThread != null) { threads.add(subThread); } } ThreadGroup[] subThreadGroups = new ThreadGroup[group.activeGroupCount() * 2]; for (ThreadGroup subThreadGroup : subThreadGroups) { if (subThreadGroup != null) { threadGroups.add(subThreadGroup); } } } // Join a maximum of time milliseconds for all non-daemon threads while (!threads.isEmpty()) { Thread thread = threads.remove(); LOGGER.trace(thread); if (!thread.isDaemon() && thread != Thread.currentThread()) { logger.trace("Waiting for thread '" + thread.getName() + "'"); thread.join(time); if (thread.isAlive()) { logger.trace("Interrupting thread '" + thread.getName() + "'"); thread.interrupt(); } } } } catch (Throwable e) { LOGGER.warn("Interrupted while terminating application", e); } finally { // Exit the program System.exit(0); } }
From source file:com.enderville.enderinstaller.util.InstallScript.java
/** * Repackages all the files in the tmp directory to the new minecraft.jar * * @param tmp The temp directory where mods were installed. * @param mcjar The location to save the new minecraft.jar. * @throws IOException//from ww w . java2 s .c o m */ public static void repackMCJar(File tmp, File mcjar) throws IOException { byte[] dat = new byte[4 * 1024]; JarOutputStream jarout = new JarOutputStream(FileUtils.openOutputStream(mcjar)); Queue<File> queue = new LinkedList<File>(); for (File f : tmp.listFiles()) { queue.add(f); } while (!queue.isEmpty()) { File f = queue.poll(); if (f.isDirectory()) { for (File child : f.listFiles()) { queue.add(child); } } else { //TODO need a better way to do this String name = f.getPath().substring(tmp.getPath().length() + 1); //TODO is this formatting really required for jars? name = name.replace("\\", "/"); if (f.isDirectory() && !name.endsWith("/")) { name = name + "/"; } JarEntry entry = new JarEntry(name); jarout.putNextEntry(entry); FileInputStream in = new FileInputStream(f); int len = -1; while ((len = in.read(dat)) > 0) { jarout.write(dat, 0, len); } in.close(); } jarout.closeEntry(); } jarout.close(); }
From source file:geotag.example.sbickt.SbicktAPI.java
public static Queue<GeoTag> getGeoTags(Point3D me) throws Exception { KmlParser kp = new KmlParser(); Queue<GeoTag> listOfGeoTags = new LinkedList<GeoTag>(); Exception up = new Exception("SbicktAPI -> getGeoTags: No data from server"); kp.requestKml(Properties.URL_PROTOCOL, Properties.URL_HOST, Properties.URL_PORT, Properties.URL_FOLDER_LIST + "?lat=" + me.x + "&lng=" + me.y); listOfGeoTags = kp.generateObjects(); if (listOfGeoTags == null) { throw up; //ha ha } else if (listOfGeoTags.isEmpty()) { throw new Exception("SbicktAPI -> getGeoTags: Object list is empty"); } else {//w ww.j av a2 s .c o m return listOfGeoTags; } }
From source file:org.xwiki.xdomviz.Main.java
/** * <p>//from ww w .ja v a 2 s . c o m * This method produces the GraphViz source code corresponding to the node tree. * </p> * * @param root The node tree root. * @return A string containing the GraphViz source code to display the node tree. */ private static String generateGraphViz(Node root) { // The rendering buffer. StringBuffer sb = new StringBuffer(); // This map contains the GraphViz Ids (integers) associated to the nodes in the tree. Map<Node, Integer> nodeToIdMap = new HashMap<Node, Integer>(); sb.append("digraph XDOM {\n"); // Breadth first visit of the XDOM to assign simple ids to nodes. Queue<Node> nodesQueue = new ArrayDeque<Node>(); nodesQueue.add(root); // Counter used to keep track of the assigned ids. It's incremented at each time a new node is found for the // first time. int i = 0; while (!nodesQueue.isEmpty()) { Node node = nodesQueue.poll(); if (nodeToIdMap.get(node) == null) { nodeToIdMap.put(node, i); i++; } for (Node child : node.getChildren()) { if (nodeToIdMap.get(child) == null) { nodeToIdMap.put(child, i); i++; } nodesQueue.add(child); // Render the edge. sb.append(String.format("%d -> %d;\n", nodeToIdMap.get(node), nodeToIdMap.get(child))); } } // Render the label assignment. for (Node node : nodeToIdMap.keySet()) { sb.append(String.format("%d [label = \"%s\"];\n", nodeToIdMap.get(node), node)); } sb.append("}\n"); return sb.toString(); }
From source file:com.linkedin.pinot.core.startree.StarTreeSerDe.java
/** * Helper method to write the star tree nodes for Star Tree off-heap format * * @param starTree/*from w w w .j a va2 s. co m*/ * @param mappedByteBuffer * @param offset */ private static void writeNodesOffHeap(StarTree starTree, MMapBuffer mappedByteBuffer, long offset) { int index = 0; Queue<StarTreeIndexNode> queue = new LinkedList<>(); StarTreeIndexNode root = (StarTreeIndexNode) starTree.getRoot(); queue.add(root); while (!queue.isEmpty()) { StarTreeIndexNode node = queue.poll(); List<StarTreeIndexNode> children = getSortedChildren(node); // Returns empty list instead of null. int numChildren = children.size(); int startChildrenIndex = (numChildren != 0) ? (index + queue.size() + 1) : StarTreeIndexNodeOffHeap.INVALID_INDEX; int endChildrenIndex = (numChildren != 0) ? (startChildrenIndex + numChildren - 1) : StarTreeIndexNodeOffHeap.INVALID_INDEX; offset = writeOneOffHeapNode(mappedByteBuffer, offset, node, startChildrenIndex, endChildrenIndex); for (StarTreeIndexNode child : children) { queue.add(child); } index++; } }
From source file:org.aksw.simba.cetus.yago.YagoBasedTypeSearcher.java
protected static void addHigherIncludedDolceClass(Set<Resource> classes, Model dolceClassModel, Set<Resource> unlinkedDolceClasses) { Queue<Resource> queue = new LinkedList<Resource>(classes); Resource classResource, superClass, subClass; RDFNode node;/*from w w w . j a v a 2 s . c om*/ NodeIterator nodeIterator; ResIterator resIterator; boolean addClass; while (!queue.isEmpty()) { classResource = queue.poll(); if (dolceClassModel.containsResource(classResource)) { nodeIterator = dolceClassModel.listObjectsOfProperty(classResource, RDFS.subClassOf); while (nodeIterator.hasNext()) { node = nodeIterator.next(); if (node.isResource()) { superClass = node.asResource(); // get all sub classes of this class resIterator = dolceClassModel.listSubjectsWithProperty(RDFS.subClassOf, superClass); addClass = true; // Check that all sub classes of this super class are // already in // the list of classes or are marked as unlinked classes while (resIterator.hasNext() && addClass) { subClass = resIterator.next(); addClass = classes.contains(subClass) || unlinkedDolceClasses.contains(subClass); } if (addClass) { classes.add(superClass); queue.add(superClass); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Added " + superClass.getURI()); } } } else { LOGGER.error("Expected a resource in the statement (" + classResource + ", rdfs:subClassOf, " + node + "). Ignoring this statement."); } } } } }
From source file:com.cloudera.oryx.rdf.common.pmml.DecisionForestPMML.java
private static Segment buildTreeModel(DecisionForest forest, Map<Integer, BiMap<String, Integer>> columnToCategoryNameToIDMapping, MiningFunctionType miningFunctionType, MiningSchema miningSchema, int treeID, DecisionTree tree, InboundSettings settings) {/* w w w . j a v a 2 s . c o m*/ List<String> columnNames = settings.getColumnNames(); int targetColumn = settings.getTargetColumn(); Node root = new Node(); root.setId("r"); // Queue<Node> modelNodes = Queues.newArrayDeque(); Queue<Node> modelNodes = new ArrayDeque<Node>(); modelNodes.add(root); Queue<Pair<TreeNode, Decision>> treeNodes = new ArrayDeque<Pair<TreeNode, Decision>>(); treeNodes.add(new Pair<TreeNode, Decision>(tree.getRoot(), null)); while (!treeNodes.isEmpty()) { Pair<TreeNode, Decision> treeNodePredicate = treeNodes.remove(); Node modelNode = modelNodes.remove(); // This is the decision that got us here from the parent, if any; not the predicate at this node Predicate predicate = buildPredicate(treeNodePredicate.getSecond(), columnNames, columnToCategoryNameToIDMapping); modelNode.setPredicate(predicate); TreeNode treeNode = treeNodePredicate.getFirst(); if (treeNode.isTerminal()) { TerminalNode terminalNode = (TerminalNode) treeNode; modelNode.setRecordCount((double) terminalNode.getCount()); Prediction prediction = terminalNode.getPrediction(); if (prediction.getFeatureType() == FeatureType.CATEGORICAL) { Map<Integer, String> categoryIDToName = columnToCategoryNameToIDMapping.get(targetColumn) .inverse(); CategoricalPrediction categoricalPrediction = (CategoricalPrediction) prediction; int[] categoryCounts = categoricalPrediction.getCategoryCounts(); float[] categoryProbabilities = categoricalPrediction.getCategoryProbabilities(); for (int categoryID = 0; categoryID < categoryProbabilities.length; categoryID++) { int categoryCount = categoryCounts[categoryID]; float probability = categoryProbabilities[categoryID]; if (categoryCount > 0 && probability > 0.0f) { String categoryName = categoryIDToName.get(categoryID); ScoreDistribution distribution = new ScoreDistribution(categoryName, categoryCount); distribution.setProbability((double) probability); modelNode.getScoreDistributions().add(distribution); } } } else { NumericPrediction numericPrediction = (NumericPrediction) prediction; modelNode.setScore(Float.toString(numericPrediction.getPrediction())); } } else { DecisionNode decisionNode = (DecisionNode) treeNode; Decision decision = decisionNode.getDecision(); Node positiveModelNode = new Node(); positiveModelNode.setId(modelNode.getId() + '+'); modelNode.getNodes().add(positiveModelNode); Node negativeModelNode = new Node(); negativeModelNode.setId(modelNode.getId() + '-'); modelNode.getNodes().add(negativeModelNode); modelNode.setDefaultChild( decision.getDefaultDecision() ? positiveModelNode.getId() : negativeModelNode.getId()); modelNodes.add(positiveModelNode); modelNodes.add(negativeModelNode); treeNodes.add(new Pair<TreeNode, Decision>(decisionNode.getRight(), decision)); treeNodes.add(new Pair<TreeNode, Decision>(decisionNode.getLeft(), null)); } } TreeModel treeModel = new TreeModel(miningSchema, root, miningFunctionType); treeModel.setSplitCharacteristic(TreeModel.SplitCharacteristic.BINARY_SPLIT); treeModel.setMissingValueStrategy(MissingValueStrategyType.DEFAULT_CHILD); Segment segment = new Segment(); segment.setId(Integer.toString(treeID)); segment.setPredicate(new True()); segment.setModel(treeModel); segment.setWeight(forest.getWeights()[treeID]); return segment; }