Example usage for java.util Queue contains

List of usage examples for java.util Queue contains

Introduction

In this page you can find the example usage for java.util Queue contains.

Prototype

boolean contains(Object o);

Source Link

Document

Returns true if this collection contains the specified element.

Usage

From source file:com.barchart.netty.server.http.TestHttpServer.java

@Test
public void testTooManyConnections() throws Exception {

    final Queue<Integer> status = new LinkedBlockingQueue<Integer>();

    final Runnable r = new Runnable() {
        @Override//from ww  w. j  a v a2  s  . com
        public void run() {
            try {
                final HttpResponse response = client
                        .execute(new HttpGet("http://localhost:" + port + "/client-disconnect"));
                status.add(response.getStatusLine().getStatusCode());
                EntityUtils.consume(response.getEntity());
            } catch (final Exception e) {
                e.printStackTrace();
            }
        }
    };

    final Thread t1 = new Thread(r);
    t1.start();

    final Thread t2 = new Thread(r);
    t2.start();

    t1.join();
    t2.join();

    assertEquals(2, status.size());
    assertTrue(status.contains(200));
    assertTrue(status.contains(503));

}

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

/**
 * Test the item addition, addition event broadcasting and item retrieval from {@link JaxrsItemStoreResource}.
 *
 * @throws Exception in case of a test failure.
 *//*ww w .j av a 2 s. c  o  m*/
@Test
public void testItemsStore() throws Exception {
    final List<String> items = Collections.unmodifiableList(Arrays.asList("foo", "bar", "baz"));
    final WebTarget itemsTarget = target("items");
    final CountDownLatch latch = new CountDownLatch(items.size() * MAX_LISTENERS * 2); // countdown on all events
    final List<Queue<Integer>> indexQueues = new ArrayList<>(MAX_LISTENERS);
    final SseEventSource[] sources = new SseEventSource[MAX_LISTENERS];
    final AtomicInteger sizeEventsCount = new AtomicInteger(0);

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

        final Queue<Integer> indexes = new ConcurrentLinkedQueue<>();
        indexQueues.add(indexes);

        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);
                    indexes.add(items.indexOf(data));
                } else if ("size".equals(inboundEvent.getName())) {
                    sizeEventsCount.incrementAndGet();
                }
            } catch (Exception ex) {
                LOGGER.log(Level.SEVERE, "[-x-] SOURCE " + id + ": Error getting event data.", ex);
                indexes.add(-999);
            } finally {
                latch.countDown();
            }
        });
    }

    try {
        open(sources);
        items.forEach((item) -> postItem(itemsTarget, item));

        assertTrue("Waiting to receive all events has timed out.",
                latch.await((1000 + MAX_LISTENERS * RECONNECT_DEFAULT) * getAsyncTimeoutMultiplier(),
                        TimeUnit.MILLISECONDS));

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

    String postedItems = itemsTarget.request().get(String.class);
    items.forEach(
            (item) -> assertTrue("Item '" + item + "' not stored on server.", postedItems.contains(item)));

    final AtomicInteger queueId = new AtomicInteger(0);
    indexQueues.forEach((indexes) -> {
        for (int i = 0; i < items.size(); i++) {
            assertTrue("Event for '" + items.get(i) + "' not received in queue " + queueId.get(),
                    indexes.contains(i));
        }
        assertEquals("Not received the expected number of events in queue " + queueId.get(), items.size(),
                indexes.size());
        queueId.incrementAndGet();
    });

    assertEquals("Number of received 'size' events does not match.", items.size() * MAX_LISTENERS,
            sizeEventsCount.get());
}

From source file:org.glassfish.jersey.examples.sseitemstore.jersey.JerseyItemStoreResourceTest.java

/**
 * Test the item addition, addition event broadcasting and item retrieval from {@link ItemStoreResource}.
 *
 * @throws Exception in case of a test failure.
 *//*  www . j  a v a  2 s . co  m*/
