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:test.jamocha.languages.clips.SystemTest.java

private static Pair<Queue<Object>, Queue<Warning>> run(final Network network, final String parserInput)
        throws ParseException {
    final SFPParser parser = new SFPParser(new StringReader(parserInput));
    final SFPToCETranslator visitor = new SFPToCETranslator(network, network);
    final Queue<Object> values = new LinkedList<>();

    while (true) {
        final SFPStart n = parser.Start();
        if (n == null)
            return Pair.of(values, visitor.getWarnings());
        final Object value = n.jjtAccept(visitor, null);
        if (null != value) {
            values.add(value);
        }/*w w  w  .  jav  a 2s . c  om*/
    }
}

From source file:com.android.repository.util.InstallerUtil.java

/**
 * Compute the complete list of packages that need to be installed to meet the dependencies of
 * the given list (including the requested packages themselves, if they are not already
 * installed). Returns {@code null} if we were unable to compute a complete list of dependencies
 * due to not being able to find required packages of the specified version.
 *
 * Packages are returned in install order (that is, if we request A which depends on B, the
 * result will be [B, A]). If a dependency cycle is encountered the order of the returned
 * results at or below the cycle is undefined. For example if we have A -> [B, C], B -> D, and D
 * -> B then the returned list will be either [B, D, C, A] or [D, B, C, A].
 *
 * Note that we assume installed packages already have their dependencies met.
 *//*from   w  ww .jav  a 2  s  . co  m*/
