Example usage for java.util ArrayDeque ArrayDeque

List of usage examples for java.util ArrayDeque ArrayDeque

Introduction

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

Prototype

public ArrayDeque() 

Source Link

Document

Constructs an empty array deque with an initial capacity sufficient to hold 16 elements.

Usage

From source file:io.undertow.server.handlers.proxy.LoadBalancingProxyHTTP2TestCase.java

@Test
public void testHttp2ClientMultipleStreamsThreadSafety()
        throws IOException, URISyntaxException, ExecutionException, InterruptedException, TimeoutException {
    //not actually a proxy test
    //but convent to put it here
    UndertowXnioSsl ssl = new UndertowXnioSsl(DefaultServer.getWorker().getXnio(), OptionMap.EMPTY,
            DefaultServer.SSL_BUFFER_POOL, DefaultServer.createClientSslContext());
    final UndertowClient client = UndertowClient.getInstance();
    final ClientConnection connection = client.connect(
            new URI("https", null, DefaultServer.getHostAddress(), DefaultServer.getHostPort() + 1, "/", null,
                    null),//from w ww.j  ava2s .  c o m
            DefaultServer.getWorker(), ssl, DefaultServer.getBufferPool(),
            OptionMap.create(UndertowOptions.ENABLE_HTTP2, true)).get();
    final ExecutorService service = Executors.newFixedThreadPool(10);
    try {
        Deque<FutureResult<String>> futures = new ArrayDeque<>();
        for (int i = 0; i < 100; ++i) {
            final FutureResult<String> future = new FutureResult<>();
            futures.add(future);
            service.submit(new Callable<String>() {

                @Override
                public String call() throws Exception {
                    ClientRequest cr = new ClientRequest().setMethod(Methods.GET).setPath("/path")
                            .setProtocol(Protocols.HTTP_1_1);
                    connection.sendRequest(cr, new ClientCallback<ClientExchange>() {
                        @Override
                        public void completed(ClientExchange result) {
                            result.setResponseListener(new ClientCallback<ClientExchange>() {
                                @Override
                                public void completed(ClientExchange result) {
                                    new StringReadChannelListener(DefaultServer.getBufferPool()) {
                                        @Override
                                        protected void stringDone(String string) {
                                            future.setResult(string);
                                        }

                                        @Override
                                        protected void error(IOException e) {
                                            future.setException(e);
                                        }
                                    }.setup(result.getResponseChannel());
                                }

                                @Override
                                public void failed(IOException e) {
                                    future.setException(e);
                                }
                            });
                        }

                        @Override
                        public void failed(IOException e) {
                            future.setException(e);
                        }
                    });
                    return null;
                }
            });
        }
        while (!futures.isEmpty()) {
            FutureResult<String> future = futures.poll();
            Assert.assertNotEquals(IoFuture.Status.WAITING,
                    future.getIoFuture().awaitInterruptibly(10, TimeUnit.SECONDS));
            Assert.assertEquals("/path", future.getIoFuture().get());
        }
    } finally {
        service.shutdownNow();
    }
}

From source file:com.tussle.script.StackedBindings.java

public void putOver(String key, Object value) {
    if (bindingStack.peek().containsKey(key)) {
        Object fromStackEntry = bindingStack.peek().put(key, value);
        Object fromMapEntry = bindingMap.get(key).pop();
        bindingMap.get(key).push(value);
        assert fromStackEntry == fromMapEntry;
    } else {/*  ww w. ja v a 2  s . c o  m*/
        bindingStack.peek().put(key, value);
        if (!bindingMap.containsKey(key))
            bindingMap.put(key, new ArrayDeque<>());
        bindingMap.get(key).push(value);
    }
}

From source file:stroom.util.StreamGrepTool.java

private void processFile(final StreamStore streamStore, final long streamId, final String match) {
    try {//from w w w. ja v a2  s.c o m
        final StreamSource streamSource = streamStore.openStreamSource(streamId);
        if (streamSource != null) {
            final InputStream inputStream = streamSource.getInputStream();

            // Build up 2 buffers so we can output the content either side
            // of
            // the matching line
            final ArrayDeque<String> preBuffer = new ArrayDeque<>();
            final ArrayDeque<String> postBuffer = new ArrayDeque<>();

            final LineNumberReader lineNumberReader = new LineNumberReader(
                    new InputStreamReader(inputStream, StreamUtil.DEFAULT_CHARSET));

            String aline = null;
            while ((aline = lineNumberReader.readLine()) != null) {
                String lines[] = new String[] { aline };
                if (addLineBreak != null) {
                    lines = aline.split(addLineBreak);

                }

                for (final String line : lines) {
                    if (match == null) {
                        System.out.println(lineNumberReader.getLineNumber() + ":" + line);
                    } else {
                        postBuffer.add(lineNumberReader.getLineNumber() + ":" + line);

                        if (postBuffer.size() > 5) {
                            final String searchLine = postBuffer.pop();

                            checkMatch(match, preBuffer, postBuffer, searchLine);

                            preBuffer.add(searchLine);

                            if (preBuffer.size() > 5) {
                                preBuffer.pop();
                            }
                        }
                    }
                }

            }

            // Look at the end
            while (postBuffer.size() > 0) {
                final String searchLine = postBuffer.pop();

                checkMatch(match, preBuffer, postBuffer, searchLine);

                preBuffer.add(searchLine);

                if (preBuffer.size() > 5) {
                    preBuffer.pop();
                }
            }

            inputStream.close();
            streamStore.closeStreamSource(streamSource);
        }
    } catch (final Exception ex) {
        ex.printStackTrace();
    }

}

