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:com.liferay.server.manager.internal.executor.PluginExecutor.java

@Override
public void executeCreate(HttpServletRequest request, JSONObject responseJSONObject, Queue<String> arguments)
        throws Exception {

    AutoDeploymentContext autoDeploymentContext = new AutoDeploymentContext();

    String context = arguments.poll();

    autoDeploymentContext.setContext(context);

    File tempFile = getTempFile(request, responseJSONObject);

    if (tempFile == null) {
        return;/*from  w ww.ja  v a  2  s  .  c o m*/
    }

    autoDeploymentContext.setFile(tempFile);

    DeployManagerUtil.deploy(autoDeploymentContext);

    boolean success = FileUtils.deleteQuietly(tempFile.getParentFile());

    if (success) {
        return;
    }

    String message = "Unable to remove temp directory " + tempFile.getParentFile();

    _log.error(message);

    responseJSONObject.put(JSONKeys.ERROR, message);

    success = FileUtils.deleteQuietly(tempFile);

    if (success) {
        return;
    }

    message = "Unable to remove temp file " + tempFile;

    _log.error(message);

    responseJSONObject.put(JSONKeys.ERROR, message);
}

From source file:org.rhq.core.pc.configuration.ConfigurationManager.java

private void mergedStructuredIntoRaws(Configuration configuration, ResourceConfigurationFacet facet) {
    Set<RawConfiguration> rawConfigs = facet.loadRawConfigurations();

    if (rawConfigs == null) {
        return;/* ww w . ja  v a  2 s  .c  om*/
    }

    prepareConfigForMergeIntoRaws(configuration, rawConfigs);

    Queue<RawConfiguration> queue = new LinkedList<RawConfiguration>(rawConfigs);

    while (!queue.isEmpty()) {
        RawConfiguration originalRaw = queue.poll();
        RawConfiguration mergedRaw = facet.mergeRawConfiguration(configuration, originalRaw);
        if (mergedRaw != null) {
            //TODO bypass validation of structured config for template values
            String contents = mergedRaw.getContents();
            String sha256 = new MessageDigestGenerator(MessageDigestGenerator.SHA_256)
                    .calcDigestString(contents);
            mergedRaw.setContents(contents, sha256);
            updateRawConfig(configuration, originalRaw, mergedRaw);
        }
    }
}

From source file:org.apache.camel.component.aws.sqs.SqsConsumer.java

public int processBatch(Queue<Object> exchanges) throws Exception {
    int total = exchanges.size();

    for (int index = 0; index < total && isBatchAllowed(); index++) {
        // only loop if we are started (allowed to run)
        Exchange exchange = ObjectHelper.cast(Exchange.class, exchanges.poll());
        // add current index and total as properties
        exchange.setProperty(Exchange.BATCH_INDEX, index);
        exchange.setProperty(Exchange.BATCH_SIZE, total);
        exchange.setProperty(Exchange.BATCH_COMPLETE, index == total - 1);

        // update pending number of exchanges
        pendingExchanges = total - index - 1;

        // add on completion to handle after work when the exchange is done
        exchange.addOnCompletion(new Synchronization() {
            public void onComplete(Exchange exchange) {
                processCommit(exchange);
            }//from w w w  .java 2  s .com

            public void onFailure(Exchange exchange) {
                processRollback(exchange);
            }

            @Override
            public String toString() {
                return "SqsConsumerOnCompletion";
            }
        });

        if (LOG.isTraceEnabled()) {
            LOG.trace("Processing exchange [" + exchange + "]...");
        }

        getProcessor().process(exchange);
    }

    return total;
}

From source file:org.aksw.simba.cetus.tools.ClassModelCreator.java

