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:sadl.models.pdrta.PDRTA.java

public void checkConsistency() {

    // Checking that a path for each sequence exists
    for (int i = 0; i < input.getAlphSize(); i++) {
        final Set<Entry<Integer, Interval>> ins = root.getIntervals(i).entrySet();
        for (final Entry<Integer, Interval> eIn : ins) {
            final Set<Entry<Integer, TimedTail>> tails = eIn.getValue().getTails().entries();
            for (final Entry<Integer, TimedTail> eTail : tails) {
                TimedTail t = eTail.getValue();
                PDRTAState source = root, target;
                while (t != null) {
                    assert (source.getInterval(t.getSymbolAlphIndex(), t.getTimeDelay()).getTails()
                            .containsValue(t));
                    target = source.getTarget(t);
                    if (target == null) {
                        throw new IllegalStateException(
                                "The tail (" + input.getSymbol(t.getSymbolAlphIndex()) + "," + t.getTimeDelay()
                                        + ") has no transition from state ((" + source.getIndex() + "))!");
                    }/*from   ww  w .  ja  v  a2s.  co  m*/
                    source = target;
                    t = t.getNextTail();
                }
            }
        }
    }

    // Checking that number of states in structure is equal to number of states in map
    int counter = 0;
    final Set<PDRTAState> seen = new HashSet<>();
    seen.add(root);
    final Queue<PDRTAState> q = new LinkedList<>();
    q.add(root);
    while (!q.isEmpty()) {
        final PDRTAState s = q.poll();
        PDRTAState s2 = states.get(s.getIndex());
        if (s != s2) {
            throw new IllegalStateException("State (" + s.getIndex() + ") is not in map!");
        }
        counter++;
        for (int i = 0; i < input.getAlphSize(); i++) {
            final Set<Entry<Integer, Interval>> ins = s.getIntervals(i).entrySet();
            for (final Entry<Integer, Interval> eIn : ins) {
                s2 = eIn.getValue().getTarget();
                if (s2 != null && !seen.contains(s2)) {
                    seen.add(s2);
                    q.add(s2);
                }
            }
        }
    }
    if (counter != states.size()) {
        throw new IllegalStateException(
                "Found " + counter + " sates in structure but " + states.size() + " states are in map!");
    }
}

From source file:org.glassfish.jersey.examples.sseitemstore.jaxrs.JaxrsItemStoreResourceTest.java

/**
 * Test the {@link SseEventSource} reconnect feature.
 *
 * @throws Exception in case of a test failure.
 *///from w  w  w. j av  a 2s  .c  o m
@Test
public void testEventSourceReconnect() throws Exception {
    final WebTarget itemsTarget = target("items");
    final CountDownLatch latch = new CountDownLatch(MAX_ITEMS * MAX_LISTENERS * 2); // countdown only on new item events
    final List<Queue<String>> receivedQueues = new ArrayList<>(MAX_LISTENERS);
    final SseEventSource[] sources = new SseEventSource[MAX_LISTENERS];

    for (int i = 0; i < MAX_LISTENERS; i++) {
        final int id = i;
        final SseEventSource es = SseEventSource.target(itemsTarget.path("events"))
                .reconnectingEvery(1, TimeUnit.MILLISECONDS).build();
        sources[id] = es;

        final Queue<String> received = new ConcurrentLinkedQueue<>();
        receivedQueues.add(received);

        es.register(inboundEvent -> {
            try {
                if (null == inboundEvent.getName()) {
                    final String data = inboundEvent.readData();
                    LOGGER.info("[-i-] SOURCE " + id + ": Received event id=" + inboundEvent.getId() + " data="
                            + data);
                    received.add(data);
                    latch.countDown();
                }
            } catch (Exception ex) {
                LOGGER.log(Level.SEVERE, "[-x-] SOURCE " + id + ": Error getting event data.", ex);
                received.add("[data processing error]");
            }
        });
    }

    final String[] postedItems = new String[MAX_ITEMS * 2];
    try {
        open(sources);

        for (int i = 0; i < MAX_ITEMS; i++) {
            final String item = String.format("round-1-%02d", i);
            postItem(itemsTarget, item);
            postedItems[i] = item;
            sendCommand(itemsTarget, "disconnect");
            Thread.sleep(200);
        }

        final int reconnectDelay = 1;
        sendCommand(itemsTarget, "reconnect " + reconnectDelay);
        sendCommand(itemsTarget, "disconnect");

        Thread.sleep(reconnectDelay * 1000);

        for (int i = 0; i < MAX_ITEMS; i++) {
            final String item = String.format("round-2-%02d", i);
            postedItems[i + MAX_ITEMS] = item;
            postItem(itemsTarget, item);
        }

        sendCommand(itemsTarget, "reconnect now");

        assertTrue("Waiting to receive all events has timed out.",
                latch.await(
                        (1 + MAX_LISTENERS * (MAX_ITEMS + 1) * reconnectDelay) * getAsyncTimeoutMultiplier(),
                        TimeUnit.SECONDS));

        // need to force disconnect on server in order for EventSource.close(...) to succeed with HttpUrlConnection
        sendCommand(itemsTarget, "disconnect");
    } finally {
        close(sources);
    }

    final String storedItems = itemsTarget.request().get(String.class);
    for (String item : postedItems) {
        assertThat("Posted item '" + item + "' stored on server", storedItems, containsString(item));
    }

    int sourceId = 0;
    for (Queue<String> queue : receivedQueues) {
        assertThat("Received events in source " + sourceId, queue, describedAs("Collection containing %0",
                hasItems(postedItems), Arrays.asList(postedItems).toString()));
        assertThat("Size of received queue for source " + sourceId, queue.size(), equalTo(postedItems.length));
        sourceId++;
    }
}