From source file:com.restswitch.controlpanel.MainActivity.java

private TimingStats getTimingStats(String devid, int ms, int valcnt) {
    if (valcnt < 5)
        valcnt = 5;/*from www  . jav a  2 s  . c o  m*/

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    //                   devid1_times
    String key = (devid + "_times");
    String jsonData = prefs.getString(key, "");
    JSONArray data = null;
    try {
        data = new JSONArray(jsonData);
    } catch (Exception ex) {
        data = new JSONArray();
    }
    data.put(ms);

    // examine the last 'valcnt' values
    int minms = 8000;
    int maxms = 0;
    int totalms = 0;
    int len = 0;
    ArrayDeque<Integer> newData = new ArrayDeque<>();
    for (int i = data.length() - 1; i >= 0; --i) {
        int val = 0;
        try {
            val = data.getInt(i);
        } catch (Exception ex) {
            continue;
        }

        if (val > 7) { // 8ms sanity
            if (val > maxms)
                maxms = val;
            if (val < minms)
                minms = val;
            totalms += val;
            newData.addFirst(val);
            ++len;
            if (len >= valcnt)
                break;
        }
    }

    SharedPreferences.Editor prefsEdit = prefs.edit();
    try {
        JSONArray outJson = new JSONArray(newData);
        prefsEdit.putString(key, outJson.toString());
        //alertInfo(outJson.toString());
    } catch (Exception ex) {
        prefsEdit.remove(key);
    }
    prefsEdit.apply();

    int avgms = (len == 0) ? 0 : (totalms / len);

    TimingStats stats = new TimingStats(ms, minms, avgms, maxms);

    return (stats);
}

From source file:org.grouplens.grapht.solver.DependencySolver.java

/**
 * Update the dependency graph to include the given desire. An edge from the
 * root node to the desire's resolved satisfaction will exist after this is
 * finished./*from  ww  w  . j a  v  a 2  s.  c  o m*/
 * 
 * @param desire The desire to include in the graph
 */
public synchronized void resolve(Desire desire) throws ResolutionException {
    logger.info("Resolving desire: {}", desire);

    Queue<Deferral> deferralQueue = new ArrayDeque<Deferral>();

    // before any deferred nodes are processed, we use a synthetic root
    // and null original desire since nothing produced this root
    deferralQueue.add(new Deferral(rootNode(), initialContext()));

    while (!deferralQueue.isEmpty()) {
        Deferral current = deferralQueue.poll();
        DAGNode<Component, Dependency> parent = current.node;
        // deferred nodes are either root - depless - or having deferred dependencies
        assert parent.getOutgoingEdges().isEmpty();

        if (current.node.getLabel().equals(ROOT_SATISFACTION)) {
            Pair<DAGNode<Component, Dependency>, Dependency> rootNode = resolveFully(desire, current.context,
                    deferralQueue);
            // add this to the global graph
            graph = DAGNode.copyBuilder(graph).addEdge(mergePool.merge(rootNode.getLeft()), rootNode.getRight())
                    .build();
        } else if (graph.getReachableNodes().contains(parent)) {
            // the node needs to be re-scanned.  This means that it was not consolidated by
            // a previous merge operation.  This branch only arises with provider injection.
            Satisfaction sat = parent.getLabel().getSatisfaction();
            for (Desire d : sat.getDependencies()) {
                logger.debug("Attempting to resolve deferred dependency {} of {}", d, sat);
                // resolve the dependency
                Pair<DAGNode<Component, Dependency>, Dependency> result = resolveFully(d, current.context,
                        deferralQueue);
                // merge it in
                DAGNode<Component, Dependency> merged = mergePool.merge(result.getLeft());
                // now see if there's a real cycle
                if (merged.getReachableNodes().contains(parent)) {
                    // parent node is referenced from merged, we have a circle!
                    // that means we need a back edge
                    backEdges.put(parent, DAGEdge.create(parent, merged, result.getRight()));
                } else {
                    // an edge from parent to merged does not add a cycle
                    // we have to update graph right away so it's available to merge the next
                    // dependency
                    DAGNode<Component, Dependency> newP = DAGNode.copyBuilder(parent)
                            .addEdge(merged, result.getRight()).build();
                    replaceNode(parent, newP);
                    parent = newP;
                }
            }
        } else {
            // node unreachable - it's a leftover or unneeded deferral
            logger.debug("node {} not in graph, ignoring", parent);
        }
    }
}

