Example usage for java.util Queue poll

List of usage examples for java.util Queue poll

Introduction

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

Prototype

E poll();

Source Link

Document

Retrieves and removes the head of this queue, or returns null if this queue is empty.

Usage

From source file:info.magnolia.vaadin.periscope.result.SupplierUtil.java

/**
 * Highlight (using HTML tags) all occurrences of a query string, ignoring case.
 *
 * @param text Text in which parts should be highlighted
 * @param query Parts to highlight//from w  ww. j a  va 2s  . c  o m
 * @return Highlighted string
 */
public static String highlight(final String text, final String query) {
    if (StringUtils.isBlank(query)) {
        return text;
    }

    final List<Integer> startIndices = allIndicesOf(text, query);
    final List<Integer> endIndices = startIndices.stream().map(i -> i + query.length()).collect(toList());

    // we run back to front to not mess up indices when inserting tags
    Collections.reverse(startIndices);
    Collections.reverse(endIndices);
    Queue<Integer> startQueue = new LinkedList<>(startIndices);
    Queue<Integer> endQueue = new LinkedList<>(endIndices);

    StringBuilder highlighted = new StringBuilder(text);
    while (!startQueue.isEmpty() || !endQueue.isEmpty()) {
        final Integer startCandidate = startQueue.peek();
        final Integer endCandidate = endQueue.peek();

        if (startCandidate != null && (endCandidate == null || startCandidate > endCandidate)) {
            highlighted.insert(startCandidate, "<strong>");
            startQueue.poll();
        } else {
            highlighted.insert(endCandidate, "</strong>");
            endQueue.poll();
        }
    }

    return highlighted.toString();
}

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 o  m
    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.linkedin.pinot.core.startree.StarTreeSerDe.java

/**
 * Helper method to write the star tree nodes for Star Tree off-heap format
 *
 * @param starTree//from   w  ww  .  j  av  a2  s  .com
 * @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:au.org.ala.delta.editor.EditorPreferences.java

/**
 * Adds the supplied filename to the top of the most recently used files.
 * /*  ww w  . j a v  a  2s.  co  m*/
 * @param filename
 */
