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.orekit.models.earth.tessellation.EllipsoidTessellator.java

/** Expand a mesh so it surrounds at least one connected part of a zone.
 * <p>/*from   w  w  w .j a  va2 s  .co  m*/
 * This part of mesh expansion is neighbors based. It includes the seed
 * node neighbors, and their neighbors, and the neighbors of their
 * neighbors until the path-connected sub-parts of the zone these nodes
 * belong to are completely surrounded by the mesh taxicab boundary.
 * </p>
 * @param mesh mesh to expand
 * @param seeds seed nodes (already in the mesh) from which to start expansion
 * @param zone zone to mesh
 * @exception OrekitException if tile direction cannot be computed
 */
private void neighborExpandMesh(final Mesh mesh, final Collection<Mesh.Node> seeds,
        final SphericalPolygonsSet zone) throws OrekitException {

    // mesh expansion loop
    boolean expanding = true;
    final Queue<Mesh.Node> newNodes = new LinkedList<Mesh.Node>();
    newNodes.addAll(seeds);
    while (expanding) {

        // first expansion step: set up the mesh so that all its
        // inside nodes are completely surrounded by at least
        // one layer of outside nodes
        while (!newNodes.isEmpty()) {

            // retrieve an active node
            final Mesh.Node node = newNodes.remove();

            if (node.isInside()) {
                // the node is inside the zone, the mesh must contain its 8 neighbors
                addAllNeighborsIfNeeded(node, mesh, newNodes);
            }

        }

        // second expansion step: check if the loop of outside nodes
        // completely surrounds the zone, i.e. there are no peaks
        // pointing out of the loop between two nodes
        expanding = false;
        final List<Mesh.Node> boundary = mesh.getTaxicabBoundary(false);
        if (boundary.size() > 1) {
            Mesh.Node previous = boundary.get(boundary.size() - 1);
            for (final Mesh.Node node : boundary) {
                if (meetInside(previous.getS2P(), node.getS2P(), zone)) {
                    // part of the mesh boundary is still inside the zone!
                    // the mesh must be expanded again
                    addAllNeighborsIfNeeded(previous, mesh, newNodes);
                    addAllNeighborsIfNeeded(node, mesh, newNodes);
                    expanding = true;
                }
                previous = node;
            }
        }

    }

}

From source file:bwem.map.MapImpl.java

public WalkPosition breadthFirstSearch(final WalkPosition start, final Pred findCond, final Pred visitCond,
        final boolean connect8) {
    if (findCond.isTrue(getData().getMiniTile(start), start, this)) {
        return start;
    }/*  w  w w. j  ava 2  s. c o m*/

    final Set<WalkPosition> visited = new TreeSet<>((a, b) -> {
        int result = Integer.compare(a.getX(), b.getX());
        if (result != 0) {
            return result;
        }
        return Integer.compare(a.getY(), b.getY());
    });
    final Queue<WalkPosition> toVisit = new ArrayDeque<>();

    toVisit.add(start);
    visited.add(start);

    final WalkPosition[] dir8 = { new WalkPosition(-1, -1), new WalkPosition(0, -1), new WalkPosition(1, -1),
            new WalkPosition(-1, 0), new WalkPosition(1, 0), new WalkPosition(-1, 1), new WalkPosition(0, 1),
            new WalkPosition(1, 1) };
    final WalkPosition[] dir4 = { new WalkPosition(0, -1), new WalkPosition(-1, 0), new WalkPosition(1, 0),
            new WalkPosition(0, 1) };
    final WalkPosition[] directions = connect8 ? dir8 : dir4;

    while (!toVisit.isEmpty()) {
        final WalkPosition current = toVisit.remove();
        for (final WalkPosition delta : directions) {
            final WalkPosition next = current.add(delta);
            if (getData().getMapData().isValid(next)) {
                final MiniTile miniTile = getData().getMiniTile(next, CheckMode.NO_CHECK);
                if (findCond.isTrue(miniTile, next, this)) {
                    return next;
                }
                if (visitCond.isTrue(miniTile, next, this) && !visited.contains(next)) {
                    toVisit.add(next);
                    visited.add(next);
                }
            }
        }
    }

    //TODO: Are we supposed to return start or not?
    //        bwem_assert(false);
    throw new IllegalStateException();
    //        return start;
}

From source file:com.github.rinde.rinsim.core.model.road.PlaneRoadModelTest.java