From source file:org.chromium.chrome.browser.media.router.cast.CastMessageHandler.java

@VisibleForTesting
void handleStopMessage(String clientId, int sequenceNumber) {
    Queue<Integer> sequenceNumbersForClient = mStopRequests.get(clientId);
    if (sequenceNumbersForClient == null) {
        sequenceNumbersForClient = new ArrayDeque<Integer>();
        mStopRequests.put(clientId, sequenceNumbersForClient);
    }//  w  w w.  j av  a  2  s.  c  om
    sequenceNumbersForClient.add(sequenceNumber);

    mSession.stopApplication();
}

From source file:sadl.models.pdrta.PDRTA.java

@Override
public int getTransitionCount() {
    int result = 0;
    final Queue<PDRTAState> q = new ArrayDeque<>();
    final Set<PDRTAState> found = new HashSet<>();
    q.add(root);
    found.add(root);/*from ww w.j  a v  a  2 s  .com*/
    while (!q.isEmpty()) {
        final PDRTAState s = q.remove();
        for (int i = 0; i < input.getAlphSize(); i++) {
            final Set<Entry<Integer, Interval>> ins = s.getIntervals(i).entrySet();
            for (final Entry<Integer, Interval> eIn : ins) {
                final Interval in = eIn.getValue();
                final PDRTAState t = in.getTarget();
                if (t != null) {
                    result++;
                }
            }
        }
    }
    return result;
}

From source file:org.kuali.student.enrollment.class1.krms.service.impl.FERuleEditorMaintainableImpl.java

public AgendaItemDefinition maintainAgendaItems(AgendaEditor agenda, String namePrefix, String nameSpace) {

    Queue<RuleDefinition.Builder> rules = new LinkedList<RuleDefinition.Builder>();
    FEAgendaEditor feAgenda;//from w ww .  j  a va2s .com
    if (agenda instanceof FEAgendaEditor) {
        feAgenda = (FEAgendaEditor) agenda;
        for (RuleEditor rule : feAgenda.getRules()) {
            if (!rule.isDummy()) {
                rules.add(this.finRule(rule, namePrefix, nameSpace));
            }
        }

        AgendaItemDefinition.Builder rootItemBuilder = manageFirstItem(agenda);

        AgendaItemDefinition.Builder itemToDelete = null;
        AgendaItemDefinition.Builder itemBuilder = rootItemBuilder;
        while (rules.peek() != null) {
            itemBuilder.setRule(rules.poll());
            itemBuilder.setRuleId(itemBuilder.getRule().getId());
            if (rules.peek() != null) {
                if (itemBuilder.getWhenFalse() == null) {
                    itemBuilder.setWhenFalse(AgendaItemDefinition.Builder.create(null, agenda.getId()));
                }
                itemBuilder = itemBuilder.getWhenFalse();
            } else {
                itemToDelete = itemBuilder.getWhenFalse();
                itemBuilder.setWhenFalse(null);
            }
        }

        return manageAgendaItems(agenda, rootItemBuilder, itemToDelete);
    }

    return null;
}