public static void addFileToMRU(String filename) {

    Queue<String> q = new LinkedList<String>();

    q.add(filename);

    String[] existingFiles = getPreviouslyUsedFiles();
    if (existingFiles != null) {
        for (String existingFile : existingFiles) {
            if (!q.contains(existingFile)) {
                q.add(existingFile);
            }
        }
    }

    StringBuilder b = new StringBuilder();
    for (int i = 0; i < MAX_SIZE_MRU && q.size() > 0; ++i) {
        if (i > 0) {
            b.append(MRU_SEPARATOR);
        }
        b.append(q.poll());
    }

    Preferences prefs = Preferences.userNodeForPackage(DeltaEditor.class);
    prefs.put(MRU_PREF_KEY, b.toString());
    try {
        prefs.sync();
    } catch (BackingStoreException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.googlecode.fightinglayoutbugs.helpers.ImageHelper.java

/**
 * Find the outlines of all areas where <code>pixels[x][y]</code> is <code>true</code>.
 *///from w ww.  ja v a  2 s  . co m
public static boolean[][] findOutlines(boolean[][] pixels) {
    int w = pixels.length;
    int h = pixels[0].length;
    int w1 = w - 1;
    int h1 = h - 1;
    boolean[][] outlines = new boolean[w][h];
    // Find starting point ...
    int x0 = 0;
    int y0 = 0;
    // Look for starting point on top border ...
    while (x0 < w && pixels[x0][y0]) {
        // ... and bottom border ...
        if (!pixels[x0][h1]) {
            y0 = h1;
            break;
        }
        ++x0;
    }
    if (x0 == w) {
        // Look for starting point on left border ...
        x0 = 1;
        // ... and right border ...
        while (y0 < h && pixels[x0][y0]) {
            if (!pixels[w1][y0]) {
                x0 = w1;
                break;
            }
            ++y0;
        }
    }
    if (y0 == h) {
        // No starting point found, therefore ...
        return outlines;
    }
    // Find outlines ...
    Queue<Point> todo = new LinkedList<Point>();
    todo.add(new Point(x0, y0));
    boolean[][] visited = new boolean[w][h];
    while (!todo.isEmpty()) {
        Point p = todo.poll();
        int x = p.x;
        int y = p.y;
        if (!visited[x][y]) {
            visited[x][y] = true;
            if (!pixels[x][y]) {
                // Compare with pixel above ...
                if (y > 0) {
                    int y1 = y - 1;
                    if (pixels[x][y1]) {
                        outlines[x][y] = true;
                    } else if (!visited[x][y1]) {
                        todo.add(new Point(x, y1));
                    }
                }
                // Compare with pixel to the right ...
                if (x < w1) {
                    int x1 = x + 1;
                    if (pixels[x1][y]) {
                        outlines[x][y] = true;
                    } else if (!visited[x1][y]) {
                        todo.add(new Point(x1, y));
                    }
                }
                // Compare with pixel below ...
                if (y < h1) {
                    int y1 = y + 1;
                    if (pixels[x][y1]) {
                        outlines[x][y] = true;
                    } else if (!visited[x][y1]) {
                        todo.add(new Point(x, y1));
                    }
                }
                // Compare with pixel to the left ...
                if (x > 0) {
                    int x1 = x - 1;
                    if (pixels[x1][y]) {
                        outlines[x][y] = true;
                    } else if (!visited[x1][y]) {
                        todo.add(new Point(x1, y));
                    }
                }
            }
        }
    }
    return outlines;
}

From source file:org.kuali.rice.krad.uif.lifecycle.ViewLifecycleUtils.java

/**
 * Return the lifecycle elements of the specified type from the given list
 *
 * <p>/*ww  w  . ja v  a  2 s  .  c om*/
 * Elements that match, implement or are extended from the specified {@code elementType} are
 * returned in the result. If an element is a parent to other elements then these child elements
 * are searched for matching types as well.
 * </p>
 *
 * @param items list of elements from which to search
 * @param elementType the class or interface of the element type to return
 * @param <T> the type of the elements that are returned
 * @return List of matching elements
 */
public static <T extends LifecycleElement> List<T> getElementsOfTypeDeep(
        Collection<? extends LifecycleElement> items, Class<T> elementType) {
    if (items == null) {
        return Collections.emptyList();
    }

    List<T> elements = Collections.emptyList();

    @SuppressWarnings("unchecked")
    Queue<LifecycleElement> elementQueue = RecycleUtils.getInstance(LinkedList.class);
    elementQueue.addAll(items);

    try {
        while (!elementQueue.isEmpty()) {
            LifecycleElement currentElement = elementQueue.poll();
            if (currentElement == null) {
                continue;
            }

            if (elementType.isInstance(currentElement)) {
                if (elements.isEmpty()) {
                    elements = new ArrayList<T>();
                }

                elements.add(elementType.cast(currentElement));
            }

            elementQueue.addAll(getElementsForLifecycle(currentElement).values());
        }
    } finally {
        elementQueue.clear();
        RecycleUtils.recycle(elementQueue);
    }
    return elements;
}

From source file:org.kuali.rice.krad.uif.lifecycle.ViewLifecycleUtils.java

/**
 * Get nested elements of the type specified one layer deep; this defers from
 * getElementsOfTypeShallow because it does NOT include itself as a match if it also matches the
 * type being requested.// ww w . ja  v a 2 s .c o  m
 *
 * @param element instance to get children for
 * @param elementType type for element to return
 * @param <T> type of element that will be returned
 * @return list of child elements with the given type
 */
public static <T extends LifecycleElement> List<T> getNestedElementsOfTypeShallow(LifecycleElement element,
        Class<T> elementType) {
    if (element == null) {
        return Collections.emptyList();
    }

    List<T> elements = Collections.emptyList();

    @SuppressWarnings("unchecked")
    Queue<LifecycleElement> elementQueue = RecycleUtils.getInstance(LinkedList.class);
    try {
        elementQueue.add(element);

        while (!elementQueue.isEmpty()) {
            LifecycleElement currentElement = elementQueue.poll();
            if (currentElement == null) {
                continue;
            }

            if (elementType.isInstance(currentElement) && currentElement != element) {
                if (elements.isEmpty()) {
                    elements = new ArrayList<T>();
                }

                elements.add(elementType.cast(currentElement));
            }

            for (LifecycleElement nestedElement : getElementsForLifecycle(currentElement).values()) {
                if (!(nestedElement instanceof Component)) {
                    elementQueue.offer(nestedElement);
                }
            }
        }
    } finally {
        elementQueue.clear();
        RecycleUtils.recycle(elementQueue);
    }
    return elements;
}

From source file:com.amalto.core.jobox.util.JoboxUtil.java

public static String parseMainClassFromJCL(String content) throws IOException {
    String mainClass = null;//from   ww  w.  jav a2  s. co m
    BufferedReader reader = new BufferedReader(new StringReader(content));
    String line;
    while ((line = reader.readLine()) != null) {
        if (line.length() > 0) {
            boolean hasJAL = false;
            Queue<String> myQueue = new LinkedList<String>();
            String[] tokens = line.split("\\s"); //$NON-NLS-1$
            for (String token : tokens) {
                if (hasJAL && token.trim().length() > 0) {
                    myQueue.offer(token.trim());
                }
                if ("java".equals(token)) { //$NON-NLS-1$
                    hasJAL = true;
                }
            }
            if (hasJAL) {
                String str;
                boolean needConsume = false;
                while ((str = myQueue.poll()) != null) {
                    if (!str.startsWith("-")) { //$NON-NLS-1$
                        if (needConsume) {
                            needConsume = false;// consume
                        } else {
                            mainClass = str;
                            break;
                        }
                    }
                    if (str.startsWith("-")) { //$NON-NLS-1$
                        str = str.substring(1);
                        if (str.startsWith("-")) { //$NON-NLS-1$
                            str = str.substring(1);
                        }
                        // FIXME is there any more?
                        if ("cp".equals(str) || "classpath".equals(str) || "jar".equals(str)) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                            needConsume = true;
                        }
                    }
                }
            }
        }
    }
    return mainClass;
}

From source file:org.exoplatform.services.cms.impl.Utils.java

/**
 * // ww w . j ava  2  s . c  o  m
 * @param     : node
 * @param     : keepInTrash true if the link will be move to trash, otherwise set by false
 * @throws    : Exception
 * @Objective : Remove all the link of a deleted node
 * @Author    : Nguyen The Vinh from ECM of eXoPlatform
 *              vinh.nguyen@exoplatform.com
 */
public static void removeDeadSymlinks(Node node, boolean keepInTrash) throws Exception {
    if (isInTrash(node)) {
        return;
    }
    LinkManager linkManager = WCMCoreUtils.getService(LinkManager.class);
    TrashService trashService = WCMCoreUtils.getService(TrashService.class);
    SessionProvider sessionProvider = SessionProvider.createSystemProvider();
    Queue<Node> queue = new LinkedList<Node>();
    queue.add(node);

    try {
        while (!queue.isEmpty()) {
            node = queue.poll();
            if (!node.isNodeType(EXO_SYMLINK)) {
                try {
                    List<Node> symlinks = linkManager.getAllLinks(node, EXO_SYMLINK);

                    // Before removing symlinks, We order symlinks by name descending, index descending.
                    // Example: symlink[3],symlink[2], symlink[1] to avoid the case that
                    // the index of same name symlink automatically changed to increasing one by one
                    Collections.sort(symlinks, new Comparator<Node>() {
                        @Override
                        public int compare(Node node1, Node node2) {
                            try {
                                String name1 = node1.getName();
                                String name2 = node2.getName();
                                if (name1.equals(name2)) {
                                    int index1 = node1.getIndex();
                                    int index2 = node2.getIndex();
                                    return -1 * ((Integer) index1).compareTo(index2);
                                }
                                return -1 * name1.compareTo(name2);
                            } catch (RepositoryException e) {
                                return 0;
                            }
                        }
                    });

                    for (Node symlink : symlinks) {
                        synchronized (symlink) {
                            if (keepInTrash) {
                                trashService.moveToTrash(symlink, sessionProvider, 1);
                            } else {
                                symlink.remove();
                            }
                        }
                    }
                } catch (Exception e) {
                    if (LOG.isWarnEnabled()) {
                        LOG.warn(e.getMessage());
                    }
                }
                for (NodeIterator iter = node.getNodes(); iter.hasNext();) {
                    queue.add(iter.nextNode());
                }
            }
        }
    } catch (Exception e) {
        if (LOG.isWarnEnabled()) {
            LOG.warn(e.getMessage());
        }
    } finally {
        sessionProvider.close();
    }
}

From source file:org.apache.hadoop.hive.ql.lockmgr.zookeeper.ZooKeeperHiveLockManager.java

/**
 * @param conf        Hive configuration
 * @param zkpClient   The ZooKeeper client
 * @param key         The object to be compared against - if key is null, then get all locks
 **///  w  w  w. j  a va2s .  c om
private static List<HiveLock> getLocks(HiveConf conf, HiveLockObject key, String parent,
        boolean verifyTablePartition, boolean fetchData) throws LockException {
    List<HiveLock> locks = new ArrayList<HiveLock>();
    List<String> children;
    boolean recurse = true;
    String commonParent;

    try {
        if (key != null) {
            commonParent = "/" + parent + "/" + key.getName();
            children = curatorFramework.getChildren().forPath(commonParent);
            recurse = false;
        } else {
            commonParent = "/" + parent;
            children = curatorFramework.getChildren().forPath(commonParent);
        }
    } catch (Exception e) {
        // no locks present
        return locks;
    }

    Queue<String> childn = new LinkedList<String>();
    if (children != null && !children.isEmpty()) {
        for (String child : children) {
            childn.add(commonParent + "/" + child);
        }
    }

    while (true) {
        String curChild = childn.poll();
        if (curChild == null) {
            return locks;
        }

        if (recurse) {
            try {
                children = curatorFramework.getChildren().forPath(curChild);
                for (String child : children) {
                    childn.add(curChild + "/" + child);
                }
            } catch (Exception e) {
                // nothing to do
            }
        }

        HiveLockMode mode = getLockMode(curChild);
        if (mode == null) {
            continue;
        }

        HiveLockObjectData data = null;
        // set the lock object with a dummy data, and then do a set if needed.
        HiveLockObject obj = getLockObject(conf, curChild, mode, data, parent, verifyTablePartition);
        if (obj == null) {
            continue;
        }

        if ((key == null) || (obj.getName().equals(key.getName()))) {

            if (fetchData) {
                try {
                    data = new HiveLockObjectData(
                            new String(curatorFramework.getData().watched().forPath(curChild)));
                    data.setClientIp(clientIp);
                } catch (Exception e) {
                    LOG.error("Error in getting data for " + curChild, e);
                    // ignore error
                }
            }
            obj.setData(data);
            HiveLock lck = (HiveLock) (new ZooKeeperHiveLock(curChild, obj, mode));
            locks.add(lck);
        }
    }
}