@Test
public void followPath() {
    final MovingRoadUser mru = new TestRoadUser();
    model.addObjectAt(mru, new Point(0, 0));
    final Queue<Point> path = asPath(new Point(0, 0), new Point(5, 0), new Point(5, 5));

    final MoveProgress pp = model.followPath(mru, path, hour());
    assertEquals(asPath(new Point(5, 0), new Point(5, 5)), path);
    assertEquals(1, pp.distance().getValue(), EPSILON);
    assertEquals(hour().getTickLength(), pp.time().getValue(), EPSILON);
    assertEquals(asList(new Point(0, 0)), pp.travelledNodes());
    assertTrue(Point.distance(new Point(1, 0), model.getPosition(mru)) < EPSILON);

    final MoveProgress pp2 = model.followPath(mru, path, hour(5));
    assertEquals(asPath(new Point(5, 5)), path);
    assertEquals(5, pp2.distance().getValue(), EPSILON);
    assertEquals(hour(5).getTickLength(), pp2.time().getValue(), EPSILON);
    assertEquals(asList(new Point(5, 0)), pp2.travelledNodes());
    assertTrue(Point.distance(new Point(5, 1), model.getPosition(mru)) < EPSILON);

    final MoveProgress pp3 = model.followPath(mru, path, hour(50));
    assertTrue(path.isEmpty());
    assertEquals(4, pp3.distance().getValue(), EPSILON);
    assertEquals(hour(4).getTickLength(), pp3.time().getValue(), EPSILON);
    assertEquals(asList(new Point(5, 5)), pp3.travelledNodes());
    assertTrue(Point.distance(new Point(5, 5), model.getPosition(mru)) < EPSILON);
}

From source file:eu.netide.mms.MMSManager.java

private List<MMSStoreEntry> searchRuleGraph(MMSStoreEntry entry) {

    Queue<MMSStoreEntry> queue = new LinkedList<MMSStoreEntry>();
    List<MMSStoreEntry> listToDelete = Lists.newArrayList();
    MMSStoreEntry copyEntry = new DefaultMMSEntry(entry);

    copyEntry.setVisited(true);//w  w  w . j  a  v a  2  s. c  om
    queue.add(copyEntry);

    while (!queue.isEmpty()) {
        MMSStoreEntry v = queue.poll();
        for (MMSStoreEntry w : v.getRuleParents()) {
            MMSStoreEntry copyInside = new DefaultMMSEntry(w);
            if (!copyInside.getVisited()) {
                copyInside.setVisited(true);
                queue.add(copyInside);
                listToDelete.add(w);
            }
        }
    }

    return listToDelete;
}

From source file:alluxio.proxy.s3.S3RestServiceHandler.java

private List<URIStatus> listObjects(AlluxioURI uri, ListBucketOptions listBucketOptions)
        throws FileDoesNotExistException, IOException, AlluxioException {
    List<URIStatus> objects = new ArrayList<>();
    Queue<URIStatus> traverseQueue = new ArrayDeque<>();

    List<URIStatus> children;
    String prefix = listBucketOptions.getPrefix();
    if (prefix != null && prefix.contains(AlluxioURI.SEPARATOR)) {
        AlluxioURI prefixDirUri = new AlluxioURI(uri.getPath() + AlluxioURI.SEPARATOR
                + prefix.substring(0, prefix.lastIndexOf(AlluxioURI.SEPARATOR)));
        children = mFileSystem.listStatus(prefixDirUri);
    } else {//from ww w  . ja v  a 2  s.c  o m
        children = mFileSystem.listStatus(uri);
    }
    traverseQueue.addAll(children);
    while (!traverseQueue.isEmpty()) {
        URIStatus cur = traverseQueue.remove();
        if (!cur.isFolder()) {
            // Alluxio file is an object.
            objects.add(cur);
        } else if (!cur.getName().endsWith(Constants.S3_MULTIPART_TEMPORARY_DIR_SUFFIX)) {
            // The directory is not a temporary directory of multipart upload, list recursively.
            List<URIStatus> curChildren = mFileSystem.listStatus(new AlluxioURI(cur.getPath()));
            if (curChildren.isEmpty()) {
                // An empty Alluxio directory is considered as a valid object.
                objects.add(cur);
            } else {
                traverseQueue.addAll(curChildren);
            }
        }
    }
    return objects;
}

From source file:voldemort.tools.KeyVersionFetcherCLI.java

