Example usage for java.util Queue isEmpty

List of usage examples for java.util Queue isEmpty

Introduction

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

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this collection contains no elements.

Usage

From source file:org.apache.jackrabbit.oak.run.SegmentUtils.java

private static void debugFileStore(FileStore store) {
    Map<SegmentId, List<SegmentId>> idmap = Maps.newHashMap();
    int dataCount = 0;
    long dataSize = 0;
    int bulkCount = 0;
    long bulkSize = 0;

    ((Logger) getLogger(SegmentTracker.class)).setLevel(Level.OFF);
    RecordUsageAnalyser analyser = new RecordUsageAnalyser();

    for (SegmentId id : store.getSegmentIds()) {
        if (id.isDataSegmentId()) {
            Segment segment = id.getSegment();
            dataCount++;/*  w ww .  j ava2s  . co  m*/
            dataSize += segment.size();
            idmap.put(id, segment.getReferencedIds());
            analyseSegment(segment, analyser);
        } else if (id.isBulkSegmentId()) {
            bulkCount++;
            bulkSize += id.getSegment().size();
            idmap.put(id, Collections.<SegmentId>emptyList());
        }
    }
    System.out.println("Total size:");
    System.out.format("%s in %6d data segments%n", byteCountToDisplaySize(dataSize), dataCount);
    System.out.format("%s in %6d bulk segments%n", byteCountToDisplaySize(bulkSize), bulkCount);
    System.out.println(analyser.toString());

    Set<SegmentId> garbage = newHashSet(idmap.keySet());
    Queue<SegmentId> queue = Queues.newArrayDeque();
    queue.add(store.getHead().getRecordId().getSegmentId());
    while (!queue.isEmpty()) {
        SegmentId id = queue.remove();
        if (garbage.remove(id)) {
            queue.addAll(idmap.get(id));
        }
    }
    dataCount = 0;
    dataSize = 0;
    bulkCount = 0;
    bulkSize = 0;
    for (SegmentId id : garbage) {
        if (id.isDataSegmentId()) {
            dataCount++;
            dataSize += id.getSegment().size();
        } else if (id.isBulkSegmentId()) {
            bulkCount++;
            bulkSize += id.getSegment().size();
        }
    }
    System.out.format("%nAvailable for garbage collection:%n");
    System.out.format("%s in %6d data segments%n", byteCountToDisplaySize(dataSize), dataCount);
    System.out.format("%s in %6d bulk segments%n", byteCountToDisplaySize(bulkSize), bulkCount);
    System.out.format("%n%s", new PCMAnalyser(store).toString());
}

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

/**
 * Return the lifecycle elements of the specified type from the given list
 *
 * <p>// w ww .  j ava2  s  .  c o  m
 * 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:com.googlecode.fightinglayoutbugs.helpers.ImageHelper.java

/**
 * Find the outlines of all areas where <code>pixels[x][y]</code> is <code>true</code>.
 *//*from  w w  w .  j  a 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

/**
 * 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.//from ww  w.j a  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:org.apache.jackrabbit.oak.run.SegmentTarUtils.java

private static void debugFileStore(FileStore store) {
    Map<SegmentId, List<SegmentId>> idmap = Maps.newHashMap();
    int dataCount = 0;
    long dataSize = 0;
    int bulkCount = 0;
    long bulkSize = 0;

    ((Logger) getLogger(SegmentTracker.class)).setLevel(Level.OFF);
    RecordUsageAnalyser analyser = new RecordUsageAnalyser(store.getReader());

    for (SegmentId id : store.getSegmentIds()) {
        if (id.isDataSegmentId()) {
            Segment segment = id.getSegment();
            dataCount++;/*from w ww . j  ava2 s . c om*/
            dataSize += segment.size();
            idmap.put(id, segment.getReferencedIds());
            analyseSegment(segment, analyser);
        } else if (id.isBulkSegmentId()) {
            bulkCount++;
            bulkSize += id.getSegment().size();
            idmap.put(id, Collections.<SegmentId>emptyList());
        }
    }
    System.out.println("Total size:");
    System.out.format("%s in %6d data segments%n", byteCountToDisplaySize(dataSize), dataCount);
    System.out.format("%s in %6d bulk segments%n", byteCountToDisplaySize(bulkSize), bulkCount);
    System.out.println(analyser.toString());

    Set<SegmentId> garbage = newHashSet(idmap.keySet());
    Queue<SegmentId> queue = Queues.newArrayDeque();
    queue.add(store.getRevisions().getHead().getSegmentId());
    while (!queue.isEmpty()) {
        SegmentId id = queue.remove();
        if (garbage.remove(id)) {
            queue.addAll(idmap.get(id));
        }
    }
    dataCount = 0;
    dataSize = 0;
    bulkCount = 0;
    bulkSize = 0;
    for (SegmentId id : garbage) {
        if (id.isDataSegmentId()) {
            dataCount++;
            dataSize += id.getSegment().size();
        } else if (id.isBulkSegmentId()) {
            bulkCount++;
            bulkSize += id.getSegment().size();
        }
    }
    System.out.format("%nAvailable for garbage collection:%n");
    System.out.format("%s in %6d data segments%n", byteCountToDisplaySize(dataSize), dataCount);
    System.out.format("%s in %6d bulk segments%n", byteCountToDisplaySize(bulkSize), bulkCount);
}