public static boolean inferSubClassRelations(Model classModel) {
    Set<Resource> subClasses = new HashSet<Resource>();
    ResIterator resIterator = classModel.listSubjectsWithProperty(RDFS.subClassOf);
    while (resIterator.hasNext()) {
        subClasses.add(resIterator.next());
    }//w  w  w  . j  a v  a  2s.co m
    LOGGER.info("Found " + subClasses.size() + " sub classes.");

    Queue<Resource> queue = new LinkedList<Resource>();
    int count = 0, count2 = 0;
    Resource resource, next;
    NodeIterator nodeIterator;
    Set<Resource> equalClasses = new HashSet<Resource>();
    Set<Resource> alreadySeen = new HashSet<Resource>();
    for (Resource subClass : subClasses) {
        equalClasses.clear();
        equalClasses.add(subClass);
        nodeIterator = classModel.listObjectsOfProperty(subClass, OWL.equivalentClass);
        while (nodeIterator.hasNext()) {
            equalClasses.add(nodeIterator.next().asResource());
        }
        resIterator = classModel.listSubjectsWithProperty(OWL.equivalentClass, subClass);
        while (resIterator.hasNext()) {
            equalClasses.add(resIterator.next());
        }
        for (Resource equalClass : equalClasses) {
            nodeIterator = classModel.listObjectsOfProperty(equalClass, RDFS.subClassOf);
            while (nodeIterator.hasNext()) {
                queue.add(nodeIterator.next().asResource());
            }
        }
        alreadySeen.clear();
        while (!queue.isEmpty()) {
            resource = queue.poll();
            // mark this resource as super class of the sub class
            classModel.add(subClass, RDFS.subClassOf, resource);
            ++count2;
            if (!classModel.contains(resource, RDF.type, RDFS.Class)) {
                classModel.add(resource, RDF.type, RDFS.Class);
            }

            nodeIterator = classModel.listObjectsOfProperty(resource, RDFS.subClassOf);
            while (nodeIterator.hasNext()) {
                next = nodeIterator.next().asResource();
                if (!alreadySeen.contains(next)) {
                    queue.add(next);
                    alreadySeen.add(next);
                }
            }
        }
        ++count;
        if ((count % 100000) == 0) {
            LOGGER.info("processed " + count + " sub classes.");
        }
    }
    LOGGER.info("Added " + count2 + " properties.");
    return true;
}

From source file:de.thomaskrille.dropwizard.environment_configuration.EnvironmentConfigurationFactory.java

private void replaceEnvironmentVariables(final JsonNode root) {
    Queue<JsonNode> q = Queues.newArrayDeque();

    q.add(root);//w  w  w . j av a2  s  .  c o  m
    while (!q.isEmpty()) {
        JsonNode currentNode = q.poll();

        if (!currentNode.isContainerNode()) {
            continue;
        }

        if (currentNode.isObject()) {
            replaceEnvironmentVariablesForObject(q, (ObjectNode) currentNode);
        } else if (currentNode.isArray()) {
            replaceEnvironmentVariablesForArray(q, (ArrayNode) currentNode);
        }
    }
}

From source file:au.org.ala.delta.intkey.ui.UIUtils.java

/**
 * Adds the supplied filename to the top of the most recently used files.
 * /*w  w  w.  jav a2  s. co m*/
 * @param filename
 */
public static void addFileToMRU(String filename, String title, List<Pair<String, String>> existingFiles) {
    // Strip any RTF formatting, and characters used as separators in the MRU text from the title.
    title = RTFUtils.stripFormatting(title);
    title = title.replace(MRU_ITEM_SEPARATOR, " ");
    title = title.replace(MRU_FILES_SEPARATOR, " ");

    Queue<String> q = new LinkedList<String>();

    String newFilePathAndTitle;
    if (StringUtils.isEmpty(title)) {
        newFilePathAndTitle = filename + MRU_ITEM_SEPARATOR + filename;
    } else {
        newFilePathAndTitle = filename + MRU_ITEM_SEPARATOR + title;
    }
    q.add(newFilePathAndTitle);

    if (existingFiles != null) {
        for (Pair<String, String> existingFile : existingFiles) {
            String existingFilePathAndTitle = existingFile.getFirst() + MRU_ITEM_SEPARATOR
                    + existingFile.getSecond();
            if (!q.contains(existingFilePathAndTitle)) {
                q.add(existingFilePathAndTitle);
            }
        }
    }

    StringBuilder b = new StringBuilder();
    for (int i = 0; i < MAX_SIZE_MRU && q.size() > 0; ++i) {
        if (i > 0) {
            b.append(MRU_FILES_SEPARATOR);
        }
        b.append(q.poll());
    }

    Preferences prefs = Preferences.userNodeForPackage(Intkey.class);
    prefs.put(MRU_FILES_PREF_KEY, b.toString());
    try {
        prefs.sync();
    } catch (BackingStoreException e) {
        throw new RuntimeException(e);
    }
}

