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:org.siddhiesb.transport.passthru.DeliveryAgent.java

/**
 * Notification for a connection availability. When this occurs a message in the
 * queue for delivery will be tried./*from   w  ww . j a  v a2  s . c  om*/
 *
 */
public void connected(HttpRoute route) {
    Queue<CommonContext> queue = null;
    lock.lock();
    try {
        queue = waitingMessages.get(route);
    } finally {
        lock.unlock();
    }

    while (queue.size() > 0) {
        NHttpClientConnection conn = targetConnections.getConnection(route);
        if (conn != null) {
            CommonContext messageContext = queue.poll();
            if (messageContext != null) {
                tryNextMessage(messageContext, route, conn);
            }
        } else {
            break;
        }
    }
}

From source file:org.hyperic.hq.product.JDBCMeasurementPlugin.java

protected void removeCachedConnection(String url, String user, String pass) {
    String cacheKey = calculateKey(url, user, pass);
    Queue<Connection> pool = connectionPools.get(cacheKey);
    if (pool != null) {
        Connection conn;//from  w ww  .  j av a 2 s  . c  o m
        while ((conn = pool.poll()) != null) {
            DBUtil.closeJDBCObjects(log, conn, null, null);
            log.debug("[remCC] Connection for '" + cacheKey + "' closed (pool.size=" + pool.size() + ")");
        }
        connectionPools.remove(cacheKey);
    } else {
        log.debug("[remCC] Pool for '" + cacheKey + "' not found");
    }
}

From source file:org.protempa.dest.table.Derivation.java

@Override
public String[] getInferredPropositionIds(KnowledgeSource knowledgeSource, String[] inPropIds)
        throws KnowledgeSourceReadException {
    String[] explicitPropIds = getPropositionIds();
    if (explicitPropIds.length > 0) {
        return explicitPropIds;
    } else {/*from   w  ww  .  j  av a 2s  .  c  o  m*/
        Set<String> result = new HashSet<>();
        for (String propId : inPropIds) {
            PropositionDefinition propDef = knowledgeSource.readPropositionDefinition(propId);
            if (propDef == null) {
                throw new IllegalArgumentException("Invalid propId: " + propId);
            }
            switch (this.behavior) {
            case SINGLE_BACKWARD:
                Arrays.addAll(result, propDef.getChildren());
                break;
            case MULT_BACKWARD:
                Queue<String> backwardProps = new LinkedList<>();
                Arrays.addAll(backwardProps, propDef.getChildren());
                String pId;
                while ((pId = backwardProps.poll()) != null) {
                    PropositionDefinition pDef = knowledgeSource.readPropositionDefinition(pId);
                    Arrays.addAll(backwardProps, pDef.getChildren());
                }
                result.addAll(backwardProps);
                break;
            case SINGLE_FORWARD:
                for (PropositionDefinition def : knowledgeSource.readParents(propDef)) {
                    result.add(def.getId());
                }
                break;
            case MULT_FORWARD:
                Queue<String> forwardProps = new LinkedList<>();
                for (PropositionDefinition def : knowledgeSource.readParents(propDef)) {
                    forwardProps.add(def.getId());
                }
                // pId is declared in MULT_BACKWARD case.
                while ((pId = forwardProps.poll()) != null) {
                    PropositionDefinition pDef = knowledgeSource.readPropositionDefinition(pId);
                    for (PropositionDefinition def : knowledgeSource.readParents(pDef)) {
                        forwardProps.add(def.getId());
                    }
                }
                result.addAll(forwardProps);
                break;
            default:
                throw new AssertionError("Invalid derivation behavior specified");
            }
        }
        return result.toArray(new String[result.size()]);
    }
}

From source file:org.apache.predictionio.examples.java.recommendations.tutorial1.Algorithm.java