From source file:ca.nines.ise.writer.RTFWriter.java

@Override
public void render(DOM dom, Annotation annotation) throws DocumentException, IOException {
    this.preprocess(dom, annotation);

    fontStack = new ArrayDeque<>();
    fontStack.push(FontFactory.getFont("Times New Roman", 12, Color.BLACK));
    Font font;//from  ww w. j a  v  a2s  . c o  m

    boolean inSP = false; // in speech prefix
    boolean inSD = false; // in stage direction
    boolean inDQ = false; // in a double quote
    boolean inS = false; // in a speech
    boolean inHW = false;
    char part = 'i';

    String mode = "verse";

    doc.open();
    startParagraph();

    for (Node n : dom) {
        switch (n.type()) {
        case ABBR:
            break;
        case CHAR:
            addChunk(n.unicode());
            break;
        case EMPTY:
            switch (n.getName()) {
            case "FNLOC":
                EmptyNode fnloc = (EmptyNode) n;
                Note note = annotation.get(Integer.parseInt(fnloc.getAttribute("ref")) - 1);
                if (!note.hasNoteLevel("1")) {
                    break;
                }
                this.footnote(note);
                break;
            case "TLN":
            case "L":
                if (mode.equals("prose")) {
                    break;
                }
                if (inS) {
                    startParagraph(p2);
                } else {
                    startParagraph(p1);
                }
                EmptyNode en = (EmptyNode) n;
                if (en.hasAttribute("part")) {
                    part = en.getAttribute("part").charAt(0);
                } else {
                    part = 'i';
                }
                break;
            }
            break;
        case END:
            switch (n.getName()) {
            case "FOREIGN":
                fontStack.pop();
                break;
            case "HW":
                inHW = false;
                break;
            case "I":
                fontStack.pop();
                break;
            case "LD":
                startParagraph();
                break;
            case "S":
                inS = false;
                break;
            case "SD":
                fontStack.pop();
                inSD = false;
                break;
            case "SP":
                addChunk(". ");
                inSP = false;
                break;
            }
            break;
        case START:
            switch (n.getName()) {
            case "FOREIGN":
                font = new Font(fontStack.getFirst());
                font.setStyle(Font.ITALIC);
                fontStack.push(font);
                break;
            case "HW":
                inHW = true;
                break;
            case "I":
                font = new Font(fontStack.getFirst());
                font.setStyle(Font.ITALIC);
                fontStack.push(font);
                break;
            case "LD":
                startParagraph(ld);
                break;
            case "MODE":
                mode = ((TagNode) n).getAttribute("t");
                break;
            case "S":
                if (mode.equals("prose")) {
                    startParagraph(prose);
                }
                inS = true;
                break;
            case "SD":
                font = new Font(fontStack.getFirst());
                font.setStyle(Font.ITALIC);
                StartNode start = (StartNode) n;
                if (start.hasAttribute("t") && start.getAttribute("t").contains("exit")) {
                    startParagraph(exit);
                }
                if (start.hasAttribute("t") && start.getAttribute("t").contains("optional")) {
                    font.setColor(Color.GRAY);
                }
                fontStack.push(font);
                inSD = true;
                break;
            case "SP":
                inSP = true;
                break;
            }
            break;
        case TEXT:
            String txt = n.getText();
            txt = txt.replace("--", "\u2014");
            txt = txt.replace("\n", "");

            if (inSP) {
                addChunk(txt.toUpperCase());
                break;
            }

            if (inHW) {
                txt = txt.replaceFirst("[(]", "");
                inHW = false;
            }

            if (inSD) {
                // DOES NOT MATCH AFTER A TAG.
                if ((txt.indexOf('[') >= 0) || (txt.indexOf(']') >= 0)) {
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < txt.length(); i++) {
                        char c = txt.charAt(i);
                        if (c == '[' || c == ']') {
                            if (sb.length() > 0) {
                                addChunk(sb.toString());
                                sb = new StringBuilder();
                            }
                            addDirect("{\\i0" + String.valueOf(c) + "}");
                        } else {
                            sb.append(c);
                        }
                    }
                    if (sb.length() > 0) {
                        addChunk(sb.toString());
                    }
                    break;
                } else {
                    addChunk(txt);
                    break;
                }
            }

            if (part != 'i' && inS) {
                RtfTab tab = null;
                String tabStr = "";
                if (part == 'm') {
                    tab = new RtfTab(100, RtfTab.TAB_LEFT_ALIGN);
                    tabStr = "\t";
                }
                if (part == 'f') {
                    tab = new RtfTab(200, RtfTab.TAB_LEFT_ALIGN);
                    tabStr = "\t\t";
                }
                if (tab != null) {
                    p.add(tab);
                    addChunk(tabStr);
                }
                part = 'i'; // ensure it's only done once for m or f.
            }

            // fix quotation marks.
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < txt.length(); i++) {
                char c = txt.charAt(i);
                switch (c) {
                case '"':
                    if (inDQ) {
                        // typographer's end quote.
                        sb.append("\u201D");
                        inDQ = false;
                    } else {
                        // typographer's start quote.
                        sb.append("\u201C");
                        inDQ = true;
                    }
                    break;
                case '\'':
                    sb.append("\u2019"); // appostrophe
                    break;
                default:
                    sb.append(c);
                }
            }
            addChunk(sb.toString());
            break;
        }
    }

    startParagraph();

    doc.close();
}