@Nullable
public static List<RemotePackage> computeRequiredPackages(@NonNull Collection<RemotePackage> requests,
        @NonNull RepositoryPackages packages, @NonNull ProgressIndicator logger) {
    Set<RemotePackage> requiredPackages = Sets.newHashSet();
    Map<String, UpdatablePackage> consolidatedPackages = packages.getConsolidatedPkgs();

    Set<String> seen = Sets.newHashSet();
    Multimap<String, Dependency> allDependencies = HashMultimap.create();
    Set<RemotePackage> roots = Sets.newHashSet();
    Queue<RemotePackage> current = Lists.newLinkedList();
    for (RemotePackage request : requests) {
        UpdatablePackage updatable = consolidatedPackages.get(request.getPath());
        if (updatable == null) {
            logger.logWarning(String.format("No package with key %s found!", request.getPath()));
            return null;
        }
        if (!updatable.hasLocal() || updatable.isUpdate()) {
            current.add(request);
            roots.add(request);
            requiredPackages.add(request);
            seen.add(request.getPath());
        }
    }

    while (!current.isEmpty()) {
        RemotePackage currentPackage = current.remove();

        Collection<Dependency> currentDependencies = currentPackage.getAllDependencies();
        for (Dependency d : currentDependencies) {
            String dependencyPath = d.getPath();
            UpdatablePackage updatableDependency = consolidatedPackages.get(dependencyPath);
            if (updatableDependency == null) {
                logger.logWarning(String.format("Dependant package with key %s not found!", dependencyPath));
                return null;
            }
            LocalPackage localDependency = updatableDependency.getLocal();
            Revision requiredMinRevision = null;
            RevisionType r = d.getMinRevision();
            if (r != null) {
                requiredMinRevision = r.toRevision();
            }
            if (localDependency != null && (requiredMinRevision == null
                    || requiredMinRevision.compareTo(localDependency.getVersion()) <= 0)) {
                continue;
            }
            if (seen.contains(dependencyPath)) {
                allDependencies.put(dependencyPath, d);
                continue;
            }
            seen.add(dependencyPath);
            RemotePackage remoteDependency = updatableDependency.getRemote();
            if (remoteDependency == null || (requiredMinRevision != null
                    && requiredMinRevision.compareTo(remoteDependency.getVersion()) > 0)) {
                logger.logWarning(String.format("Package \"%1$s\" with revision at least %2$s not available.",
                        updatableDependency.getRepresentative().getDisplayName(), requiredMinRevision));
                return null;
            }

            requiredPackages.add(remoteDependency);
            allDependencies.put(dependencyPath, d);
            current.add(remoteDependency);
            // We had a dependency on it, so it can't be a root.
            roots.remove(remoteDependency);
        }
    }

    List<RemotePackage> result = Lists.newArrayList();

    while (!roots.isEmpty()) {
        RemotePackage root = roots.iterator().next();
        roots.remove(root);
        result.add(root);
        for (Dependency d : root.getAllDependencies()) {
            Collection<Dependency> nodeDeps = allDependencies.get(d.getPath());
            if (nodeDeps.size() == 1) {
                UpdatablePackage newRoot = consolidatedPackages.get(d.getPath());
                if (newRoot == null) {
                    logger.logWarning(String.format("Package with key %s not found!", d.getPath()));
                    return null;
                }

                roots.add(newRoot.getRemote());
            }
            nodeDeps.remove(d);
        }
    }

    if (result.size() != requiredPackages.size()) {
        logger.logInfo("Failed to sort dependencies, returning partially-sorted list.");
        for (RemotePackage p : result) {
            requiredPackages.remove(p);
        }
        result.addAll(requiredPackages);
    }

    return Lists.reverse(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);
    padresCola.add("#");
    while (true) {
        System.out.println(cola);
        if (cola.isEmpty()) {
            result.agregarPaso("No se encontro el nodo destino");
            break;
        }//  w ww  .j a v  a 2  s  .  c om
        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:eu.europeana.enrichment.common.Utils.java

private static Set<String> getClassNamesPackage(String pckgname) throws ClassNotFoundException, IOException {
    // This will hold a list of directories matching the pckgname. There may
    // be/*from w w w .j a  va 2 s  .c  o  m*/
    // more than one if a package is split over multiple jars/paths
    Queue<File> directories = new LinkedList<File>();
    try {
        ClassLoader cld = Thread.currentThread().getContextClassLoader();
        if (cld == null) {
            throw new ClassNotFoundException("Can't get class loader.");
        }
        String path = pckgname.replace('.', '/');
        // Ask for all resources for the path
        Enumeration<URL> resources = cld.getResources(path);
        while (resources.hasMoreElements()) {
            directories.add(new File(URLDecoder.decode(resources.nextElement().getPath(), "UTF-8")));
        }
    } catch (NullPointerException x) {
        throw new ClassNotFoundException(
                pckgname + " does not appear to be a valid package (Null pointer exception)");
    } catch (UnsupportedEncodingException encex) {
        throw new ClassNotFoundException(
                pckgname + " does not appear to be a valid package (Unsupported encoding)");
    } catch (IOException ioex) {
        throw new ClassNotFoundException(
                "IOException was thrown when trying to get all resources for " + pckgname);
    }

    Set<String> classes = new HashSet<String>();
    // For every directory identified capture all the .class files
    while (!directories.isEmpty()) {
        File directory = directories.poll();
        if (directory.exists()) {
            // Get the list of the files contained in the package
            File[] files = directory.listFiles();
            for (File file : files) {
                // we are only interested in .class files
                if (file.getCanonicalPath().endsWith(".class")) {
                    String fileName = file.getPath().substring(directory.getPath().length() + 1);
                    pckgname = file.getPath()
                            .substring(file.getPath().indexOf(File.separator + "nl" + File.separator) + 1);
                    pckgname = pckgname.substring(0, pckgname.lastIndexOf(File.separator))
                            .replaceAll("\\" + File.separator, ".");
                    // if (!fileName.matches("(.+)\\$\\d\\.class"))
                    // removes the .class extension
                    classes.add(fileName.substring(0, fileName.length() - 6));
                }
                // Add subdirs
                if (file.isDirectory()) {
                    directories.add(file);
                }
            }
        } else {
            throw new ClassNotFoundException(
                    pckgname + " (" + directory.getPath() + ") does not appear to be a valid package");
        }
    }
    return classes;
}

From source file:eu.annocultor.common.Utils.java

private static Set<String> getClassNamesPackage(String pckgname) throws ClassNotFoundException, IOException {
    // This will hold a list of directories matching the pckgname. There may be
    // more than one if a package is split over multiple jars/paths
    Queue<File> directories = new LinkedList<File>();
    try {// w  w  w  .j  av  a2s. c  o  m
        ClassLoader cld = Thread.currentThread().getContextClassLoader();
        if (cld == null) {
            throw new ClassNotFoundException("Can't get class loader.");
        }
        String path = pckgname.replace('.', '/');
        // Ask for all resources for the path
        Enumeration<URL> resources = cld.getResources(path);
        while (resources.hasMoreElements()) {
            directories.add(new File(URLDecoder.decode(resources.nextElement().getPath(), "UTF-8")));
        }
    } catch (NullPointerException x) {
        throw new ClassNotFoundException(
                pckgname + " does not appear to be a valid package (Null pointer exception)");
    } catch (UnsupportedEncodingException encex) {
        throw new ClassNotFoundException(
                pckgname + " does not appear to be a valid package (Unsupported encoding)");
    } catch (IOException ioex) {
        throw new ClassNotFoundException(
                "IOException was thrown when trying to get all resources for " + pckgname);
    }

    Set<String> classes = new HashSet<String>();
    // For every directory identified capture all the .class files
    while (!directories.isEmpty()) {
        File directory = directories.poll();
        if (directory.exists()) {
            // Get the list of the files contained in the package
            File[] files = directory.listFiles();
            for (File file : files) {
                // we are only interested in .class files
                if (file.getCanonicalPath().endsWith(".class")) {
                    String fileName = file.getPath().substring(directory.getPath().length() + 1);
                    pckgname = file.getPath()
                            .substring(file.getPath().indexOf(File.separator + "nl" + File.separator) + 1);
                    pckgname = pckgname.substring(0, pckgname.lastIndexOf(File.separator))
                            .replaceAll("\\" + File.separator, ".");
                    // if (!fileName.matches("(.+)\\$\\d\\.class"))
                    // removes the .class extension
                    classes.add(fileName.substring(0, fileName.length() - 6));
                }
                // Add subdirs
                if (file.isDirectory()) {
                    directories.add(file);
                }
            }
        } else {
            throw new ClassNotFoundException(
                    pckgname + " (" + directory.getPath() + ") does not appear to be a valid package");
        }
    }
    return classes;
}

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

/**
 * Breadth first traversal of AST/*from  ww w. j a  v a  2s .  c o  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)));
        }
    }
}

From source file:uniol.apt.analysis.isomorphism.IsomorphismLogic.java

private static boolean visit(BidiMap<State, State> partialIsomorphism, Queue<Pair<State, State>> unhandled,
        State state1, State state2) {
    if (state1 == null && state2 == null)
        // Nothing to do
        return true;

    if (state1 == null || state2 == null)
        // Not isomorphic
        return false;

    State oldState1 = partialIsomorphism.getKey(state2);
    if (state1.equals(oldState1))
        // This mapping was already known
        return true;
    if (oldState1 != null)
        // We have a conflicting mapping!
        return false;

    State oldState2 = partialIsomorphism.put(state1, state2);
    if (oldState2 != null) {
        // If this assert fails, then state1 was already mapped to state2 before. However, we already
        // checked for this case above.
        assert !state2.equals(oldState2);

        // We have a conflicting mapping!
        return false;
    }/*  w w w .  ja  v a2 s.  co m*/

    unhandled.add(new Pair<State, State>(state1, state2));
    return true;
}

From source file:org.intellij.erlang.psi.impl.ErlangPsiImplUtil.java

private static boolean processDeclarationRecursive(ErlangCompositeElement o, PsiScopeProcessor processor,
        ResolveState state) {//from w  ww .java  2 s  .co m
    Queue<ErlangCompositeElement> queue = new LinkedList<ErlangCompositeElement>();
    queue.add(o);
    while (!queue.isEmpty()) {
        ErlangCompositeElement top = queue.remove();
        if (!processor.execute(top, state))
            return false;
        queue.addAll(PsiTreeUtil.getChildrenOfTypeAsList(top, ErlangCompositeElement.class));
    }
    return true;
}

From source file:org.opentestsystem.airose.docquality.processors.PassiveSentencesQualityProcessor.java

private boolean checkPassive(AbstractDocument doc, Parse p) {

    Queue<Parse> queue = new LinkedList<Parse>();
    queue.add(p);

    while (queue.size() > 0) {
        p = queue.remove();/*  w ww  .j a  v a  2 s .c om*/
        String parseType = p.getType();
        if ((parseType.length() >= 2) && StringUtils.equalsIgnoreCase(parseType.substring(0, 2), "VB")) {

            String word = p.getText().substring(p.getSpan().getStart(),
                    p.getSpan().getStart() + p.getSpan().length());

            List<String> roots = wordnet.getBaseWords(word, EnumPOS.VERB);
            if ((roots.size() > 0) && (StringUtils.endsWithIgnoreCase(roots.get(0), "be"))) {
                return true;
            } else
                return false;

        } else {
            for (Parse child : p.getChildren())
                queue.add(child);
        }
    }
    return false;
}

From source file:com.stehno.sanctuary.core.scan.DefaultDirectoryScanner.java

/**
 * Scans the given directory for changes. The directory passed in will be used as the root
 * of the changeset and the stored files.
 * /*from w  ww .j a  v a2 s  .c o m*/
 * @param directory
 * @return a populated change set.
 */
@Override
public ChangeSet scanDirectory(final File directory) {
    Assert.isTrue(directory != null && directory.isDirectory(), "A non-null directory must be specified.");

    if (log.isDebugEnabled())
        log.debug("Scanning: " + directory);

    final ChangeSet changeSet = new ChangeSet(directory);

    final Queue<File> directories = new LinkedList<File>();
    directories.add(directory);

    while (!directories.isEmpty()) {
        final File scanningDir = directories.poll();

        for (final File item : scanningDir.listFiles()) {
            if (item.isDirectory()) {
                directories.add(item);
            } else {
                changeSet.addFileStatus(localStore.fileStatus(item), item);
            }
        }
    }

    // figure out the deleted files
    for (final String path : localStore.listFilePaths()) {
        final File file = new File(path);
        if (!file.exists()) {
            changeSet.addFileStatus(FileStatus.DELETED, file);
        }
    }

    return changeSet;
}