private void setTopItemSimilarity(Map<Integer, Queue<IndexAndScore>> topItemSimilarity, Integer itemID1,
        Integer index2, double score, int capacity, Comparator<IndexAndScore> comparator) {
    Queue<IndexAndScore> queue = topItemSimilarity.get(itemID1);
    if (queue == null) {
        queue = new PriorityQueue<IndexAndScore>(capacity, comparator);
        topItemSimilarity.put(itemID1, queue);
    }//from   ww w  . j  av  a  2  s.c o  m
    IndexAndScore entry = new IndexAndScore(index2, score);
    if (queue.size() < capacity)
        queue.add(entry);
    else if (comparator.compare(queue.peek(), entry) < 0) {
        queue.poll();
        queue.add(entry);
    }
}

From source file:net.cellcloud.talk.HttpDialogueHandler.java

@Override
protected void doPost(HttpRequest request, HttpResponse response) throws IOException {
    HttpSession session = request.getSession();
    if (null != session) {
        try {/* w w  w . j a  v  a  2  s. c o m*/
            // ??
            JSONObject json = new JSONObject(new String(request.readRequestData(), Charset.forName("UTF-8")));
            // ? JSON ?
            String speakerTag = json.getString(Tag);
            String celletIdentifier = json.getString(Identifier);
            JSONObject primitiveJSON = json.getJSONObject(Primitive);
            // ?
            Primitive primitive = new Primitive(speakerTag);
            PrimitiveSerializer.read(primitive, primitiveJSON);
            // ?
            this.talkService.processDialogue(session, speakerTag, celletIdentifier, primitive);

            // ?
            // FIXME 2014/10/03 ??
            JSONObject responseData = new JSONObject();

            // ??
            Queue<Message> queue = session.getQueue();
            if (!queue.isEmpty()) {
                ArrayList<String> identifiers = new ArrayList<String>(queue.size());
                ArrayList<Primitive> primitives = new ArrayList<Primitive>(queue.size());
                for (int i = 0, size = queue.size(); i < size; ++i) {
                    // ?
                    Message message = queue.poll();
                    // 
                    Packet packet = Packet.unpack(message.get());
                    if (null != packet) {
                        // ? cellet identifier
                        byte[] identifier = packet.getSubsegment(1);

                        // ?????
                        byte[] primData = packet.getSubsegment(0);
                        ByteArrayInputStream stream = new ByteArrayInputStream(primData);

                        // ???
                        Primitive prim = new Primitive(Nucleus.getInstance().getTagAsString());
                        prim.read(stream);

                        // 
                        identifiers.add(Utils.bytes2String(identifier));
                        primitives.add(prim);
                    }
                }

                // ?
                JSONArray jsonPrimitives = this.convert(identifiers, primitives);
                responseData.put(Primitives, jsonPrimitives);
            }

            // ?
            responseData.put(Queue, queue.size());

            // ?
            this.respondWithOk(response, responseData);
        } catch (JSONException e) {
            Logger.log(HttpDialogueHandler.class, e, LogLevel.ERROR);
            this.respond(response, HttpResponse.SC_BAD_REQUEST);
        }
    } else {
        this.respond(response, HttpResponse.SC_UNAUTHORIZED);
    }
}

From source file:edu.pitt.dbmi.deep.phe.i2b2.I2b2OntologyBuilder.java