From source file:com.baidu.rigel.biplatform.ac.util.DataModelUtils.java

/**
 * DataModel??/*  w  ww. j ava  2  s .c  o m*/
 * 
 * @param dataModel DataModel
 * @throws IllegalAccessException 
 */
private static void buildSortSummary(DataModel dataModel) throws IllegalAccessException {
    List<HeadField> rowLeafs = getLeafNodeList(dataModel.getRowHeadFields());
    if (CollectionUtils.isNotEmpty(rowLeafs)) {
        if (dataModel.getOperateIndex() > rowLeafs.get(0).getCompareDatas().size()) {
            throw new IllegalAccessException("can not access operate index:" + dataModel.getOperateIndex());
        }
        for (HeadField rowHeadField : dataModel.getRowHeadFields()) {
            List<HeadField> leafFileds = rowHeadField.getLeafFileds(true);
            if (CollectionUtils.isNotEmpty(leafFileds)) {

                Queue<HeadField> queue = new LinkedList<HeadField>(leafFileds);
                while (!queue.isEmpty()) {
                    HeadField leafFiled = queue.remove();
                    if (CollectionUtils.isNotEmpty(leafFiled.getCompareDatas())) {
                        leafFiled
                                .setSummarizeData(leafFiled.getCompareDatas().get(dataModel.getOperateIndex()));
                    }
                    HeadField parent = null;
                    if (leafFiled.getParent() != null) {
                        parent = leafFiled.getParent();
                    } else if (leafFiled.getParentLevelField() != null) {
                        parent = leafFiled.getParentLevelField();
                        if (!queue.contains(parent)) {
                            queue.add(parent);
                        }
                    }

                    if (parent != null && CollectionUtils.isEmpty(parent.getCompareDatas())) {
                        parent.setSummarizeData(BigDecimalUtils.addBigDecimal(parent.getSummarizeData(),
                                leafFiled.getSummarizeData()));
                    }
                }
            }

        }
    }
}

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

/**
 * /*from  ww  w. java 2 s  .  co 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:com.streamsets.pipeline.lib.util.ProtobufTypeUtil.java

private static List<DescriptorProtos.DescriptorProto> getAllMessageTypesInDescriptorProto(
        DescriptorProtos.FileDescriptorProto fileDescriptorProto) {
    Queue<DescriptorProtos.DescriptorProto> queue = new LinkedList<>();
    queue.addAll(fileDescriptorProto.getMessageTypeList());
    List<DescriptorProtos.DescriptorProto> result = new ArrayList<>();
    while (!queue.isEmpty()) {
        DescriptorProtos.DescriptorProto descriptorProto = queue.poll();
        queue.addAll(descriptorProto.getNestedTypeList());
        result.add(descriptorProto);/*from   w  w  w.  java 2 s .c  o  m*/
    }
    return result;
}