public boolean sampleStore(StoreDefinition storeDefinition) {
    String storeName = storeDefinition.getName();

    String keysFileName = inDir + System.getProperty("file.separator") + storeName + ".keys";
    File keysFile = new File(keysFileName);
    if (!keysFile.exists()) {
        logger.error("Keys file " + keysFileName + " does not exist!");
        return false;
    }//from w ww. j  av  a2 s .c o m

    String kvFileName = outDir + System.getProperty("file.separator") + storeName + ".kvs";
    File kvFile = new File(kvFileName);
    if (kvFile.exists()) {
        logger.info("Key-Version file " + kvFileName + " exists, so will not sample keys from file "
                + keysFileName + ".");
        return true;
    }

    BaseStoreRoutingPlan storeRoutingPlan = new BaseStoreRoutingPlan(cluster, storeDefinition);
    BufferedReader keyReader = null;
    BufferedWriter kvWriter = null;
    try {
        keyReader = new BufferedReader(new FileReader(keysFileName));
        kvWriter = new BufferedWriter(new FileWriter(kvFileName));

        boolean readAllKeys = false;
        while (!readAllKeys) {
            Queue<Future<String>> futureKVs = new LinkedList<Future<String>>();
            for (int numFetchTasks = 0; numFetchTasks < this.outputBatchSize; numFetchTasks++) {
                String keyLine = keyReader.readLine();
                if (keyLine == null) {
                    readAllKeys = true;
                    break;
                }
                byte[] keyInBytes = ByteUtils.fromHexString(keyLine.trim());
                FetchKeyVersionsTask kvFetcher = new FetchKeyVersionsTask(storeRoutingPlan, keyInBytes);
                Future<String> future = kvFetcherService.submit(kvFetcher);
                futureKVs.add(future);
            }

            if (futureKVs.size() > 0) {
                while (!futureKVs.isEmpty()) {
                    Future<String> future = futureKVs.poll();
                    String keyVersions = future.get();
                    kvWriter.append(keyVersions);
                }
            }
        }
        return true;
    } catch (DecoderException de) {
        logger.error("Could not decode key to sample for store " + storeName, de);
        return false;
    } catch (IOException ioe) {
        logger.error("IOException caught while sampling store " + storeName, ioe);
        return false;
    } catch (InterruptedException ie) {
        logger.error("InterruptedException caught while sampling store " + storeName, ie);
        return false;
    } catch (ExecutionException ee) {
        logger.error("Encountered an execution exception while sampling " + storeName, ee);
        ee.printStackTrace();
        return false;
    } finally {
        if (keyReader != null) {
            try {
                keyReader.close();
            } catch (IOException e) {
                logger.error("IOException caught while trying to close keyReader for store " + storeName, e);
                e.printStackTrace();
            }
        }
        if (kvWriter != null) {
            try {
                kvWriter.close();
            } catch (IOException e) {
                logger.error("IOException caught while trying to close kvWriter for store " + storeName, e);
                e.printStackTrace();
            }
        }
    }
}

From source file:com.bluepowermod.part.tube.TubeLogic.java