private TreeSet<PartialPath> extractOntologyPartialPaths() throws OWLOntologyCreationException, IOException {

    final TreeSet<PartialPath> partialPaths = new TreeSet<PartialPath>();

    OWLOntologyManager m = OWLManager.createOWLOntologyManager();
    // OWLOntology o = m.loadOntologyFromOntologyDocument(pizza_iri);
    OWLOntology o = loadDeepPheOntology(m);
    OWLReasonerFactory reasonerFactory;// w w  w  . ja va2  s .c  om
    reasonerFactory = new StructuralReasonerFactory();
    OWLReasoner reasoner = reasonerFactory.createReasoner(o);
    OWLDataFactory fac = m.getOWLDataFactory();
    OWLClass elementConcept = fac.getOWLClass(IRI.create(CONST_TOP_LEVEL_ENTRY));

    final Queue<PartialPath> partialPathQueue = new LinkedList<PartialPath>();
    NodeSet<OWLClass> subClses = reasoner.getSubClasses(elementConcept, true);
    for (Node<OWLClass> subCls : subClses) {
        PartialPath path = new PartialPath();
        path.setReasoner(reasoner);
        path.setCls(subCls.getRepresentativeElement());
        path.setLevel(1);
        partialPathQueue.add(path);
    }

    while (true) {
        PartialPath path;
        path = partialPathQueue.poll();
        if (path == null) {
            break;
        } else {
            partialPathQueue.addAll(path.expand());
        }
        partialPaths.add(path);
    }

    PartialPath topLevel = new PartialPath();
    topLevel.setPath("\\DEEPPHE");
    topLevel.setLevel(0);
    topLevel.setLeaf(false);
    partialPaths.add(topLevel);

    return partialPaths;
}

From source file:org.structr.core.entity.SchemaMethod.java

private void determineSignature(final Map<String, SchemaNode> schemaNodes,
        final AbstractSchemaNode schemaEntity, final ActionEntry entry, final String methodName)
        throws FrameworkException {

    final App app = StructrApp.getInstance();
    final Set<String> visitedTypes = new LinkedHashSet<>();
    final Queue<String> typeQueue = new LinkedList<>();
    final String structrPackage = "org.structr.dynamic.";

    // initial type
    addType(typeQueue, schemaEntity);/*from  ww w. j a va  2 s  . c  o m*/

    while (!typeQueue.isEmpty()) {

        final String typeName = typeQueue.poll();
        String shortTypeName = typeName;

        if (typeName != null && !visitedTypes.contains(typeName)) {

            visitedTypes.add(typeName);

            if (typeName.startsWith(structrPackage)) {
                shortTypeName = typeName.substring(structrPackage.length());
            }

            // try to find schema node for the given type
            final SchemaNode typeNode = schemaNodes.get(shortTypeName);
            if (typeNode != null && !typeNode.equals(schemaEntity)) {

                // try to identify overridden schema method from database
                final SchemaMethod superMethod = app.nodeQuery(SchemaMethod.class)
                        .and(SchemaMethod.schemaNode, typeNode).and(SchemaMethod.name, methodName).getFirst();

                if (superMethod != null) {

                    final ActionEntry superEntry = superMethod.getActionEntry(schemaNodes, typeNode);

                    entry.copy(superEntry);

                    // done
                    return;
                }

                // next type in queue
                addType(typeQueue, typeNode);

            } else {

                // no schema node for the given type found, try internal types
                final Class internalType = SchemaHelper.classForName(typeName);
                if (internalType != null) {

                    if (getSignature(internalType, methodName, entry)) {

                        return;
                    }

                    final Class superclass = internalType.getSuperclass();
                    if (superclass != null) {

                        // examine superclass as well
                        typeQueue.add(superclass.getName());

                        // collect interfaces
                        for (final Class iface : internalType.getInterfaces()) {
                            typeQueue.add(iface.getName());
                        }
                    }
                }
            }
        }
    }
}

From source file:org.xwiki.tool.xar.XARMojo.java

/**
 * Adds files from a specific directory to an archive. It uses an existing package.xml to filter the files to be
 * added./*w w  w .  j  a v  a2  s.  c  o m*/
 * 
 * @param archiver the archive in which the files will be added
 * @param sourceDir the directory whose contents will be added to the archive
 * @param packageXml the corresponding package.xml file
 * @throws Exception if the files cannot be added to the archive
 */