From source file:fr.landel.utils.assertor.predicate.PredicateAssertorIterableTest.java

/**
 * Test method for {@link AssertorIterable} .
 *//*  w  w  w  .  ja  v a 2 s .c  o  m*/
@Test
public void testPredicateGet() {
    final String el = "element";

    final Set<String> set = new HashSet<>();
    set.add(el);
    final List<String> list = new ArrayList<>();
    list.add(el);
    final Queue<String> queue = new LinkedList<>();
    queue.add(el);

    assertFalse(Assertor.<Set<String>, String>ofIterable().hasHashCode(0).that(set).isOK());
    assertTrue(Assertor.<Set<String>, String>ofIterable().hasHashCode(Objects.hashCode(set)).that(set).isOK());

    assertFalse(Assertor.<String>ofSet().hasHashCode(0).that(set).isOK());
    assertFalse(Assertor.<String>ofList().hasHashCode(0).that(list).isOK());
    assertFalse(Assertor.<String>ofQueue().hasHashCode(0).that(queue).isOK());
}

From source file:org.apache.drill.exec.store.mongo.MongoGroupScan.java

@Override
public void applyAssignments(List<DrillbitEndpoint> endpoints) throws PhysicalOperatorSetupException {
    logger.debug("Incoming endpoints :" + endpoints);
    watch.reset();/*from   w  w  w .j  a  v a  2 s .c  om*/
    watch.start();

    final int numSlots = endpoints.size();
    int totalAssignmentsTobeDone = chunksMapping.size();

    Preconditions.checkArgument(numSlots <= totalAssignmentsTobeDone, String.format(
            "Incoming endpoints %d is greater than number of chunks %d", numSlots, totalAssignmentsTobeDone));

    final int minPerEndpointSlot = (int) Math.floor((double) totalAssignmentsTobeDone / numSlots);
    final int maxPerEndpointSlot = (int) Math.ceil((double) totalAssignmentsTobeDone / numSlots);

    endpointFragmentMapping = Maps.newHashMapWithExpectedSize(numSlots);
    Map<String, Queue<Integer>> endpointHostIndexListMap = Maps.newHashMap();

    for (int i = 0; i < numSlots; ++i) {
        endpointFragmentMapping.put(i, new ArrayList<MongoSubScanSpec>(maxPerEndpointSlot));
        String hostname = endpoints.get(i).getAddress();
        Queue<Integer> hostIndexQueue = endpointHostIndexListMap.get(hostname);
        if (hostIndexQueue == null) {
            hostIndexQueue = Lists.newLinkedList();
            endpointHostIndexListMap.put(hostname, hostIndexQueue);
        }
        hostIndexQueue.add(i);
    }

    Set<Entry<String, List<ChunkInfo>>> chunksToAssignSet = Sets.newHashSet(chunksInverseMapping.entrySet());

    for (Iterator<Entry<String, List<ChunkInfo>>> chunksIterator = chunksToAssignSet.iterator(); chunksIterator
            .hasNext();) {
        Entry<String, List<ChunkInfo>> chunkEntry = chunksIterator.next();
        Queue<Integer> slots = endpointHostIndexListMap.get(chunkEntry.getKey());
        if (slots != null) {
            for (ChunkInfo chunkInfo : chunkEntry.getValue()) {
                Integer slotIndex = slots.poll();
                List<MongoSubScanSpec> subScanSpecList = endpointFragmentMapping.get(slotIndex);
                subScanSpecList.add(buildSubScanSpecAndGet(chunkInfo));
                slots.offer(slotIndex);
            }
            chunksIterator.remove();
        }
    }

    PriorityQueue<List<MongoSubScanSpec>> minHeap = new PriorityQueue<List<MongoSubScanSpec>>(numSlots,
            LIST_SIZE_COMPARATOR);
    PriorityQueue<List<MongoSubScanSpec>> maxHeap = new PriorityQueue<List<MongoSubScanSpec>>(numSlots,
            LIST_SIZE_COMPARATOR_REV);
    for (List<MongoSubScanSpec> listOfScan : endpointFragmentMapping.values()) {
        if (listOfScan.size() < minPerEndpointSlot) {
            minHeap.offer(listOfScan);
        } else if (listOfScan.size() > minPerEndpointSlot) {
            maxHeap.offer(listOfScan);
        }
    }

    if (chunksToAssignSet.size() > 0) {
        for (Entry<String, List<ChunkInfo>> chunkEntry : chunksToAssignSet) {
            for (ChunkInfo chunkInfo : chunkEntry.getValue()) {
                List<MongoSubScanSpec> smallestList = minHeap.poll();
                smallestList.add(buildSubScanSpecAndGet(chunkInfo));
                minHeap.offer(smallestList);
            }
        }
    }

    while (minHeap.peek() != null && minHeap.peek().size() < minPerEndpointSlot) {
        List<MongoSubScanSpec> smallestList = minHeap.poll();
        List<MongoSubScanSpec> largestList = maxHeap.poll();
        smallestList.add(largestList.remove(largestList.size() - 1));
        if (largestList.size() > minPerEndpointSlot) {
            maxHeap.offer(largestList);
        }
        if (smallestList.size() < minPerEndpointSlot) {
            minHeap.offer(smallestList);
        }
    }

    logger.debug("Built assignment map in {} s.\nEndpoints: {}.\nAssignment Map: {}",
            watch.elapsed(TimeUnit.NANOSECONDS) / 1000, endpoints, endpointFragmentMapping.toString());
}

