Example usage for java.util Queue add

List of usage examples for java.util Queue add

Introduction

In this page you can find the example usage for java.util Queue add.

Prototype

boolean add(E e);

Source Link

Document

Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available.

Usage

From source file:org.xwiki.xdomviz.Main.java

/**
 * <p>//w w  w.  jav a2  s  . co m
 * This method creates an isomorphic tree using node structures instead of blocks. This is necessary because a
 * single XDOM's block can be a child of multiple parents but the getParent() method is able to return only a single
 * parent. Using this alternative representation, full parent information is correctly stored in each node.
 * </p>
 * <p>
 * The node tree representation allows also the manipulation of the tree structure because all the attributes of a
 * node are mutable.
 * </p>
 * 
 * @param xdom
 * @return The root node of the new tree.
 */
private static Node createNodeTree(XDOM xdom) {
    // The list of the nodes created from the visited XDOM's blocks.
    List<Node> nodes = new ArrayList<Node>();

    // Breadth first visit of the XDOM.
    Queue<Block> blocksQueue = new ArrayDeque<Block>();
    blocksQueue.add(xdom.getRoot());
    while (!blocksQueue.isEmpty()) {
        Block block = blocksQueue.poll();

        // If there isn't a node corresponding to this block, create it!
        Node parentNode = findNode(nodes, block);
        if (parentNode == null) {
            parentNode = new Node(block);
            nodes.add(parentNode);
        }

        for (Block child : block.getChildren()) {
            blocksQueue.add(child);

            // If there isn't a node corresponding to this child-block, create it!
            Node childNode = findNode(nodes, child);
            if (childNode == null) {
                childNode = new Node(child);
                nodes.add(childNode);
            }

            // Link parent and child child.
            parentNode.getChildren().add(childNode);
            childNode.getParents().add(parentNode);
        }
    }

    return findNode(nodes, xdom.getRoot());
}

From source file:org.xwiki.xdomviz.Main.java

/**
 * <p>/*from   w ww. j  a  v  a 2 s.co  m*/
 * This method performs a normalization of the tree by removing all the multi-edges (due to a node having multiple
 * parents). This happens often with SpaceBlocks, which are reused all over the XDOM. The algorithm performs a
 * breadth first visit. For each visited node, it checks how many times a child occurs in its children list. If a
 * child occurs more than once, then we create new nodes, one for each occurrence.
 * </p>
 * <p>
 * The node tree corresponding to the XDOM of "this is a test" is:
 * </p>
 * <ul>
 * <li>XDOM -> P</li>
 * <li>P -> "This"</li>
 * <li>P -> S (3 edges, each one representing a space)</li>
 * <li>P -> "is"</li>
 * <li>P -> "a"</li>
 * <li>P -> "test"</li>
 * </ul>
 * <p>
 * The normalized tree will be:
 * </p>
 * <ul>
 * <li>XDOM -> P</li>
 * <li>P -> "This"</li>
 * <li>P -> S</li>
 * <li>P -> "is"</li>
 * <li>P -> S</li>
 * <li>P -> "a"</li>
 * <li>P -> S</li>
 * <li>P -> "test"</li>
 * </ul>
 * <p>
 * In a normalized tree, each node has one and only one parent.
 * </p>
 * 
 * @param root The root node of the tree.
 * @return The root node of the normalized tree.
 */
private static Node normalize(Node root) {
    // Breadth first visit of the XDOM to assign simple ids to nodes.
    Queue<Node> nodesQueue = new ArrayDeque<Node>();
    nodesQueue.add(root);
    while (!nodesQueue.isEmpty()) {
        Node node = nodesQueue.poll();

        // This map contains, for the current node, where are the occurrences in the children list of each child.
        Map<Node, List<Integer>> nodeToIndexesMap = new HashMap<Node, List<Integer>>();

        int i = 0;
        // For each child calculate store the its position in the indexes list.
        for (Node child : node.getChildren()) {
            List<Integer> indexes = nodeToIndexesMap.get(child);
            if (indexes == null) {
                indexes = new ArrayList<Integer>();
                nodeToIndexesMap.put(child, indexes);
            }
            indexes.add(i);
            i++;
        }

        for (Node child : nodeToIndexesMap.keySet()) {
            List<Integer> indexes = nodeToIndexesMap.get(child);
            // If the indexes size is > 1 then a child occurs multiple times in a
            if (indexes.size() > 1) {
                for (Integer index : indexes) {
                    Node newNode = new Node(child.getBlock());
                    newNode.getParents().add(node);
                    newNode.getChildren().addAll(child.getChildren());
                    node.getChildren().set(index, newNode);
                }
            }
        }

        for (Node child : node.getChildren()) {
            nodesQueue.add(child);
        }
    }

    return root;
}