From source file:org.openscore.lang.ExecutionRuntimeServices.java

/**
 *  add event - for score to fire/*  www  . ja  v a  2 s  . c  o m*/
 * @param eventType  - string which is the key you can listen to
 * @param eventData  - the event data
 */
public void addEvent(String eventType, Serializable eventData) {
    @SuppressWarnings("unchecked")
    Queue<ScoreEvent> eventsQueue = getFromMap(SCORE_EVENTS_QUEUE);
    if (eventsQueue == null) {
        eventsQueue = new ArrayDeque<>();
        contextMap.put(SCORE_EVENTS_QUEUE, (ArrayDeque) eventsQueue);
    }
    eventsQueue.add(new ScoreEvent(eventType, eventData));
}

From source file:eu.stratosphere.nephele.taskmanager.runtime.RuntimeInputChannelContext.java

@Override
public void destroy() {
    final Queue<Buffer> buffersToRecycle = new ArrayDeque<Buffer>();

    synchronized (this.queuedEnvelopes) {
        this.destroyCalled = true;

        while (!this.queuedEnvelopes.isEmpty()) {
            final TransferEnvelope envelope = this.queuedEnvelopes.poll();
            if (envelope.getBuffer() != null) {
                buffersToRecycle.add(envelope.getBuffer());
            }/*from w w  w.  j a v  a 2  s.c  om*/
        }
    }

    while (!buffersToRecycle.isEmpty()) {
        buffersToRecycle.poll().recycleBuffer();
    }
}

From source file:com.grepcurl.random.ObjectGenerator.java

protected <T, E> Collection<T> randomCollection(Type elementType, Class<E> collectionType,
        SetterOverrides setterOverrides, int count, Deque<Object> objectStack) {
    Validate.isTrue(count >= 0);//from w w w . j  a  v a  2  s . com
    Validate.notNull(elementType);
    Validate.notNull(collectionType);
    if (verbose) {
        log(String.format("generating %s<%s> (%d)", collectionType, elementType, count));
    }
    Collection<T> collection;
    if (collectionType.equals(List.class)) {
        collection = new ArrayList<>();
    } else if (collectionType.equals(Set.class)) {
        collection = new HashSet<>();
    } else if (collectionType.equals(Deque.class)) {
        collection = new ArrayDeque<>();
    } else if (collectionType.equals(Collection.class)) {
        collection = new ArrayList<>();
    } else {
        throw new IllegalArgumentException(
                "Don't know how to generate a random collection of type: " + collectionType.getName());
    }
    for (int i = 0; i < count; i++) {
        collection.add((T) _process(elementType, setterOverrides, objectStack));
    }
    return collection;
}

From source file:io.anserini.index.IndexWebCollection.java

static Deque<Path> discoverWarcFiles(Path p, final String suffix) {

    final Deque<Path> stack = new ArrayDeque<>();

    FileVisitor<Path> fv = new SimpleFileVisitor<Path>() {

        @Override//from   w  ww . j  a  va 2  s  .c  om
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {

            Path name = file.getFileName();
            if (name != null && name.toString().endsWith(suffix))
                stack.add(file);
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
            if ("OtherData".equals(dir.getFileName().toString())) {
                LOG.info("Skipping: " + dir);
                return FileVisitResult.SKIP_SUBTREE;
            }
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Path file, IOException ioe) {
            LOG.error("Visiting failed for " + file.toString(), ioe);
            return FileVisitResult.SKIP_SUBTREE;
        }
    };

    try {
        Files.walkFileTree(p, fv);
    } catch (IOException e) {
        LOG.error("IOException during file visiting", e);
    }
    return stack;
}