@Test
public void testItemsStore() throws Exception {
    final List<String> items = Collections.unmodifiableList(Arrays.asList("foo", "bar", "baz"));
    final WebTarget itemsTarget = target("items");
    final CountDownLatch latch = new CountDownLatch(items.size() * MAX_LISTENERS * 2); // countdown on all events
    final List<Queue<Integer>> indexQueues = new ArrayList<>(MAX_LISTENERS);
    final EventSource[] sources = new EventSource[MAX_LISTENERS];
    final AtomicInteger sizeEventsCount = new AtomicInteger(0);

    for (int i = 0; i < MAX_LISTENERS; i++) {
        final int id = i;
        final EventSource es = EventSource.target(itemsTarget.path("events")).named("SOURCE " + id).build();
        sources[id] = es;

        final Queue<Integer> indexes = new ConcurrentLinkedQueue<>();
        indexQueues.add(indexes);

        es.register(inboundEvent -> {
            try {
                if (inboundEvent.getName() == null) {
                    final String data = inboundEvent.readData();
                    LOGGER.info("[-i-] SOURCE " + id + ": Received event id=" + inboundEvent.getId() + " data="
                            + data);
                    indexes.add(items.indexOf(data));
                } else if ("size".equals(inboundEvent.getName())) {
                    sizeEventsCount.incrementAndGet();
                }
            } catch (Exception ex) {
                LOGGER.log(Level.SEVERE, "[-x-] SOURCE " + id + ": Error getting event data.", ex);
                indexes.add(-999);
            } finally {
                latch.countDown();
            }
        });
    }

    try {
        open(sources);

        for (String item : items) {
            postItem(itemsTarget, item);
        }

        assertTrue("Waiting to receive all events has timed out.",
                latch.await(
                        (1000 + MAX_LISTENERS * EventSource.RECONNECT_DEFAULT) * getAsyncTimeoutMultiplier(),
                        TimeUnit.MILLISECONDS));

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

    String postedItems = itemsTarget.request().get(String.class);
    for (String item : items) {
        assertTrue("Item '" + item + "' not stored on server.", postedItems.contains(item));
    }

    int queueId = 0;
    for (Queue<Integer> indexes : indexQueues) {
        for (int i = 0; i < items.size(); i++) {
            assertTrue("Event for '" + items.get(i) + "' not received in queue " + queueId,
                    indexes.contains(i));
        }
        assertEquals("Not received the expected number of events in queue " + queueId, items.size(),
                indexes.size());
        queueId++;
    }

    assertEquals("Number of received 'size' events does not match.", items.size() * MAX_LISTENERS,
            sizeEventsCount.get());
}

From source file:org.glassfish.jersey.examples.sseitemstore.ItemStoreResourceTest.java

/**
 * Test the item addition, addition event broadcasting and item retrieval from {@link ItemStoreResource}.
 *
 * @throws Exception in case of a test failure.
 *///from   w w  w.ja  v a 2s . c  o m
@Test
public void testItemsStore() throws Exception {
    final List<String> items = Collections.unmodifiableList(Arrays.asList("foo", "bar", "baz"));
    final WebTarget itemsTarget = target("items");
    final CountDownLatch latch = new CountDownLatch(items.size() * MAX_LISTENERS * 2); // countdown on all events
    final List<Queue<Integer>> indexQueues = new ArrayList<Queue<Integer>>(MAX_LISTENERS);
    final EventSource[] sources = new EventSource[MAX_LISTENERS];
    final AtomicInteger sizeEventsCount = new AtomicInteger(0);

    for (int i = 0; i < MAX_LISTENERS; i++) {
        final int id = i;
        final EventSource es = EventSource.target(itemsTarget.path("events")).named("SOURCE " + id).build();
        sources[id] = es;

        final Queue<Integer> indexes = new ConcurrentLinkedQueue<Integer>();
        indexQueues.add(indexes);

        es.register(new EventListener() {
            @SuppressWarnings("MagicNumber")
            @Override
            public void onEvent(InboundEvent inboundEvent) {
                try {
                    if (inboundEvent.getName() == null) {
                        final String data = inboundEvent.readData();
                        LOGGER.info("[-i-] SOURCE " + id + ": Received event id=" + inboundEvent.getId()
                                + " data=" + data);
                        indexes.add(items.indexOf(data));
                    } else if ("size".equals(inboundEvent.getName())) {
                        sizeEventsCount.incrementAndGet();
                    }
                } catch (Exception ex) {
                    LOGGER.log(Level.SEVERE, "[-x-] SOURCE " + id + ": Error getting event data.", ex);
                    indexes.add(-999);
                } finally {
                    latch.countDown();
                }
            }
        });
    }

    try {
        open(sources);

        for (String item : items) {
            postItem(itemsTarget, item);
        }

        assertTrue("Waiting to receive all events has timed out.",
                latch.await(
                        (1000 + MAX_LISTENERS * EventSource.RECONNECT_DEFAULT) * getAsyncTimeoutMultiplier(),
                        TimeUnit.MILLISECONDS));

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

    String postedItems = itemsTarget.request().get(String.class);
    for (String item : items) {
        assertTrue("Item '" + item + "' not stored on server.", postedItems.contains(item));
    }

    int queueId = 0;
    for (Queue<Integer> indexes : indexQueues) {
        for (int i = 0; i < items.size(); i++) {
            assertTrue("Event for '" + items.get(i) + "' not received in queue " + queueId,
                    indexes.contains(i));
        }
        assertEquals("Not received the expected number of events in queue " + queueId, items.size(),
                indexes.size());
        queueId++;
    }

    assertEquals("Number of received 'size' events does not match.", items.size() * MAX_LISTENERS,
            sizeEventsCount.get());
}

From source file:de.tudarmstadt.ukp.dkpro.lexsemresource.graph.EntityGraphJGraphT.java

/**
 * Creates the hyponym map, that maps from nodes to their (recursive) number of hyponyms for
 * each node. "recursive" means that the hyponyms of hyponyms are also taken into account.
 *
 * @throws UnsupportedOperationException
 * @throws LexicalSemanticResourceException
 *///from www  .j  av a2s  .  c o m
private Map<String, Integer> getHyponymCountMap() throws LexicalSemanticResourceException {
    // do only create hyponymMap, if it was not already computed
    if (hyponymCountMap != null) {
        return hyponymCountMap;
    }

    // work on the lcc, otherwise this is not going to work
    // EntityGraphJGraphT lcc = this;
    EntityGraphJGraphT lcc = this.getLargestConnectedComponent();
    lcc.removeCycles();
    int nrOfNodes = lcc.getNumberOfNodes();

    File hyponymCountMapSerializedFile = new File(
            getGraphId() + "_" + hyponymCountMapFilename + (lexSemRes.getIsCaseSensitive() ? "-cs" : "-cis"));
    hyponymCountMap = new HashMap<String, Integer>();

    if (hyponymCountMapSerializedFile.exists()) {
        logger.info("Loading saved hyponymyCountMap ...");
        hyponymCountMap = EntityGraphUtils.deserializeMap(hyponymCountMapSerializedFile);
        if (hyponymCountMap.size() != nrOfNodes) {
            throw new LexicalSemanticResourceException(
                    "HyponymCountMap does not contain an entry for each node in the graph."
                            + hyponymCountMap.size() + "/" + nrOfNodes);
        }
        logger.info("Done loading saved hyponymyCountMap");
        return hyponymCountMap;
    }

    hyponymCountMap = new HashMap<String, Integer>();

    // a queue holding the nodes to process
    Queue<String> queue = new LinkedList<String>();

    // In the entity graph a node may have more than one father.
    // Thus, we check whether a node was already visited.
    // Then, it is not expanded again.
    Set<String> visited = new HashSet<String>();

    // initialize the queue with all leaf nodes
    Set<String> leafNodes = new HashSet<String>();
    for (Entity leaf : lcc.getLeaves()) {
        leafNodes.add(leaf.getId());
    }
    queue.addAll(leafNodes);

    logger.info(leafNodes.size() + " leaf nodes.");

    ProgressMeter progress = new ProgressMeter(getNumberOfNodes());
    // while the queue is not empty
    while (!queue.isEmpty()) {
        // remove first element from queue
        String currNodeId = queue.poll();
        Entity currNode = lexSemRes.getEntityById(currNodeId);

        // in some rare cases, getEntityById might fail - so better check for nulls and fail
        // gracefully
        if (currNode == null) {
            visited.add(currNodeId);
            hyponymCountMap.put(currNodeId, 0);
        }

        logger.debug(queue.size());

        if (visited.contains(currNodeId)) {
            continue;
        }

        progress.next();

        if (logger.isDebugEnabled()) {
            logger.debug(progress + " - " + queue.size() + " left in queue");
        } else if (logger.isInfoEnabled() && (progress.getCount() % 100 == 0)) {
            logger.info(progress + " - " + queue.size() + " left in queue");
        }

        Set<Entity> children = lcc.getChildren(currNode);
        Set<String> invalidChildIds = new HashSet<String>();
        int validChildren = 0;
        int sumChildHyponyms = 0;
        boolean invalid = false;
        for (Entity child : children) {
            if (lcc.containsVertex(child)) {
                if (hyponymCountMap.containsKey(child.getId())) {
                    sumChildHyponyms += hyponymCountMap.get(child.getId());
                    validChildren++;
                } else {
                    invalid = true;
                    invalidChildIds.add(child.getId());
                }
            }
        }

        // we cannot use continue directly if invalid as this would continue the inner loop not
        // the outer loop
        if (invalid) {
            // One of the childs is not in the hyponymCountMap yet
            // Re-Enter the node into the queue and continue with next node
            // Also enter all the childs that are not in the queue yet
            queue.add(currNodeId);
            for (String childId : invalidChildIds) {
                if (!visited.contains(childId) && !queue.contains(childId)) {
                    queue.add(childId);
                }
            }
            continue;
        }

        // mark as visited
        visited.add(currNodeId);

        // number of hyponomys of current node is the number of its own hyponyms and the sum of
        // the hyponyms of its children.
        int currNodeHyponomyCount = validChildren + sumChildHyponyms;
        hyponymCountMap.put(currNodeId, currNodeHyponomyCount);

        // add parents of current node to queue
        for (Entity parent : lcc.getParents(currNode)) {
            if (lcc.containsVertex(parent)) {
                queue.add(parent.getId());
            }
        }
    } // while queue not empty

    logger.info(visited.size() + " nodes visited");
    if (visited.size() != nrOfNodes) {
        List<Entity> missed = new ArrayList<Entity>();
        for (Entity e : lcc.getNodes()) {
            if (!visited.contains(e.getId())) {
                missed.add(e);
                System.out.println("Missed: [" + e + "]");
            }
        }

        throw new LexicalSemanticResourceException(
                "Visited only " + visited.size() + " out of " + nrOfNodes + " nodes.");
    }
    if (hyponymCountMap.size() != nrOfNodes) {
        throw new LexicalSemanticResourceException(
                "HyponymCountMap does not contain an entry for each node in the graph." + hyponymCountMap.size()
                        + "/" + nrOfNodes);
    }

    /*
     * As an EntityGraph is a graph rather than a tree, the hyponymCount for top nodes can be
     * greater than the number of nodes in the graph. This is due to the multiple counting of nodes
     * having more than one parent. Thus, we have to scale hyponym counts to fall in
     * [0,NumberOfNodes].
     */
    for (String key : hyponymCountMap.keySet()) {
        if (hyponymCountMap.get(key) > hyponymCountMap.size()) {
            // TODO scaling function is not optimal (to say the least :)
            hyponymCountMap.put(key, (hyponymCountMap.size() - 1));
        }
    }

    logger.info("Computed hyponymCountMap");
    EntityGraphUtils.serializeMap(hyponymCountMap, hyponymCountMapSerializedFile);
    logger.info("Serialized hyponymCountMap");

    return hyponymCountMap;
}

From source file:de.uni_koblenz.jgralab.utilities.rsa.Rsa2Tg.java

/**
 * @param containingGEC//  ww  w. j a  va 2 s.co m
 * @param containedGEC
 * @param workingList
 *            {@link Queue} which contains all elements which are nesting
 *            some element but are not nested in any element
 */
private void insertContainingGECIntoWorkingList(GraphElementClass containingGEC, GraphElementClass containedGEC,
        Queue<GraphElementClass> workingList) {
    if (workingList.contains(containedGEC)) {
        workingList.remove(containedGEC);
    }
    if (!workingList.contains(containingGEC)) {
        workingList.add(containingGEC);
    }
}

From source file:de.uni_koblenz.jgralab.utilities.rsa.Rsa2Tg.java

/**
 * //from w ww  . j a  v  a 2  s  .c  o m
 */
private void createMayBeNestedIn() {
    System.out.println("Create MayBeNestedIn relations ...");
    updateNestedElements();

    // stores the GraphElementClass which have nested elements but are not
    // nested in another GraphElementClass
    Queue<GraphElementClass> workingList = new LinkedList<GraphElementClass>();
    Queue<GraphElementClass> topLevelNestingElements = new LinkedList<GraphElementClass>();

    // all edges have to be treated
    for (EdgeClass ec : sg.getEdgeClassVertices()) {
        workingList.add(ec);
        topLevelNestingElements.add(ec);
    }

    // create the explicitly modeled MayBeNestedIn edges
    for (GraphElement<?, ?, ?, ?> ge : nestedElements.getMarkedElements()) {
        GraphElementClass containingGEC = (GraphElementClass) ge;
        assert nestedElements.getMark(containingGEC) != null;
        assert !nestedElements.getMark(containingGEC).isEmpty();

        for (GraphElementClass containedGEC : nestedElements.getMark(containingGEC)) {
            sg.createMayBeNestedIn(containedGEC, containingGEC);
            insertContainingGECIntoWorkingList(containingGEC, containedGEC, topLevelNestingElements);
        }
    }

    checkAcyclicityOfMayBeNestedIn(topLevelNestingElements);

    // check correctness of explicit modeled MayBeNestedIn edges and create
    // implicit MayBeNestedIn edges during a breadth first search over the
    // GraphElementClasses participating in the MayBeNestedIn tree
    LocalBooleanGraphMarker isImplicitlyNested = new LocalBooleanGraphMarker(sg);
    while (!workingList.isEmpty()) {
        GraphElementClass current = workingList.poll();
        assert current != null;

        if (EdgeClass.class.isInstance(current)) {
            EdgeClass containedEC = (EdgeClass) current;

            // check constraints for explicitly nested EdgeClasses
            for (MayBeNestedIn_nestedElement i : containedEC.getIncidences(MayBeNestedIn_nestedElement.class)) {
                if (!isImplicitlyNested.isMarked(i.getEdge())) {
                    GraphElementClass containingGEC = (GraphElementClass) i.getThat();
                    checkNestingConstraints(containedEC, containingGEC);
                }
            }

            // create implicit MayBeNestedIn edges
            for (GraphElementClass containingGEC : getAllNestingElements(containedEC)) {
                isImplicitlyNested.mark(sg.createMayBeNestedIn(containedEC, containingGEC));
                if (topLevelNestingElements.contains(containedEC)) {
                    topLevelNestingElements.remove(containedEC);
                }
            }
        }

        // insert all nested GraphElementClasses into workingList
        for (MayBeNestedIn_nestingElement i : current.getIncidences(MayBeNestedIn_nestingElement.class)) {
            if (!workingList.contains(i.getThat()) && !isImplicitlyNested.isMarked(i.getEdge())) {
                workingList.add((GraphElementClass) i.getThat());
            }
        }
    }

    deleteDuplicateMayBeNestedIn();

    checkAcyclicityOfMayBeNestedIn(topLevelNestingElements);
}