From source file:org.xwiki.xdomviz.Main.java

/**
 * <p>//from  w ww. j av 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:org.apache.mahout.clustering.lda.LDAPrintTopics.java

private static List<Queue<Pair<String, Double>>> topWordsForTopics(String dir, Configuration job,
        List<String> wordList, int numWordsToPrint) {
    List<Queue<Pair<String, Double>>> queues = Lists.newArrayList();
    Map<Integer, Double> expSums = Maps.newHashMap();
    for (Pair<IntPairWritable, DoubleWritable> record : new SequenceFileDirIterable<IntPairWritable, DoubleWritable>(
            new Path(dir, "part-*"), PathType.GLOB, null, null, true, job)) {
        IntPairWritable key = record.getFirst();
        int topic = key.getFirst();
        int word = key.getSecond();
        ensureQueueSize(queues, topic);//  w  w  w.j  a  v a 2  s .  c  o  m
        if (word >= 0 && topic >= 0) {
            double score = record.getSecond().get();
            if (expSums.get(topic) == null) {
                expSums.put(topic, 0.0);
            }
            expSums.put(topic, expSums.get(topic) + Math.exp(score));
            String realWord = wordList.get(word);
            maybeEnqueue(queues.get(topic), realWord, score, numWordsToPrint);
        }
    }
    for (int i = 0; i < queues.size(); i++) {
        Queue<Pair<String, Double>> queue = queues.get(i);
        Queue<Pair<String, Double>> newQueue = new PriorityQueue<Pair<String, Double>>(queue.size());
        double norm = expSums.get(i);
        for (Pair<String, Double> pair : queue) {
            newQueue.add(new Pair<String, Double>(pair.getFirst(), Math.exp(pair.getSecond()) / norm));
        }
        queues.set(i, newQueue);
    }
    return queues;
}

From source file:org.apache.tajo.rpc.RpcChannelFactory.java

protected static Queue<EventLoopGroup> createClientEventloopGroups(ClientChannelId clientId, int workerNum) {
    int defaultMaxObjectCount = defaultMaxKeyPoolCount.get(clientId);
    Queue<EventLoopGroup> loopGroupQueue = new ConcurrentLinkedQueue<EventLoopGroup>();
    eventLoopGroupPool.put(clientId, loopGroupQueue);

    for (int objectIdx = 0; objectIdx < defaultMaxObjectCount; objectIdx++) {
        loopGroupQueue.add(createClientEventloopGroup(clientId.name(), workerNum));
    }// ww w. ja v a2s. c  o m

    return loopGroupQueue;
}

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);

    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);
            }//from   ww w  .j av a2  s .co  m

            if (!visited.contains(predecessor)) {
                verticesToTest.add(predecessor);
            }
        }
        visited.add(vertex);
    }
}

From source file:org.apache.mahout.clustering.lda.LDAPrintTopics.java

private static void maybeEnqueue(Queue<Pair<String, Double>> q, String word, double score,
        int numWordsToPrint) {
    if (q.size() >= numWordsToPrint && score > q.peek().getSecond()) {
        q.poll();/*from w  w w .java 2 s.  c o  m*/
    }
    if (q.size() < numWordsToPrint) {
        q.add(new Pair<String, Double>(word, score));
    }
}

From source file:com.demandware.vulnapp.util.Helpers.java

/**
 * Given a root dir and a file name, search all subdirectories for the file. 
 * /*from  ww w  . j  a v a2s .c om*/
 * @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:es.darkhogg.hazelnutt.Hazelnutt.java

/**
 * Terminates the application in at most <i>time</i> milliseconds for
 * every alive thread. /*  www  . j a v  a  2s  .  co 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  w ww.j  a  v a  2s .  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();

}