/**
 * This method gets the end target and heading for a TubeStack. When the tubestack's target variable is null, this is an exporting item, meaning
 * the returned target will be the TileEntity the item is going to transport to. When the tubestack's target variable is not not, the item is
 * being retrieved to this inventory. The returned target is the inventory the item came/should come from.
 *
 * @param simulate//from  w ww .ja  va 2s  .c  om
 *            The only difference between simulate and not simulate is the fact that the round robin handling will be updated in non-simulate.
 * @param from
 *            The direction this item came from, this direction will never be a valid heading. Is null in normal item routing, as the from
 *            direction IS a valid output.
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
private Pair<ForgeDirection, TileEntity> getHeadingForItem(TubeStack stack, boolean simulate) {

    Map<TubeNode, Integer> distances = new HashMap<TubeNode, Integer>();
    Queue<TubeNode> traversingNodes = new LinkedBlockingQueue<TubeNode>();
    Queue<ForgeDirection> trackingExportDirection = new LinkedBlockingQueue<ForgeDirection>();
    Map<TubeEdge, ForgeDirection> validDestinations = new LinkedHashMap<TubeEdge, ForgeDirection>();// using a LinkedHashMap so the order doesn't
    // change, used for round robin.

    if (getNode() != null) {
        distances.put(getNode(), 0);// make this the origin.
        traversingNodes.add(getNode());
    }

    boolean firstRun = true;
    int closestDest = 0;
    while (!traversingNodes.isEmpty()) {
        TubeNode node = traversingNodes.poll();
        if (node.edges == null)
            node.init();
        ForgeDirection heading = firstRun ? null : trackingExportDirection.poll();
        for (int i = 0; i < 6; i++) {
            if (firstRun)
                heading = ForgeDirection.getOrientation(i);
            if (node.edges != null) {
                TubeEdge edge = node.edges[i];
                if (edge != null && canPassThroughMask(stack.color, edge.colorMask)) {// if this item can travel through this color mask proceed.
                    Integer distance = distances.get(edge.target);
                    if (distance == null || distances.get(node) + edge.distance < distance) {
                        distances.put(edge.target, distances.get(node) + edge.distance);
                        if (edge.target.target instanceof PneumaticTube) {
                            traversingNodes.add(edge.target);
                            trackingExportDirection.add(heading);
                        } else if (stack.getTarget(tube.getWorld()) == null
                                && edge.isValidForExportItem(stack.stack)
                                || stack.heading == null && edge.isValidForImportItem(stack)
                                || stack.heading != null
                                        && stack.getTarget(tube.getWorld()) == edge.target.target
                                        && edge.targetConnectionSide.getOpposite() == stack
                                                .getTargetEntryDir()) {
                            validDestinations.put(edge,
                                    stack.heading == null ? edge.targetConnectionSide : heading);
                        }
                    }
                }
            }
        }

        // Check the distances of the current breadth first search layer. if no points are closer than the currently valid destination(s), we're
        // done searching.
        boolean isDoneSearching = true;
        closestDest = getClosestDestination(validDestinations.keySet(), distances);
        for (TubeNode checkingNode : traversingNodes) {
            if (distances.get(checkingNode) <= closestDest) {
                isDoneSearching = false;
                break;
            }
        }
        if (isDoneSearching)
            break;
        firstRun = false;
    }

    if (validDestinations.size() == 0) {
        if (stack.getTarget(tube.getWorld()) != null && stack.heading != null && !simulate) {
            stack.setTarget(null, ForgeDirection.UNKNOWN);// if we can't reach the retrieving target anymore, reroute as normal.
            return getHeadingForItem(stack, simulate);
        } else {
            return null;
        }
    }

    List<Pair<ForgeDirection, TileEntity>> validDirections = new ArrayList<Pair<ForgeDirection, TileEntity>>();
    for (Map.Entry<TubeEdge, ForgeDirection> entry : validDestinations.entrySet()) {
        if (distances.get(entry.getKey().target) == closestDest) {
            validDirections.add(new ImmutablePair(entry.getValue(), entry.getKey().target.target));
        }
    }

    // handle round robin
    if (!simulate)
        roundRobinCounter++;
    if (roundRobinCounter >= validDirections.size())
        roundRobinCounter = 0;
    return validDirections.get(roundRobinCounter);
}

From source file:com.baifendian.swordfish.common.utils.graph.Graph.java

/**
 * ??, ???, ??:/*from   w w  w . j a v a2 s .co  m*/
 * 1) , ?????
 * 2) ????, , ?
 *
 * @return true  , false ?
 */
public synchronized boolean isConnected() {
    Queue<VK> q = new LinkedList<>();
    Set<VK> hasVisited = new HashSet<>();

    // ?
    Iterator<Map.Entry<VK, VD>> iter = vertices.entrySet().iterator();

    // ,  true
    if (!iter.hasNext()) {
        return true;
    }

    // ????
    Map.Entry<VK, VD> entry = iter.next();

    VK startKey = entry.getKey();

    q.add(startKey);
    hasVisited.add(startKey);

    while (!q.isEmpty()) {
        VK key = q.poll();

        for (VK postKey : getPostNode(key)) {
            if (!hasVisited.contains(postKey)) {
                q.add(postKey);
                hasVisited.add(postKey);
            }
        }

        for (VK preKey : getPreNode(key)) {
            if (!hasVisited.contains(preKey)) {
                q.add(preKey);
                hasVisited.add(preKey);
            }
        }
    }

    return hasVisited.size() == getVertexNumber();
}

From source file:org.apache.falcon.resource.AbstractInstanceManager.java

