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:cn.chenlichao.web.ssm.controller.BaseController.java

@SuppressWarnings("unchecked")
private void addActionMessage(String key, String message) {
    Queue<String> queue = (Queue<String>) localRequest.get().getSession().getAttribute(key);
    if (queue == null) {
        queue = new LinkedReadOnceQueue<>();
        localRequest.get().getSession().setAttribute(key, queue);
    }//from w ww  . ja v  a  2 s  .  c om
    if (message != null) {
        message = message.replaceAll("\n", "\\n");
    }
    queue.add(message);
}

From source file:org.apache.gobblin.ingestion.google.webmaster.GoogleWebmasterDataFetcherImpl.java

/**
 * Due to the limitation of the API, we can get a maximum of 5000 rows at a time. Another limitation is that, results are sorted by click count descending. If two rows have the same click count, they are sorted in an arbitrary way. (Read more at https://developers.google.com/webmaster-tools/v3/searchanalytics). So we try to get all pages by partitions, if a partition has 5000 rows returned. We try partition current partition into more granular levels.
 *
 *///from  w w w .  ja v  a 2s .co m
@Override
public Collection<ProducerJob> getAllPages(String startDate, String endDate, String country, int rowLimit)
        throws IOException {
    log.info("Requested row limit: " + rowLimit);
    if (!_jobs.isEmpty()) {
        log.info("Service got hot started.");
        return _jobs;
    }
    ApiDimensionFilter countryFilter = GoogleWebmasterFilter.countryEqFilter(country);

    List<GoogleWebmasterFilter.Dimension> requestedDimensions = new ArrayList<>();
    requestedDimensions.add(GoogleWebmasterFilter.Dimension.PAGE);
    int expectedSize = -1;
    if (rowLimit >= GoogleWebmasterClient.API_ROW_LIMIT) {
        //expected size only makes sense when the data set size is larger than GoogleWebmasterClient.API_ROW_LIMIT
        expectedSize = getPagesSize(startDate, endDate, country, requestedDimensions,
                Arrays.asList(countryFilter));
        log.info(String.format("Expected number of pages is %d for market-%s from %s to %s", expectedSize,
                GoogleWebmasterFilter.countryFilterToString(countryFilter), startDate, endDate));
    }

    Queue<Pair<String, FilterOperator>> jobs = new ArrayDeque<>();
    jobs.add(Pair.of(_siteProperty, FilterOperator.CONTAINS));

    Collection<String> allPages = getPages(startDate, endDate, requestedDimensions, countryFilter, jobs,
            Math.min(rowLimit, GoogleWebmasterClient.API_ROW_LIMIT));
    int actualSize = allPages.size();
    log.info(String.format("A total of %d pages fetched for property %s at country-%s from %s to %s",
            actualSize, _siteProperty, country, startDate, endDate));

    if (expectedSize != -1 && actualSize != expectedSize) {
        log.warn(String.format("Expected page size is %d, but only able to get %d", expectedSize, actualSize));
    }

    ArrayDeque<ProducerJob> producerJobs = new ArrayDeque<>(actualSize);
    for (String page : allPages) {
        producerJobs.add(new SimpleProducerJob(page, startDate, endDate));
    }
    return producerJobs;
}

From source file:it.geosolutions.geobatch.imagemosaic.GranuleRemoverOnlineTest.java

