Example usage for java.util Deque pollFirst

List of usage examples for java.util Deque pollFirst

Introduction

In this page you can find the example usage for java.util Deque pollFirst.

Prototype

E pollFirst();

Source Link

Document

Retrieves and removes the first element of this deque, or returns null if this deque is empty.

Usage

From source file:Main.java

public static void main(String[] args) {
    Deque<String> deque = new LinkedList<>();
    deque.addLast("Oracle");
    deque.offerLast("Java");
    deque.offerLast("CSS");
    deque.offerLast("XML");

    System.out.println("Deque: " + deque);

    // remove elements from the Deque until it is empty
    while (deque.peekFirst() != null) {
        System.out.println("Head  Element: " + deque.peekFirst());
        deque.removeFirst();//w ww  .  ja va2s.co m
        System.out.println("Removed one  element from  Deque");
        System.out.println("Deque: " + deque);
    }

    // the Deque is empty. Try to call its peekFirst(),
    // getFirst(), pollFirst() and removeFirst() methods
    System.out.println("deque.isEmpty(): " + deque.isEmpty());

    System.out.println("deque.peekFirst(): " + deque.peekFirst());
    System.out.println("deque.pollFirst(): " + deque.pollFirst());

    String str = deque.getFirst();
    System.out.println("deque.getFirst(): " + str);
    str = deque.removeFirst();
    System.out.println("deque.removeFirst(): " + str);

}

From source file:com.frostwire.platform.DefaultFileSystem.java

public static void walkFiles(FileSystem fs, File file, FileFilter filter) {
    File[] arr = fs.listFiles(file, filter);
    if (arr == null) {
        return;/*from  w w w  .  j  av a2  s.c om*/
    }
    Deque<File> q = new LinkedList<>(Arrays.asList(arr));

    while (!q.isEmpty()) {
        File child = q.pollFirst();
        filter.file(child);
        if (fs.isDirectory(child)) {
            arr = fs.listFiles(child, filter);
            if (arr != null) {
                for (int i = arr.length - 1; i >= 0; i--) {
                    q.addFirst(arr[i]);
                }
            }
        }
    }
}

From source file:com.spotify.helios.servicescommon.coordination.DefaultZooKeeperClient.java

@Override
public List<String> listRecursive(final String path) throws KeeperException {
    assertClusterIdFlagTrue();/*from   w  w w  .  j  av  a 2  s  .c  o m*/
    final Deque<String> queue = newLinkedList();
    final List<String> tree = newArrayList();

    queue.add(path);
    tree.add(path);

    while (!queue.isEmpty()) {
        final String node = queue.pollFirst();
        final List<String> children = getChildren(node);

        for (final String child : children) {
            final String childPath = node.replaceAll("/$", "") + "/" + child;
            queue.add(childPath);
            tree.add(childPath);
        }
    }

    return tree;
}

From source file:org.ops4j.pax.url.mvn.internal.AetherBasedResolver.java

private RepositorySystemSession newSession(LocalRepository repo) {
    if (repo == null) {
        repo = getLocalRepository();/*from   w ww . java 2s  .com*/
    }
    Deque<RepositorySystemSession> deque = sessions.get(repo);
    RepositorySystemSession session = null;
    if (deque != null) {
        session = deque.pollFirst();
    }
    if (session == null) {
        session = createSession(repo);
    }
    return session;
}

From source file:org.apache.giraph.comm.flow_control.CreditBasedFlowControl.java

/**
 * Try to send as much as cached requests to a given worker
 *
 * @param taskId id of the worker to send cached requests to
 *//*from   w w w .  java 2  s  . c  om*/
private void trySendCachedRequests(int taskId) {
    Deque<WritableRequest> requestDeque = perWorkerUnsentRequestMap.get(taskId);
    AdjustableSemaphore openRequestPermit = perWorkerOpenRequestMap.get(taskId).getLeft();
    while (true) {
        WritableRequest request;
        synchronized (requestDeque) {
            request = requestDeque.pollFirst();
            if (request == null) {
                break;
            }
            // See whether the sender client has any unused credit
            if (!openRequestPermit.tryAcquire()) {
                requestDeque.offerFirst(request);
                break;
            }
        }
        unsentRequestPermit.release();
        // At this point, we have a request, and we reserved a credit for the
        // sender client. So, we send the request to the client and update
        // the state.
        nettyClient.doSend(taskId, request);
        if (aggregateUnsentRequests.decrementAndGet() == 0) {
            synchronized (aggregateUnsentRequests) {
                aggregateUnsentRequests.notifyAll();
            }
        }
    }
}