From source file:bme.iclef.weka.featureselection.InfoGain.java

public AttributeInfoGain[] topAttributes(final int n) {
    Queue<AttributeInfoGain> all = new PriorityQueue<AttributeInfoGain>(m_InfoGains.length,
            new Comparator<AttributeInfoGain>() {
                @Override//ww  w .  ja v  a2s  .c o  m
                public int compare(AttributeInfoGain o1, AttributeInfoGain o2) {
                    return Double.compare(o2.infoGain, o1.infoGain); // descending
                }
            });
    for (int i = 0; i < m_InfoGains.length; i++)
        all.add(new AttributeInfoGain(i, m_InfoGains[i]));
    AttributeInfoGain[] best = new AttributeInfoGain[n];
    for (int i = 0; i < best.length; i++) {
        best[i] = all.remove();
    }
    return best;
}

From source file:ch.mlutz.plugins.t4e.tapestry.TapestryModule.java

/**
 * Scans app specification for module metadata (mainly page and component
 * class packages); then scans this module (html and java files) and updates
 * the central tapestryIndex with file relations; finally scans
 * hivemodule.xml and collects and stores services in this module
 * @param monitor//from  w  w  w . j a  va2 s  .  c  om
 *
 * @throws TapestryException
 */
public void scanAndUpdateIndex(IProgressMonitor monitor) throws TapestryException {
    try {
        // validateAppSpecificationFile(appSpecification.getAppSpecificationFile());
        if (!getAppSpecification().update()) {
            return;
        }

        Queue<IResource> resourceQueue = new LinkedList<IResource>();
        resourceQueue.add(webappFolder);

        IResource current = resourceQueue.poll();
        while (current != null) {
            if (current.getType() == IResource.FILE) {
                if ("html".equals(FilenameUtils.getExtension(current.getName()))) {
                    try {
                        findRelatedUnit((IFile) current);
                    } catch (CoreException e) {
                        log.warn("Couldn't find related unit for " + current.getName(), e);
                    }
                }
            } else if (current.getType() == IResource.FOLDER) {
                // add all members in this folder to queue
                IResource[] members;
                try {
                    members = ((IFolder) current).members();
                    for (IResource member : members) {
                        resourceQueue.add(member);
                    }
                } catch (CoreException e) {
                    log.warn("Couldn't get members of folder " + current.getName(), e);
                }
            }
            current = resourceQueue.poll();
        }
    } finally {
        if (monitor != null) {
            monitor.worked(getScanAndUpdateWork());
        }
    }
}