@Test
public void removeGranules() throws Exception {
    removeStore();/* ww  w .j a  va2s .c o  m*/

    File imcFile;

    //=== Add first set of granules
    LOGGER.info(" ***** CREATING FIRST BATCH OF GRANULES");
    {
        ImageMosaicCommand imc = recreateIMC("20121004", "20121005", "20121006", "20121007", "20121008");
        // serialize
        imcFile = new File(getTempDir(), "ImageMosaicCommand0.xml");
        LOGGER.info("Creating  " + imcFile);
        ImageMosaicCommand.serialize(imc, imcFile.toString());
    }

    {
        Queue<EventObject> inputQ = new LinkedList<EventObject>();
        inputQ.add(new FileSystemEvent(imcFile, FileSystemEventType.FILE_ADDED));
        ImageMosaicAction action = createMosaicAction(createMosaicConfig());
        Queue<EventObject> outputQ = action.execute(inputQ);
    }

    DataStore dataStore = createDatastore();
    assertEquals(5, dataStore.getFeatureSource(STORENAME).getCount(Query.ALL));

    //=== Add another granule
    LOGGER.info(" ***** ADD ONE MORE GRANULE");
    {
        ImageMosaicCommand imc = recreateIMC("20121009");
        // serialize
        imcFile = new File(getTempDir(), "ImageMosaicCommand1.xml");
        LOGGER.info("Creating  " + imcFile);
        ImageMosaicCommand.serialize(imc, imcFile.toString());
    }

    {
        Queue<EventObject> inputQ = new LinkedList<EventObject>();
        inputQ.add(new FileSystemEvent(imcFile, FileSystemEventType.FILE_ADDED));
        ImageMosaicAction action = createMosaicAction(createMosaicConfig());
        Queue<EventObject> outputQ = action.execute(inputQ);
    }

    assertEquals(6, dataStore.getFeatureSource(STORENAME).getCount(Query.ALL));

    //== performs some tests on delete list
    LOGGER.info(" ***** REMOVE OLD GRANULE");
    {
        ImageMosaicCommand imc = recreateIMC("nothing");
        GranuleRemover remover = new GranuleRemover();

        Calendar cal = new GregorianCalendar(2012, 9, 7);
        cal.setTimeZone(TimeZone.getTimeZone("UTC"));

        remover.setBaseDate(cal);
        remover.setDaysAgo(2);
        remover.enrich(imc);
        LOGGER.info("remove " + imc.getDelFiles());
        assertEquals(2, imc.getDelFiles().size());

        imc.setDelFiles(null);
        remover.setDaysAgo(1);
        remover.enrich(imc);
        LOGGER.info("remove " + imc.getDelFiles());
        assertEquals(3, imc.getDelFiles().size());
        assertNotNull(imc.getAddFiles());

        // serialize
        imcFile = new File(getTempDir(), "ImageMosaicCommand2.xml");
        LOGGER.info("Creating  " + imcFile);
        ImageMosaicCommand.serialize(imc, imcFile.toString());
    }

    //== run the action with latest IMC
    {
        Queue<EventObject> inputQ = new LinkedList<EventObject>();
        inputQ.add(new FileSystemEvent(imcFile, FileSystemEventType.FILE_ADDED));
        ImageMosaicConfiguration conf = createMosaicConfig();
        //            conf.setFailIgnored(true);
        ImageMosaicAction action = createMosaicAction(conf);
        Queue<EventObject> outputQ = action.execute(inputQ);
    }

    assertEquals(3, dataStore.getFeatureSource(STORENAME).getCount(Query.ALL));

    //== Cleanup
    removeStore();
}

From source file:za.co.jumpingbean.alfresco.repo.EmailDocumentsAction.java

public void addAttachments(final Action action, final NodeRef nodeRef, MimeMessage mimeMessage)
        throws MessagingException {
    String text = (String) action.getParameterValue(PARAM_BODY);
    Boolean convertToPDF = (Boolean) action.getParameterValue(PARAM_CONVERT);
    MimeMultipart mail = new MimeMultipart("mixed");
    MimeBodyPart bodyText = new MimeBodyPart();
    bodyText.setText(text);/*from  w  w  w .jav  a 2 s .com*/
    mail.addBodyPart(bodyText);

    Queue<NodeRef> que = new LinkedList<>();
    QName type = nodeService.getType(nodeRef);
    if (type.isMatch(ContentModel.TYPE_FOLDER) || type.isMatch(ContentModel.TYPE_CONTAINER)) {
        que.add(nodeRef);
    } else {
        addAttachement(nodeRef, mail, convertToPDF);
    }
    while (!que.isEmpty()) {
        NodeRef tmpNodeRef = que.remove();
        List<ChildAssociationRef> list = nodeService.getChildAssocs(tmpNodeRef);
        for (ChildAssociationRef childRef : list) {
            NodeRef ref = childRef.getChildRef();
            if (nodeService.getType(ref).isMatch(ContentModel.TYPE_CONTENT)) {
                addAttachement(ref, mail, convertToPDF);
            } else {
                que.add(ref);
            }
        }
    }
    mimeMessage.setContent(mail);
}

From source file:org.mozilla.gecko.sync.jpake.JPakeClient.java

/**
 * Set up Sender sequence of stages for J-PAKE. (sender of credentials)
 *
 *///from  w  w  w  . j  a va  2 s  .  co m

private void prepareSenderStages() {
    Queue<JPakeStage> jStages = new LinkedList<JPakeStage>();
    jStages.add(new ComputeStepOneStage());
    jStages.add(new GetRequestStage());
    jStages.add(new PutRequestStage());
    jStages.add(new ComputeStepTwoStage());
    jStages.add(new GetRequestStage());
    jStages.add(new PutRequestStage());
    jStages.add(new ComputeFinalStage());
    jStages.add(new GetRequestStage());
    jStages.add(new VerifyPairingStage()); // Calls onPaired if verified.

    stages = jStages;
}

From source file:org.lambda3.indra.core.RelatednessClient.java

protected List<ScoredTextPair> compute(Map<? extends AnalyzedPair, VectorPair> vectorPairs,
        RelatednessFunction func) {/* www  .  j  a va2  s. co m*/
    Queue<ScoredTextPair> scoredTextPairs = new ConcurrentLinkedQueue<>();

    vectorPairs.entrySet().stream().parallel().forEach(entry -> {
        AnalyzedPair pair = entry.getKey();
        VectorPair vectorPair = entry.getValue();

        if (vectorPair.v1 != null && vectorPair.v2 != null) {
            scoredTextPairs.add(new ScoredTextPair(pair,
                    func.sim(vectorPair.v1, vectorPair.v2, vectorSpace.getMetadata().sparse)));
        } else {
            scoredTextPairs.add(new ScoredTextPair(pair, 0));
        }
    });

    //TODO REVIEW HERE
    return new LinkedList<>(scoredTextPairs);
}