From source file:au.org.ala.delta.intkey.directives.TaxonListArgument.java

@Override
public List<Item> parseInput(Queue<String> inputTokens, IntkeyContext context, String directiveName,
        StringBuilder stringRepresentationBuilder) throws IntkeyDirectiveParseException {
    List<String> selectedKeywordsOrTaxonNumbers = new ArrayList<String>();

    boolean overrideExcludedTaxa = false;

    String token = inputTokens.poll();
    if (token != null && token.equalsIgnoreCase(OVERRIDE_EXCLUDED_TAXA)) {
        overrideExcludedTaxa = true;// w  w w.j a  v  a  2 s .co  m
        token = inputTokens.poll();
    }

    List<Item> taxa = null;

    SelectionMode selectionMode = context.displayKeywords() ? SelectionMode.KEYWORD : SelectionMode.LIST;

    if (token != null) {
        if (token.equalsIgnoreCase(DEFAULT_DIALOG_WILDCARD)) {
            // do nothing - default selection mode is already set above.
        } else if (token.equalsIgnoreCase(KEYWORD_DIALOG_WILDCARD)) {
            selectionMode = SelectionMode.KEYWORD;
        } else if (token.equalsIgnoreCase(LIST_DIALOG_WILDCARD)) {
            selectionMode = SelectionMode.LIST;
        } else if (token.equalsIgnoreCase(LIST_DIALOG_AUTO_SELECT_SOLE_ITEM_WILDCARD)) {
            selectionMode = SelectionMode.LIST_AUTOSELECT_SINGLE_VALUE;
        } else {
            taxa = new ArrayList<Item>();

            while (token != null) {
                try {
                    taxa.addAll(ParsingUtils.parseTaxonToken(token, context));
                    selectedKeywordsOrTaxonNumbers.add(token);
                    token = inputTokens.poll();

                } catch (IllegalArgumentException ex) {
                    throw new IntkeyDirectiveParseException("UnrecognizedTaxonKeyword.error", token);
                }
            }

            if (!(overrideExcludedTaxa || _selectFromAll)) {
                taxa.retainAll(context.getIncludedTaxa());
            }
        }
    }

    if (taxa == null) {
        List<String> selectedKeywords = new ArrayList<String>();
        DirectivePopulator populator = context.getDirectivePopulator();
        if (selectionMode == SelectionMode.KEYWORD) {
            taxa = populator.promptForTaxaByKeyword(directiveName, !(overrideExcludedTaxa || _selectFromAll),
                    _noneSelectionPermitted, false, null, selectedKeywords);
        } else {
            boolean autoSelectSingleValue = (selectionMode == SelectionMode.LIST_AUTOSELECT_SINGLE_VALUE);
            taxa = populator.promptForTaxaByList(directiveName, !(overrideExcludedTaxa || _selectFromAll),
                    autoSelectSingleValue, false, false, null, selectedKeywords);
        }

        if (taxa == null) {
            // cancelled
            return null;
        }

        // Put selected keywords or taxon numbers into a collection to use
        // to build the string representation.
        if (!selectedKeywords.isEmpty()) {
            for (String selectedKeyword : selectedKeywords) {
                if (selectedKeyword.contains(" ")) {
                    // Enclose any keywords that contain spaces in quotes
                    // for the string representation
                    selectedKeywordsOrTaxonNumbers.add("\"" + selectedKeyword + "\"");
                } else {
                    selectedKeywordsOrTaxonNumbers.add(selectedKeyword);
                }
            }
        } else {
            List<Integer> selectedTaxonNumbers = new ArrayList<Integer>();
            for (int i = 0; i < taxa.size(); i++) {
                Item taxon = taxa.get(i);
                selectedTaxonNumbers.add(taxon.getItemNumber());
            }
            selectedKeywordsOrTaxonNumbers.add(Utils.formatIntegersAsListOfRanges(selectedTaxonNumbers));
        }
    }

    // build the string representation of the directive call
    stringRepresentationBuilder.append(" ");

    if (overrideExcludedTaxa) {
        stringRepresentationBuilder.append(OVERRIDE_EXCLUDED_TAXA);
        stringRepresentationBuilder.append(" ");
    }

    stringRepresentationBuilder.append(StringUtils.join(selectedKeywordsOrTaxonNumbers, " "));

    if (taxa.size() == 0 && !_noneSelectionPermitted) {
        throw new IntkeyDirectiveParseException("NoTaxaInSet.error");
    }

    Collections.sort(taxa);

    return taxa;
}