From source file:org.betaconceptframework.astroboa.engine.definition.visitor.CmsPropertyVisitor.java

private void populateDefinition(XSComponent component) {
    try {/*from   www  .ja va  2s.  com*/

        if (isDefinitionComplex()) {
            //Do not process complex property if already exists
            if (component instanceof XSComplexType) {
                if (name != null
                        && cmsDefinitionVisitor.getDefinitionCacheRegion().hasComplexTypeDefinition(name)) {
                    logger.debug("Complex Definition '{}' has already been processed.", name);

                    createDefinition = false;
                    return;
                }
            }
        }

        //Set namespaceURI
        retrieveElementNamespace(component);

        //Set URI
        retrieveSchemaURI(component);

        setBasicProperties(component);

        //process further in case of ComplexProperty or ContentType
        if (ValueType.ContentType == valueType || isDefinitionComplex()) {

            if (component instanceof XSComplexType) {
                visitSubProperties(((XSComplexType) component), false);
            } else if (component instanceof XSElementDecl) {

                final XSElementDecl element = ((XSElementDecl) component);
                if (element.getType() != null) {
                    if (ValueType.ContentType == valueType) {
                        //XML element represents a ContentType.
                        //First we have to visit the inherited elements (at least from complexType contentObjectType
                        //found in astroboa-model.xsd)

                        if (!element.getType().isComplexType()) {
                            throw new CmsException("Element " + element.getName()
                                    + " is Content Type but it does not refer to a complex type");
                        }

                        //Create a stack of all parent elements
                        Deque<XSType> elementTypes = collectAllSuperTypesIncludingProvidedElement(element);

                        if (superTypes == null) {
                            superTypes = new ArrayList<String>();
                        }

                        //Now visit properties for each element stored
                        boolean elementExtendsBaseContentObjectType = false;

                        while (!elementTypes.isEmpty()) {

                            //Retrieve the first item in queue and remove it at the same time
                            final XSComplexType complexType = elementTypes.pollFirst().asComplexType();

                            final boolean complexTypeRepresentsContentObjectType = complexType.getName() != null
                                    && CmsDefinitionItem.contentObjectType.equals(ItemUtils.createNewItem(null,
                                            complexType.getTargetNamespace(), complexType.getName()));

                            elementExtendsBaseContentObjectType = elementExtendsBaseContentObjectType
                                    || complexTypeRepresentsContentObjectType;

                            if (!complexTypeRepresentsContentObjectType && complexType.getName() != null) {

                                logger.debug("Adding superType {} for definition {}", complexType.getName(),
                                        name);

                                superTypes.add(complexType.getName());
                            }

                            visitSubProperties(complexType, complexTypeRepresentsContentObjectType);
                        }

                        if (!elementExtendsBaseContentObjectType) {
                            //Element is a global one and does not extend base contentObjectType.
                            //In this case we should dynamically load contentObjectType properties

                            XSComplexType contentObjectType = cmsDefinitionVisitor
                                    .getComplexType("contentObjectType");

                            if (contentObjectType == null) {
                                throw new CmsException("Could not locate complex type contentObjectType.");
                            }

                            visitSubProperties(contentObjectType, true);

                        }
                    } else {

                        if (element.getType().isLocal()) {
                            logger.debug(
                                    "Definition '{}' represents a complex element which is defined inside an element.",
                                    name);

                            visitSubProperties(element.getType().asComplexType(), false);
                        } else {
                            logger.debug(
                                    "Definition '{}' represents a complex element which refers to another complex type",
                                    name);

                            setComplexReference(element);
                        }
                    }
                } else
                    throw new CmsException("Element " + element.getName() + " is " + valueType
                            + "but it does not refer to a type");
            }
        }

    } catch (Throwable e) {
        logger.error("", e);
        createDefinition = false;
    }
}