From source file:com.core.controller.AlgoritmoController.java

public static Solucion busquedaAmplitud(Grafo g, String nodoInicioNombre, String nodoFinNombre) { //funcionna bien
    Solucion result = new Solucion();
    result.setPasos("Algoritmo de Busqueda Primero en Amplitud");
    result.agregarPaso("Cantidad de nodos: " + g.getNodos().size());
    result.agregarPaso("Cantidad de aristas: " + g.getAristas().size());
    Queue<String> cola = new LinkedList<>();
    Queue<String> padresCola = new LinkedList<>();
    List<String> explorados = new ArrayList<>(); //LISTA-NODOS
    List<String> padresExplorados = new ArrayList<>();
    String nodoActual, nodoPadre;
    cola.add(nodoInicioNombre);// w  ww. j  a v  a 2s  .c  o m
    padresCola.add("#");
    while (true) {
        System.out.println(cola);
        if (cola.isEmpty()) {
            result.agregarPaso("No se encontro el nodo destino");
            break;
        }
        nodoActual = cola.poll();
        nodoPadre = padresCola.poll();
        explorados.add(nodoActual);
        padresExplorados.add(nodoPadre);
        if (nodoActual.equals(nodoFinNombre)) {
            result.agregarPaso("Nodo fin alcanzado"); //Mostrar camino
            String nodo = nodoActual;
            String secuenciaResultado = "";
            while (nodo != "#") {
                secuenciaResultado = nodo + " " + secuenciaResultado;
                nodo = padresExplorados.get(explorados.indexOf(nodo));
            }
            result.agregarPaso("Camino solucion: " + secuenciaResultado);
            break;
        }
        List<String> vecinos = g.nodosVecinos(nodoActual);
        Iterator<String> i = vecinos.iterator();
        while (i.hasNext()) {
            String a = i.next();
            if (!explorados.contains(a) && !cola.contains(a)) {
                cola.add(a);
                padresCola.add(nodoActual);
            }
        }
    }
    //Verifico la solucion y la guardo en Solucion
    if (result.getPasos().contains("Nodo fin alcanzado")) {
        String solucion = result.getPasos().split("Nodo fin alcanzado\n")[1];
        String[] array = solucion.split(" ");
        //            ArrayUtils.reverse(array);
        for (String nombreNodo : array) {
            System.out.println("--------------------------------------");
            for (Map.Entry<String, Nodo> n : g.getNodos().entrySet()) {
                System.out.println("Comparando " + n.getKey() + " con " + nombreNodo);
                if (n.getKey().equals(nombreNodo)) {
                    System.out.println("Son iguales! Agregando " + nombreNodo + " a la lista");
                    result.getNodos().add(n.getValue());
                }
            }
        }

        System.out.println(
                "Nodos del resultado final en la lista: " + Arrays.toString(result.getNodos().toArray()));
    }
    return result;
}

From source file:org.apache.lens.cube.parse.HQLParser.java

/**
 * Breadth first traversal of AST//from w  ww.j a va 2  s  . co  m
 *
 * @param root      node from where to start bft
 * @param visitor   action to take on each visit
 * @throws LensException
 */
public static void bft(ASTNode root, ASTNodeVisitor visitor) throws LensException {
    if (root == null) {
        throw new NullPointerException("Root cannot be null");
    }

    if (visitor == null) {
        throw new NullPointerException("Visitor cannot be null");
    }
    Queue<TreeNode> queue = new LinkedList<>();
    queue.add(new TreeNode(null, root));

    while (!queue.isEmpty()) {
        TreeNode node = queue.poll();
        visitor.visit(node);
        ASTNode astNode = node.getNode();
        for (int i = 0; i < astNode.getChildCount(); i++) {
            queue.offer(new TreeNode(node, (ASTNode) astNode.getChild(i)));
        }
    }
}