From source file:com.tasktop.c2c.server.internal.tasks.domain.conversion.TaskConverter.java

@SuppressWarnings("unchecked")
@Override//from  w w w  .j a va 2 s .  c  o m
public void copy(Task target, Object internalObject, DomainConverter converter,
        DomainConversionContext context) {
    com.tasktop.c2c.server.internal.tasks.domain.Task source = (com.tasktop.c2c.server.internal.tasks.domain.Task) internalObject;

    DomainConversionContext subcontext = context.subcontext();

    target.setId(source.getId());
    target.setFoundInRelease(
            source.getVersion() == null ? null : source.getVersion().isEmpty() ? null : source.getVersion());
    target.setCreationDate(source.getCreationTs());
    target.setModificationDate(source.getDeltaTs());
    target.setVersion(source.getDeltaTs() == null ? null : Long.toString(source.getDeltaTs().getTime()));
    target.setShortDescription(source.getShortDesc());
    target.setEstimatedTime(source.getEstimatedTime());
    target.setRemainingTime(source.getRemainingTime());
    target.setDeadline(source.getDeadline());
    target.setUrl(configuration.getWebUrlForTask(target.getId()));

    // Mandatory custom fields
    target.setTaskType(source.getTaskType());

    List<ExternalTaskRelation> externalTaskRelations = new ArrayList<ExternalTaskRelation>();
    if (source.getExternalTaskRelations() != null) {
        String[] strings = StringUtils.split(source.getExternalTaskRelations(), "\n");
        Pattern p = Pattern.compile("(.*)\\.(.*): (.*)");
        for (String string : strings) {
            Matcher matcher = p.matcher(string);
            if (matcher.matches()) {
                String type = matcher.group(1);
                String kind = matcher.group(2);
                String uri = matcher.group(3);
                externalTaskRelations.add(new ExternalTaskRelation(type, kind, uri));
            }
        }
    }
    target.setExternalTaskRelations(externalTaskRelations);

    List<String> commits = new ArrayList<String>();
    if (source.getCommits() != null) {
        for (String commit : StringUtils.split(source.getCommits(), ",")) {
            commits.add(commit);
        }
    }
    target.setCommits(commits);

    // These must be set from query join results
    target.setSeverity(context.getTaskSeverity(source.getSeverity()));
    target.setStatus(context.getTaskStatus(source.getStatus()));
    target.setResolution(context.getTaskResolution(source.getResolution()));
    target.setPriority(context.getPriority(source.getPriority()));
    target.setMilestone(context.getMilestone(source.getProduct(), source.getTargetMilestone()));

    target.setProduct((Product) converter.convert(source.getProduct(), subcontext));
    target.setComponent((Component) converter.convert(source.getComponent(), subcontext));
    target.setReporter((TaskUserProfile) converter.convert(source.getReporter(), subcontext));
    target.setAssignee((TaskUserProfile) converter.convert(source.getAssignee(), subcontext));
    target.setWatchers((List<TaskUserProfile>) converter.convert(source.getCcs(), subcontext));

    List<Keyworddef> keyworddefs = new ArrayList<Keyworddef>();
    for (com.tasktop.c2c.server.internal.tasks.domain.Keyword keyword : source.getKeywordses()) {
        keyworddefs.add(keyword.getKeyworddefs());
    }

    target.setKeywords((List<Keyword>) converter.convert(keyworddefs, subcontext));

    // Description (first comment), Comments, and Worklog items (comment with workTime)
    copyCommentsAndWorkLogs(target, source.getComments(), converter, context);

    BigDecimal sumOfSubtasksEstimate = BigDecimal.ZERO;
    BigDecimal sumOfSubtasksTimeSpent = BigDecimal.ZERO;
    Queue<Dependency> subTaskQueue = new LinkedList<Dependency>(source.getDependenciesesForBlocked());
    while (!subTaskQueue.isEmpty()) {
        com.tasktop.c2c.server.internal.tasks.domain.Task subTask = subTaskQueue.poll().getBugsByDependson();
        subTaskQueue.addAll(subTask.getDependenciesesForBlocked());

        if (subTask.getEstimatedTime() != null) {
            sumOfSubtasksEstimate = sumOfSubtasksEstimate.add(subTask.getEstimatedTime());
        }
        for (com.tasktop.c2c.server.internal.tasks.domain.Comment c : subTask.getComments()) {
            if (c.getWorkTime() != null && c.getWorkTime().signum() > 0) {
                sumOfSubtasksTimeSpent = sumOfSubtasksTimeSpent.add(c.getWorkTime());
            }
        }
    }
    target.setSumOfSubtasksEstimatedTime(sumOfSubtasksEstimate);
    target.setSumOfSubtasksTimeSpent(sumOfSubtasksTimeSpent);

    if (!context.isThin()) {
        target.setBlocksTasks(new ArrayList<Task>(source.getDependenciesesForDependson().size()));
        for (Dependency dep : source.getDependenciesesForDependson()) {
            target.getBlocksTasks().add(shallowCopyAssociate(dep.getBugsByBlocked(), subcontext));
        }

        target.setSubTasks(new ArrayList<Task>(source.getDependenciesesForBlocked().size()));
        for (Dependency dep : source.getDependenciesesForBlocked()) {
            target.getSubTasks().add(shallowCopyAssociate(dep.getBugsByDependson(), subcontext));
        }
        if (source.getDuplicatesByBugId() != null) {
            target.setDuplicateOf(
                    shallowCopyAssociate(source.getDuplicatesByBugId().getBugsByDupeOf(), subcontext));
        }
        target.setDuplicates(new ArrayList<Task>());
        for (Duplicate duplicate : source.getDuplicatesesForDupeOf()) {
            target.getDuplicates().add(shallowCopyAssociate(duplicate.getBugsByBugId(), subcontext));
        }

        if (source.getStatusWhiteboard() != null && !source.getStatusWhiteboard().isEmpty()) {
            // A non-empty statusWhiteboard means we store description there for backward compatibility. (See
            // discussion in Task 422)
            target.setDescription(source.getStatusWhiteboard());
            // REVIEW do we really need this for subtasks?
            target.setWikiRenderedDescription(
                    renderer.render(source.getStatusWhiteboard(), context.getWikiMarkup()));
        }
        target.setAttachments((List<Attachment>) converter.convert(source.getAttachments(), subcontext));
    } else {
        // THIN tasks still get their parent populated
        if (!source.getDependenciesesForDependson().isEmpty()) {
            target.setParentTask(shallowCopyAssociate(
                    source.getDependenciesesForDependson().get(0).getBugsByBlocked(), subcontext));
        }
    }
}

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