From source file:org.gdms.source.DefaultSourceManager.java

private void removeFromSchema(String name) {
    if (name.isEmpty()) {
        throw new IllegalArgumentException("Empty table name!");
    }//from w  ww  . ja v  a  2s .com

    // split on the dots '.' into
    // schema1.schema2.schema3.table1

    String[] l = DOT.split(name);

    if (l.length <= 1) {
        // just a table, we remove it from the root schema
        schema.removeTable(name);
    } else {
        Deque<Schema> path = new ArrayDeque<Schema>();
        path.add(schema);
        // we get down
        // to the last schema before the table
        for (int i = 0; i < l.length - 1; i++) {
            final Schema n = path.getFirst().getSubSchemaByName(l[i]);
            path.addFirst(n);
        }

        boolean stop = false;
        while (!path.isEmpty() && !stop) {
            // take the last schema in the path (top of the pile)
            final Schema n = path.pollFirst();
            n.removeTable(l[l.length - 1]);
            if (n.getTableCount() != 0 || n.getSubSchemaNames().length != 0) {
                // the schema is still needed, we must not remove it
                stop = true;
            } else {
                Schema p = n.getParentSchema();
                if (p != null) {
                    p.removeSubSchema(n.getName());
                } else {
                    // we have reached root, it stays were it is...
                    stop = true;
                }
            }
        }
    }
}

From source file:org.nickelproject.util.testUtil.ClasspathUtil.java

private static Iterable<String> getAllSubClasses(final Class<?>... pTags) {
    final Deque<String> vClassNames = Lists.newLinkedList();
    final Set<String> vResults = Sets.newHashSet();
    for (final Class<?> vClass : pTags) {
        vClassNames.add(vClass.getCanonicalName());
    }//from www .  ja  v a  2  s  .  co m
    while (!vClassNames.isEmpty()) {
        final String vCurrentClass = vClassNames.pollFirst();
        for (final String vChild : kChildren.get(vCurrentClass)) {
            vClassNames.addLast(vChild);
            vResults.add(vChild);
        }
    }
    return vResults;
}

From source file:org.xframium.page.data.provider.AbstractPageDataProvider.java

@Override
public PageData getRecord(String recordType) {
    try {/*  w  ww. ja va 2  s .  c  o m*/
        Deque<PageData> dataList = recordMap.get(getRecordType(recordType)).getRecordList();

        if (dataList instanceof LinkedBlockingDeque)
            return ((LinkedBlockingDeque<PageData>) dataList).pollFirst(waitTimeOut, TimeUnit.SECONDS);
        else {
            PageData pageData = dataList.pollFirst();
            dataList.offer(pageData);
            return pageData;
        }
    } catch (Exception e) {
        log.error("Error acquiring page data [" + getRecordType(recordType) + "] - " + e.getMessage());
        return null;
    }
}

From source file:uniol.apt.adt.automaton.FiniteAutomatonUtility.java

static private <S extends State> Iterable<S> statesIterable(final S initialState) {
    return new Iterable<S>() {
        @Override//from w  ww  . ja v a  2s  . co m
        public Iterator<S> iterator() {
            final Deque<State> unhandled = new LinkedList<>();
            final Set<State> seen = new HashSet<>();
            unhandled.add(initialState);
            seen.add(initialState);
            return new Iterator<S>() {
                @Override
                public boolean hasNext() {
                    return !unhandled.isEmpty();
                }

                @Override
                public S next() {
                    State state = unhandled.pollFirst();
                    if (state == null)
                        throw new NoSuchElementException();
                    for (State next : state.getFollowingStates(Symbol.EPSILON))
                        if (seen.add(next))
                            unhandled.add(next);
                    for (Symbol symbol : state.getDefinedSymbols())
                        for (State next : state.getFollowingStates(symbol))
                            if (seen.add(next))
                                unhandled.add(next);
                    @SuppressWarnings("unchecked")
                    S ret = (S) state;
                    return ret;
                }

                @Override
                public void remove() {
                    throw new UnsupportedOperationException();
                }
            };
        }
    };
}