private LineageGraphResult triage(EntityType entityType, Entity entity, String instanceTime, Cluster cluster)
        throws FalconException {

    Date instanceDate = SchemaHelper.parseDateUTC(instanceTime);
    LineageGraphResult result = new LineageGraphResult();
    Set<String> vertices = new HashSet<>();
    Set<LineageGraphResult.Edge> edges = new HashSet<>();
    Map<String, String> instanceStatusMap = new HashMap<>();

    // queue containing all instances which need to be triaged
    Queue<SchedulableEntityInstance> remainingInstances = new LinkedList<>();
    SchedulableEntityInstance currentInstance = new SchedulableEntityInstance(entity.getName(),
            cluster.getName(), instanceDate, entityType);
    remainingInstances.add(currentInstance);

    while (!remainingInstances.isEmpty()) {
        currentInstance = remainingInstances.remove();
        if (currentInstance.getEntityType() == EntityType.FEED) {
            Feed feed = ConfigurationStore.get().get(EntityType.FEED, currentInstance.getEntityName());
            FeedInstanceStatus.AvailabilityStatus status = getFeedInstanceStatus(feed,
                    currentInstance.getInstanceTime(), cluster);

            // add vertex to the graph
            vertices.add(currentInstance.toString());
            instanceStatusMap.put(currentInstance.toString(), "[" + status.name() + "]");
            if (status == FeedInstanceStatus.AvailabilityStatus.AVAILABLE) {
                continue;
            }/*from  w w w.  java 2  s.  c om*/

            // find producer process instance and add it to the queue
            SchedulableEntityInstance producerInstance = FeedHelper.getProducerInstance(feed,
                    currentInstance.getInstanceTime(), cluster);
            if (producerInstance != null) {
                remainingInstances.add(producerInstance);

                //add edge from producerProcessInstance to the feedInstance
                LineageGraphResult.Edge edge = new LineageGraphResult.Edge(producerInstance.toString(),
                        currentInstance.toString(), "produces");
                edges.add(edge);
            }
        } else { // entity type is PROCESS
            Process process = ConfigurationStore.get().get(EntityType.PROCESS, currentInstance.getEntityName());
            InstancesResult.WorkflowStatus status = getProcessInstanceStatus(process,
                    currentInstance.getInstanceTime());

            // add current process instance as a vertex
            vertices.add(currentInstance.toString());
            if (status == null) {
                instanceStatusMap.put(currentInstance.toString(), "[ Not Available ]");
            } else {
                instanceStatusMap.put(currentInstance.toString(), "[" + status.name() + "]");
                if (status == InstancesResult.WorkflowStatus.SUCCEEDED) {
                    continue;
                }
            }

            // find list of input feed instances - only mandatory ones and not optional ones
            Set<SchedulableEntityInstance> inputFeedInstances = ProcessHelper.getInputFeedInstances(process,
                    currentInstance.getInstanceTime(), cluster, false);
            for (SchedulableEntityInstance inputFeedInstance : inputFeedInstances) {
                remainingInstances.add(inputFeedInstance);

                //Add edge from inputFeedInstance to consumer processInstance
                LineageGraphResult.Edge edge = new LineageGraphResult.Edge(inputFeedInstance.toString(),
                        currentInstance.toString(), "consumed by");
                edges.add(edge);
            }
        }
    }

    // append status to each vertex
    Set<String> relabeledVertices = new HashSet<>();
    for (String instance : vertices) {
        String status = instanceStatusMap.get(instance);
        relabeledVertices.add(instance + status);
    }

    // append status to each edge
    for (LineageGraphResult.Edge edge : edges) {
        String oldTo = edge.getTo();
        String oldFrom = edge.getFrom();

        String newFrom = oldFrom + instanceStatusMap.get(oldFrom);
        String newTo = oldTo + instanceStatusMap.get(oldTo);

        edge.setFrom(newFrom);
        edge.setTo(newTo);
    }

    result.setEdges(edges.toArray(new LineageGraphResult.Edge[0]));
    result.setVertices(relabeledVertices.toArray(new String[0]));
    return result;
}

From source file:com.datatorrent.stram.webapp.TypeGraph.java

private void removeSubGraph(TypeGraphVertex v) {

    // Can't recursively remove because it will get into concurrent modification
    // Use queue to delete all nodes
    Queue<TypeGraphVertex> removingQueue = new LinkedList<>();
    removingQueue.add(v);//from  ww w.  j a  va  2  s. c  om
    while (!removingQueue.isEmpty()) {
        TypeGraphVertex tgv = removingQueue.poll();
        if (typeGraph.get(tgv.typeName) == null) {
            // skip node that's been removed already.
            // It comes from common descendants
            continue;
        }
        // put all the descendants to waiting queue
        for (TypeGraphVertex child : tgv.descendants) {
            removingQueue.offer(child);
        }
        // remove from global hashmap
        typeGraph.remove(tgv.typeName);
        // remove from instantiable descendants list of all the (in)direct ancestors
        if (!tgv.allInstantiableDescendants.isEmpty() && !tgv.ancestors.isEmpty()) {
            for (TypeGraphVertex p : tgv.ancestors) {
                removeFromInstantiableDescendants(p, tgv.allInstantiableDescendants);
            }
        }
        // cut links from parent to child
        for (TypeGraphVertex parent : tgv.ancestors) {
            parent.descendants.remove(tgv);
        }
        // cut links form child to parent
        tgv.ancestors.clear();
    }
}