private void populateKnowledgeTree(KnowledgeSourceCache ksCache) {
    if (this.knowledgeTree == null) {
        this.knowledgeTree = new HashSet<>();
        Queue<String> queue = new LinkedList<>();
        Arrays.addAll(queue, getPropositionIds());
        String propId;// w  w  w  .  java  2s  .co  m
        while ((propId = queue.poll()) != null) {
            PropositionDefinition propDef = ksCache.get(propId);
            if (propDef != null) {
                if (propDef.getInDataSource()) {
                    this.knowledgeTree.add(propDef.getId());
                }
                Arrays.addAll(queue, propDef.getChildren());
            } else {
                throw new AssertionError("Invalid proposition definition " + propId);
            }
        }
    }
}

From source file:au.org.ala.delta.intkey.directives.CharacterListArgument.java

@Override
public List<au.org.ala.delta.model.Character> parseInput(Queue<String> inputTokens, IntkeyContext context,
        String directiveName, StringBuilder stringRepresentationBuilder) throws IntkeyDirectiveParseException {

    List<String> selectedKeywordsOrCharacterNumbers = new ArrayList<String>();

    boolean overrideExcludedCharacters = false;

    String token = inputTokens.poll();
    if (token != null && token.equalsIgnoreCase(OVERRIDE_EXCLUDED_CHARACTERS)) {
        overrideExcludedCharacters = true;
        token = inputTokens.poll();// w  ww.  ja  va 2s. c  o m
    }

    List<au.org.ala.delta.model.Character> characters = null;

    SelectionMode selectionMode = context.displayKeywords() ? SelectionMode.KEYWORD : SelectionMode.LIST;
    DirectivePopulator populator = context.getDirectivePopulator();

    if (token != null) {
        if (token.equalsIgnoreCase(DEFAULT_DIALOG_WILDCARD)) {
            // do nothing - default selection mode is already set above.
        } else if (token.equalsIgnoreCase(KEYWORD_DIALOG_WILDCARD)) {
            selectionMode = SelectionMode.KEYWORD;
        } else if (token.equalsIgnoreCase(LIST_DIALOG_WILDCARD)) {
            selectionMode = SelectionMode.LIST;
        } else {
            characters = new ArrayList<au.org.ala.delta.model.Character>();
            while (token != null) {
                try {
                    characters.addAll(ParsingUtils.parseCharacterToken(token, context));
                    selectedKeywordsOrCharacterNumbers.add(token);
                    token = inputTokens.poll();
                } catch (IllegalArgumentException ex) {
                    throw new IntkeyDirectiveParseException("UnrecognizedCharacterKeyword.error", token);
                }
            }

            if (!(overrideExcludedCharacters || _selectFromAll)) {
                characters.retainAll(context.getIncludedCharacters());
            }
        }
    }

    if (characters == null) {
        if (context.isProcessingDirectivesFile()) {
            //ignore incomplete directives when processing an input file
            return null;
        }

        List<String> selectedKeywords = new ArrayList<String>();
        if (selectionMode == SelectionMode.KEYWORD) {
            characters = populator.promptForCharactersByKeyword(directiveName,
                    !(overrideExcludedCharacters || _selectFromAll), _noneSelectionPermitted, selectedKeywords);
        } else {
            characters = populator.promptForCharactersByList(directiveName,
                    !(overrideExcludedCharacters || _selectFromAll), selectedKeywords);
        }

        if (characters == null) {
            // cancelled
            return null;
        }

        // Put selected keywords or taxon numbers into a collection to use
        // to build the string representation.
        if (!selectedKeywords.isEmpty()) {
            for (String selectedKeyword : selectedKeywords) {
                if (selectedKeyword.contains(" ")) {
                    // Enclose any keywords that contain spaces in quotes
                    // for the string representation
                    selectedKeywordsOrCharacterNumbers.add("\"" + selectedKeyword + "\"");
                } else {
                    selectedKeywordsOrCharacterNumbers.add(selectedKeyword);
                }
            }
        } else {
            List<Integer> selectedCharacterNumbers = new ArrayList<Integer>();
            for (int i = 0; i < characters.size(); i++) {
                Character ch = characters.get(i);
                selectedCharacterNumbers.add(ch.getCharacterId());
            }
            selectedKeywordsOrCharacterNumbers
                    .add(Utils.formatIntegersAsListOfRanges(selectedCharacterNumbers));
        }
    }

    // build the string representation of the directive call
    stringRepresentationBuilder.append(" ");

    if (overrideExcludedCharacters) {
        stringRepresentationBuilder.append(OVERRIDE_EXCLUDED_CHARACTERS);
        stringRepresentationBuilder.append(" ");
    }

    stringRepresentationBuilder.append(StringUtils.join(selectedKeywordsOrCharacterNumbers, " "));

    if (characters.size() == 0 && !_noneSelectionPermitted) {
        throw new IntkeyDirectiveParseException("NoCharactersInSet.error");
    }

    Collections.sort(characters);

    return characters;
}