private void addFilesToArchive(ZipArchiver archiver, File sourceDir, File packageXml) throws Exception {
    Collection<String> documentNames;
    getLog().info(String.format("Using the existing package.xml descriptor at [%s]", packageXml.getPath()));
    try {
        documentNames = getDocumentNamesFromXML(packageXml);
    } catch (Exception e) {
        getLog().error(String.format("The existing [%s] is invalid.", PACKAGE_XML));
        throw e;
    }

    // Next, we scan the hole directory and subdirectories for documents.

    Queue<File> fileQueue = new LinkedList<File>();
    addContentsToQueue(fileQueue, sourceDir);
    while (!fileQueue.isEmpty() && !documentNames.isEmpty()) {
        File currentFile = fileQueue.poll();
        if (currentFile.isDirectory()) {
            addContentsToQueue(fileQueue, currentFile);
        } else {
            String documentReference = XWikiDocument.getReference(currentFile);
            if (documentNames.contains(documentReference)) {
                // building the path the current file will have within the archive
                //
                // Note: DO NOT USE String.split since it requires a regexp. Under Windows XP, the FileSeparator is
                // '\' when not escaped is a special character of the regexp
                //     String archivedFilePath =
                //         currentFile.getAbsolutePath().split(sourceDir.getAbsolutePath() + File.separator)[1];
                String archivedFilePath = currentFile.getAbsolutePath()
                        .substring((sourceDir.getAbsolutePath() + File.separator).length());
                archivedFilePath = archivedFilePath.replace(File.separatorChar, '/');

                archiver.addFile(currentFile, archivedFilePath);
                documentNames.remove(documentReference);
            }
        }
    }

    if (!documentNames.isEmpty()) {
        StringBuilder errorMessage = new StringBuilder("The following documents could not be found: ");
        for (String name : documentNames) {
            errorMessage.append(name);
            errorMessage.append(" ");
        }
        throw new Exception(errorMessage.toString());
    }

    archiver.addFile(packageXml, PACKAGE_XML);
}

From source file:org.sakaiproject.nakamura.files.pool.ExportIMSCP.java

private File getZipFile(Manifest manifest, Content content, String poolId, ContentManager contentManager)
        throws JSONException, IOException, StorageClientException, AccessDeniedException {
    String resourcesDir = "resources/";
    String filename = (String) content.getProperty(FilesConstants.POOLED_CONTENT_FILENAME);
    filename = filename.replaceAll("/", "_");
    File f = File.createTempFile(filename, ".zip");
    f.deleteOnExit();//from   ww w .  j a va2  s . c o  m
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(f));
    List<org.sakaiproject.nakamura.cp.Resource> resources = manifest.getResources().getResources();
    if (resources == null) {
        return null;
    }
    for (org.sakaiproject.nakamura.cp.Resource resource : resources) {
        Item item = new Item();
        Queue<Item> items = new LinkedList<Item>();
        items.addAll(manifest.getOrganizations().getOrganizations().get(0).getItems());
        while (!items.isEmpty()) {
            Item i = items.poll();
            if (i.getIdentifierRef() != null && i.getIdentifierRef().equals(resource.getIdentifier())) {
                item = i;
                break;
            }
            if (i.hasSubItems()) {
                items.addAll(i.getItems());
            }
        }
        String title = resource.getIdentifier() + ".html";
        String originTitle = title;
        if (item.getTitle() != null && item.getTitle().length() != 0) {
            originTitle = item.getTitle() + ".html";
        }

        String page = collectPageContent(content, resource.getIdentifier(), contentManager);
        page = handlePage(page, contentManager, poolId, zos);
        page = "<html><head><title>" + originTitle + "</title></head><body>" + page + "</body></html>";
        InputStream input = new ByteArrayInputStream(page.getBytes());
        ZipEntry zae = new ZipEntry(resourcesDir + title);
        zos.putNextEntry(zae);
        IOUtils.copy(input, zos);
    }
    String xml = manifest.generateXML();
    InputStream input = new ByteArrayInputStream(xml.getBytes());
    ZipEntry zae = new ZipEntry("imsmanifest.xml");
    zos.putNextEntry(zae);
    IOUtils.copy(input, zos);
    zos.close();
    return f;
}