From source file:de.tbuchloh.kiskis.gui.treeview.TreeView.java

/**
 * @return gets all the displayed tree nodes
 *///w  w w. j  a v a2  s.c om
protected Collection<MyTreeNode> getAllNodes() {
    final Queue<MyTreeNode> treeNodes = new LinkedList<MyTreeNode>();
    treeNodes.add(getRoot());
    final Collection<MyTreeNode> r = new LinkedList<MyTreeNode>();
    r.add(getRoot());
    while (!treeNodes.isEmpty()) {
        final MyTreeNode node = treeNodes.poll();
        final List<MyTreeNode> children = Collections.list(node.children());
        treeNodes.addAll(children);
        r.addAll(children);
    }
    return r;
}

From source file:org.kuali.rice.krad.uif.util.ComponentUtils.java

/**
 * Replace all IDs from a component and its children with new generated ID values.
 *
 * <p>If there are features that depend on a static id of this
 * component, this call may cause errors.</p>
 *
 * @param components A list of component to clear all IDs from.
 * @see AssignIdsTask For a complete description of the algorithm.
 *///from   w w  w.  ja  v a2 s .co m
public static void clearAndAssignIds(List<? extends Component> components) {
    if (components == null || components.isEmpty()) {
        return;
    }

    int hash = 1;
    @SuppressWarnings("unchecked")
    Queue<LifecycleElement> toClear = RecycleUtils.getInstance(LinkedList.class);
    toClear.addAll(components);
    try {
        while (!toClear.isEmpty()) {
            LifecycleElement element = toClear.poll();

            hash = generateId(element, hash);

            for (LifecycleElement nested : ViewLifecycleUtils.getElementsForLifecycle(element).values()) {
                if (nested != null) {
                    toClear.add(nested);
                }
            }

            if (element instanceof Component) {
                List<Component> propertyReplacerComponents = ((Component) element)
                        .getPropertyReplacerComponents();
                if (propertyReplacerComponents == null) {
                    continue;
                }

                for (Component nested : propertyReplacerComponents) {
                    if (nested != null) {
                        toClear.add(nested);
                    }
                }
            }
        }
    } finally {
        toClear.clear();
        RecycleUtils.recycle(toClear);
    }
}

From source file:playground.johannes.snowball2.Centrality.java

public void run(Graph g, int iteration) {
    if (iteration != lastIteration) {
        isSampled = false;/*from   w w  w .j a  v a  2s  . co  m*/
        if (g instanceof SampledGraph)
            isSampled = true;

        graphDecorator = new CentralityGraphDecorator(g);
        graph = (CentralityGraph) graphDecorator.getSparseGraph();
        Queue<CentralityVertex> vertices = new ConcurrentLinkedQueue<CentralityVertex>();
        for (SparseVertex v : graph.getVertices())
            vertices.add((CentralityVertex) v);

        int numThreads = Runtime.getRuntime().availableProcessors();
        List<DijkstraThread> threads = new ArrayList<DijkstraThread>(numThreads);

        DijkstraThread.count = 0;
        for (int i = 0; i < numThreads; i++) {
            threads.add(new DijkstraThread(graph, vertices));
        }

        for (DijkstraThread thread : threads) {
            thread.start();
        }

        for (DijkstraThread thread : threads) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        calcCloseness();
        calcBetweenness();

        lastIteration = iteration;
    }
}

From source file:com.microsoft.office.plugin.MetadataMojo.java

/**
 * Adds type to queue for generation.//from w  w w.j av  a2s.  c om
 * 
 * @param entitySetNames Maps entity type and its set name.
 * @param currentType Fully qualified enity type (contains schema namespace and class name).
 * @param paths Maps entity type and path to its set related to service root.
 * @param typesQueue A queue.
 * @param np Navigation property to extract entity type and set name.
 */
private void addTypeToQueue(Map<String, String> entitySetNames, String currentType, Map<String, String> paths,
        Queue<String> typesQueue, NavigationProperty np) {
    typesQueue.add(utility.getNameFromNS(np.getType()));
    if (!entitySetNames.containsKey(utility.getNameFromNS(np.getType()))) {
        entitySetNames.put(utility.getNameFromNS(np.getType()), np.getName());
    }
    if (!paths.containsKey(utility.getNameFromNS(np.getType()))) {
        paths.put(utility.getNameFromNS(np.getType()),
                paths.get(utility.getNameFromNS(currentType))
                        + entitySetNames.get(utility.getNameFromNS(currentType))
                        + (getUtility().isSingleton(entitySetNames.get(utility.getNameFromNS(currentType)))
                                ? "/"
                                : "(%s)/"));
    }
}