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(Collection<? extends E> c) 

Source Link

Document

Constructs a deque containing the elements of the specified collection, in the order they are returned by the collection's iterator.

Usage

From source file:com.espertech.esper.epl.spec.PatternStreamSpecRaw.java

private PatternStreamSpecCompiled compileInternal(StatementContext context, Set<String> eventTypeReferences,
        boolean isInsertInto, Collection<Integer> assignedTypeNumberStack, MatchEventSpec tags,
        Set<String> priorAllTags) throws ExprValidationException {
    if (tags == null) {
        tags = new MatchEventSpec();
    }/*  ww  w  .j a v  a  2  s  .  c  o  m*/
    Deque<Integer> subexpressionIdStack = new ArrayDeque<Integer>(assignedTypeNumberStack);
    ExprEvaluatorContext evaluatorContextStmt = new ExprEvaluatorContextStatement(context);
    Stack<EvalFactoryNode> nodeStack = new Stack<EvalFactoryNode>();

    // detemine ordered tags
    Set<EvalFactoryNode> filterFactoryNodes = EvalNodeUtil.recursiveGetChildNodes(evalFactoryNode,
            FilterForFilterFactoryNodes.INSTANCE);
    LinkedHashSet<String> allTagNamesOrdered = new LinkedHashSet<String>();
    if (priorAllTags != null) {
        allTagNamesOrdered.addAll(priorAllTags);
    }
    for (EvalFactoryNode filterNode : filterFactoryNodes) {
        EvalFilterFactoryNode factory = (EvalFilterFactoryNode) filterNode;
        int tagNumber;
        if (factory.getEventAsName() != null) {
            if (!allTagNamesOrdered.contains(factory.getEventAsName())) {
                allTagNamesOrdered.add(factory.getEventAsName());
                tagNumber = allTagNamesOrdered.size() - 1;
            } else {
                tagNumber = findTagNumber(factory.getEventAsName(), allTagNamesOrdered);
            }
            factory.setEventAsTagNumber(tagNumber);
        }
    }

    recursiveCompile(evalFactoryNode, context, evaluatorContextStmt, eventTypeReferences, isInsertInto, tags,
            subexpressionIdStack, nodeStack, allTagNamesOrdered);

    Audit auditPattern = AuditEnum.PATTERN.getAudit(context.getAnnotations());
    Audit auditPatternInstance = AuditEnum.PATTERNINSTANCES.getAudit(context.getAnnotations());
    EvalFactoryNode compiledEvalFactoryNode = evalFactoryNode;
    if (auditPattern != null || auditPatternInstance != null) {
        EvalAuditInstanceCount instanceCount = new EvalAuditInstanceCount();
        compiledEvalFactoryNode = recursiveAddAuditNode(null, auditPattern != null,
                auditPatternInstance != null, evalFactoryNode, evalNodeExpressions, instanceCount);
    }

    return new PatternStreamSpecCompiled(compiledEvalFactoryNode, tags.getTaggedEventTypes(),
            tags.getArrayEventTypes(), allTagNamesOrdered, this.getViewSpecs(), this.getOptionalStreamName(),
            this.getOptions());
}

From source file:hudson.plugins.plot.XMLSeries.java

/***
 * This is a fallback strategy for nodesets that include non numeric content
 * enabling users to create lists by selecting them such that names and
 * values share a common parent. If a node has attributes and is empty that
 * node will be re-enqueued as a parent to its attributes.
 * /*w  w w  .  j  a  va 2  s . c  o  m*/
 * @param buildNumber
 *            the build number
 * 
 * @returns a list of PlotPoints where the label is the last non numeric
 *          text content and the value is the last numeric text content for
 *          each set of nodes under a given parent.
 ***/
private List<PlotPoint> coalesceTextnodesAsLabelsStrategy(NodeList nodeList, int buildNumber) {
    Map<Node, List<Node>> parentNodeMap = new HashMap<Node, List<Node>>();

    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        if (!parentNodeMap.containsKey(node.getParentNode())) {
            parentNodeMap.put(node.getParentNode(), new ArrayList<Node>());
        }
        parentNodeMap.get(node.getParentNode()).add(node);
    }

    List<PlotPoint> retval = new ArrayList<PlotPoint>();
    Queue<Node> parents = new ArrayDeque<Node>(parentNodeMap.keySet());
    while (!parents.isEmpty()) {
        Node parent = parents.poll();
        Double value = null;
        String label = null;

        for (Node child : parentNodeMap.get(parent)) {
            if (null == child.getTextContent() || child.getTextContent().trim().isEmpty()) {
                NamedNodeMap attrmap = child.getAttributes();
                List<Node> attrs = new ArrayList<Node>();
                for (int i = 0; i < attrmap.getLength(); i++) {
                    attrs.add(attrmap.item(i));
                }
                parentNodeMap.put(child, attrs);
                parents.add(child);
            } else if (new Scanner(child.getTextContent().trim()).hasNextDouble()) {
                value = new Scanner(child.getTextContent().trim()).nextDouble();
            } else {
                label = child.getTextContent().trim();
            }
        }
        if ((label != null) && (value != null)) {
            addValueToList(retval, new String(label), String.valueOf(value), buildNumber);
        }
    }
    return retval;
}

From source file:com.joliciel.talismane.parser.ParseConfigurationImpl.java

public ParseConfigurationImpl(ParseConfiguration history) {
    super();/* ww w.  j ava  2 s . c om*/
    ParseConfigurationInternal iHistory = (ParseConfigurationInternal) history;
    this.transitions = new ArrayList<Transition>(history.getTransitions());
    this.dependencies = new TreeSet<DependencyArc>(iHistory.getDependenciesInternal());
    this.posTagSequence = history.getPosTagSequence();
    posTagSequence.prependRoot();
    this.underlyingSolutions.add(this.posTagSequence);
    this.buffer = new ArrayDeque<PosTaggedToken>(history.getBuffer());
    this.stack = new ArrayDeque<PosTaggedToken>(history.getStack());
    this.dependentTransitionMap = new HashMap<PosTaggedToken, Transition>(
            ((ParseConfigurationInternal) history).getDependentTransitionMap());

    this.decisions = new ArrayList<Decision<Transition>>(history.getDecisions());
    this.lastProbApplied = (((ParseConfigurationInternal) history).getLastProbApplied());
    this.scoringStrategy = history.getScoringStrategy();
}

From source file:edu.odu.cs.cs350.yellow1.file.FileMover.java

/**
 * Retrieve files in the target directory only after setup return true
 *//*from  w  w w  .j  av a  2 s .c  om*/
public void pullFiles() {
    moveFiles = new ArrayDeque<File>(Arrays.asList(origin.listFiles(ff)));
    System.out.println("Pulling files");
}

From source file:com.offbynull.peernetic.playground.chorddht.model.SuccessorTable.java

/**
 * Updates this successor table so that the immediate successor is {@code successor} and the successors after it are {@code table}. If
 * {@code table} contains the base pointer in it, all pointers including and after the base pointer won't be added. If {@code table}'s
 * size exceeds the number of bits in base pointer's id, it'll be trimmed so that it doesn't exceed. The pointers in {@code table} must
 * be sorted. The point at which {@code table} loops around our base id is the point that it'll be trimmed.
 * @param successor immediate successor//from  w  w  w.j  a  va2  s .  c om
 * @param table successors after {@code successor}
 * @throws NullPointerException if any arguments are {@code null} or contain {@code null}
 * @throws IllegalArgumentException if {@code successor}'s id has a different limit bit size than the base pointer's id, or if the ids
 * of any of the pointers in {@code table} have a different limit bit size than the base pointer's id
 */
public void update(Pointer successor, List<Pointer> table) {
    Validate.notNull(successor);
    Validate.noNullElements(table);

    Id baseId = basePtr.getId();
    Id successorId = successor.getId();

    Validate.isTrue(IdUtils.getBitLength(successorId) == limit);

    if (table.size() > limit) {
        table = table.subList(0, limit);
    }

    Id lastId = successor.getId();
    int lastTableIdx = -1;
    int idx = 0;
    for (Pointer ptrSuccessor : table) {
        Id ptrSuccessorId = ptrSuccessor.getId();

        Validate.isTrue(IdUtils.getBitLength(ptrSuccessorId) == limit);

        if (baseId.equals(ptrSuccessorId)) {
            lastTableIdx = idx;
            break;
        }

        if (Id.comparePosition(baseId, ptrSuccessorId, lastId) <= 0) {
            lastTableIdx = idx;
            break;
        }

        lastId = ptrSuccessor.getId();

        idx++;
    }

    if (lastTableIdx != -1) {
        table = table.subList(0, lastTableIdx);
    }

    int len = table.size() + 1;
    ArrayDeque<Pointer> newTable = new ArrayDeque<>(len);

    newTable.add(successor);
    table.forEach(x -> {
        Id id = x.getId();
        if (id.equals(baseId)) {
            newTable.add(new InternalPointer(id)); // if referencing self, use internalpointer
        } else {
            newTable.add(x);
        }
    });

    this.table = newTable;
}

From source file:org.apache.hadoop.hbase.thrift.TestMutationWriteToWAL.java

@Test
public void testMutationWriteToWAL() throws Exception {
    HBaseTestingUtility.setThreadNameFromMethod();
    final Configuration conf = TEST_UTIL.getConfiguration();
    FileSystem fs = FileSystem.get(conf);
    List<String> expectedLogEntries = new ArrayList<String>();

    try {//from ww w .jav  a2 s. co m
        Hbase.Client client = createClient();
        client.createTable(HTestConst.DEFAULT_TABLE_BYTE_BUF, HTestConst.DEFAULT_COLUMN_DESC_LIST);
        int expectedEntriesForRow[] = new int[NUM_ROWS];
        for (int i = NUM_ROWS - 1; i >= 0; --i) {
            final String row = getRow(i);
            List<Mutation> mutations = new ArrayList<Mutation>();

            // writeToWAL cannot depend on column, only on the row
            boolean writeToWAL = i % 3 == 0;

            for (int j = 0; j < NUM_COLS_PER_ROW; ++j) {
                final String qual = getCol(j);

                boolean isDelete = shouldDelete(i, j);
                if (!isDelete) {
                    expectedEntriesForRow[i]++;
                }

                final String value = isDelete ? "" : getValue(i, j);

                Mutation m = new Mutation(false,
                        ByteBuffer.wrap(Bytes.toBytes(HTestConst.DEFAULT_CF_STR + ":" + qual)),
                        ByteBuffer.wrap(Bytes.toBytes(value)), writeToWAL, HConstants.LATEST_TIMESTAMP);
                m.isDelete = isDelete;

                mutations.add(m);
                if (writeToWAL) {
                    expectedLogEntries.add(row + "," + qual + "," + value + "," + m.isDelete);
                }
            }
            final ByteBuffer rowBuf = ByteBuffer.wrap(Bytes.toBytes(row));
            // Exercise both APIs.
            if (i % 2 == 0) {
                client.mutateRow(HTestConst.DEFAULT_TABLE_BYTE_BUF, rowBuf, mutations, null, null);
            } else {
                List<BatchMutation> rowBatches = new ArrayList<BatchMutation>();
                BatchMutation bm = new BatchMutation(rowBuf, mutations);
                rowBatches.add(bm);
                client.mutateRows(HTestConst.DEFAULT_TABLE_BYTE_BUF, rowBatches, null, null);
            }
        }
        client.disableTable(HTestConst.DEFAULT_TABLE_BYTE_BUF);
        client.enableTable(HTestConst.DEFAULT_TABLE_BYTE_BUF);

        // Check that all the data is there
        for (int i = 0; i < NUM_ROWS; ++i) {
            final String row = getRow(i);
            List<TRowResult> results = client.getRow(HTestConst.DEFAULT_TABLE_BYTE_BUF,
                    ByteBuffer.wrap(Bytes.toBytes(row)), null);
            TRowResult result = results.get(0);
            assertEquals("No results found for row " + row, expectedEntriesForRow[i], result.getColumnsSize());
            Map<ByteBuffer, TCell> sortedColumns = new TreeMap<ByteBuffer, TCell>(result.getColumns());
            int j = -1;
            for (Map.Entry<ByteBuffer, TCell> entry : sortedColumns.entrySet()) {
                ++j;
                while (shouldDelete(i, j)) {
                    ++j;
                }
                assertEquals(HTestConst.DEFAULT_CF_STR + ":" + getCol(j),
                        Bytes.toStringBinaryRemaining(entry.getKey()));
                assertEquals(getValue(i, j), Bytes.toStringBinary(entry.getValue().getValue()));
            }
        }
    } finally {
        closeClientSockets();
    }

    TEST_UTIL.shutdownMiniHBaseCluster();

    final Path baseDir = new Path(conf.get(HConstants.HBASE_DIR));
    final Path oldLogDir = new Path(baseDir, HConstants.HREGION_OLDLOGDIR_NAME);
    int nLogFilesRead = 0;
    List<String> actualLogEntries = new ArrayList<String>();
    ArrayDeque<FileStatus> checkQueue = new ArrayDeque<FileStatus>(
            java.util.Arrays.asList(fs.listStatus(oldLogDir)));
    while (!checkQueue.isEmpty()) {
        FileStatus logFile = checkQueue.pop();
        if (logFile.isDir()) {
            checkQueue.addAll(java.util.Arrays.asList(fs.listStatus(logFile.getPath())));
            continue;
        }
        HLog.Reader r = HLog.getReader(fs, logFile.getPath(), conf);
        LOG.info("Reading HLog: " + logFile.getPath());
        HLog.Entry entry = null;
        while ((entry = r.next(entry)) != null) {
            if (!Bytes.equals(entry.getKey().getTablename(), HTestConst.DEFAULT_TABLE_BYTES)) {
                continue;
            }
            for (KeyValue kv : entry.getEdit().getKeyValues()) {
                if (Bytes.equals(kv.getRow(), HLog.METAROW)) {
                    continue;
                }
                actualLogEntries.add(Bytes.toStringBinary(kv.getRow()) + ","
                        + Bytes.toStringBinary(kv.getQualifier()) + "," + Bytes.toStringBinary(kv.getValue())
                        + "," + (kv.getType() == KeyValue.Type.DeleteColumn.getCode()));
            }
        }
        r.close();
        ++nLogFilesRead;
    }
    assertTrue(nLogFilesRead > 0);
    Collections.sort(expectedLogEntries);
    Collections.sort(actualLogEntries);
    LOG.info("Expected log entries: " + expectedLogEntries.size() + ", actual log entries: "
            + actualLogEntries.size());
    assertEquals(expectedLogEntries.toString(), actualLogEntries.toString());
}

From source file:org.apache.htrace.impl.HTracedRESTReceiver.java

/**
 * Constructor.//from ww  w . jav a  2 s  .c om
 * You must call {@link #close()} post construction when done.
 * @param conf
 * @throws Exception
 */
public HTracedRESTReceiver(final HTraceConfiguration conf) throws Exception {
    int connTimeout = conf.getInt(CLIENT_CONNECT_TIMEOUT_MS_KEY, CLIENT_CONNECT_TIMEOUT_MS_DEFAULT);
    int idleTimeout = conf.getInt(CLIENT_IDLE_TIMEOUT_MS_KEY, CLIENT_IDLE_TIMEOUT_MS_DEFAULT);
    this.httpClient = createHttpClient(connTimeout, idleTimeout);
    this.capacity = conf.getInt(CLIENT_REST_QUEUE_CAPACITY_KEY, CLIENT_REST_QUEUE_CAPACITY_DEFAULT);
    this.spans = new ArrayDeque<Span>(capacity);
    // Build up the writeSpans URL.
    URL restServer = new URL(conf.get(HTRACED_REST_URL_KEY, HTRACED_REST_URL_DEFAULT));
    URL url = new URL(restServer.getProtocol(), restServer.getHost(), restServer.getPort(), "/writeSpans");
    this.url = url.toString();
    // Period at which we run the background thread that does the REST POST to htraced.
    int periodInMs = conf.getInt(CLIENT_REST_PERIOD_MS_KEY, CLIENT_REST_PERIOD_MS_DEFAULT);
    // Maximum spans to send in one go
    this.maxToSendAtATime = conf.getInt(CLIENT_REST_MAX_SPANS_AT_A_TIME_KEY,
            CLIENT_REST_MAX_SPANS_AT_A_TIME_DEFAULT);
    // Start up the httpclient.
    this.httpClient.start();
    // Start the background thread.
    this.postSpans = new PostSpans(periodInMs);
    this.postSpansThread = new Thread(postSpans);
    this.postSpansThread.setDaemon(true);
    this.postSpansThread.setName("PostSpans");
    this.postSpansThread.start();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Created new HTracedRESTReceiver with connTimeout=" + connTimeout + ", idleTimeout = "
                + idleTimeout + ", capacity=" + capacity + ", url=" + url + ", periodInMs=" + periodInMs
                + ", maxToSendAtATime=" + maxToSendAtATime);
    }
}

From source file:com.google.gwt.emultest.java.util.ArrayDequeTest.java

public void testFailFastIterator() {
    ArrayDeque<Object> deque = new ArrayDeque<>(asList(getFullNonNullElements()));
    Iterator<Object> it = deque.iterator();
    it.next();//  w w  w.  j a v a 2  s.  c o m
    deque.removeFirst();
    try {
        it.next();
    } catch (ConcurrentModificationException e) {
        fail();
    }
    deque.removeLast();
    try {
        it.next();
        fail();
    } catch (ConcurrentModificationException expected) {
    }

    deque = new ArrayDeque<>(asList(getFullNonNullElements()));
    it = deque.iterator();
    it.next();
    deque.clear();
    try {
        it.next();
        fail();
    } catch (ConcurrentModificationException expected) {
    }

    deque = new ArrayDeque<>(asList(getFullNonNullElements()));
    it = deque.iterator();
    it.next();
    deque.addFirst(new Object());
    try {
        it.next();
    } catch (ConcurrentModificationException e) {
        fail();
    }
    deque.addLast(new Object());
    try {
        it.next();
        fail();
    } catch (ConcurrentModificationException expected) {
    }

    deque = new ArrayDeque<>(asList(getFullNonNullElements()));
    it = deque.iterator();
    it.next();
    it.next();
    deque.removeFirst();
    try {
        it.remove();
    } catch (ConcurrentModificationException e) {
        fail();
    }

    deque = new ArrayDeque<>(asList(getFullNonNullElements()));
    it = deque.iterator();
    it.next();
    it.next();
    deque.removeFirst();
    deque.removeFirst();
    try {
        it.remove();
        fail();
    } catch (ConcurrentModificationException expected) {
    }
}

From source file:org.apache.hadoop.hdfs.hoss.ds.IntHashMap.java

private void initCache(final int size) {
    cache = new ArrayDeque<IntEntry<V>>(size);
}

From source file:com.google.gwt.emultest.java.util.ArrayDequeTest.java

public void testFailFastDescendingIterator() {
    ArrayDeque<Object> deque = new ArrayDeque<>(asList(getFullNonNullElements()));
    Iterator<Object> it = deque.descendingIterator();
    it.next();//ww w  . j  a  v  a2s . c o m
    deque.removeLast();
    try {
        it.next();
    } catch (ConcurrentModificationException e) {
        fail();
    }
    deque.removeFirst();
    try {
        it.next();
        fail();
    } catch (ConcurrentModificationException expected) {
    }

    deque = new ArrayDeque<>(asList(getFullNonNullElements()));
    it = deque.descendingIterator();
    it.next();
    deque.clear();
    try {
        it.next();
        fail();
    } catch (ConcurrentModificationException expected) {
    }

    deque = new ArrayDeque<>(asList(getFullNonNullElements()));
    it = deque.descendingIterator();
    it.next();
    deque.addLast(new Object());
    try {
        it.next();
    } catch (ConcurrentModificationException e) {
        fail();
    }
    deque.addFirst(new Object());
    try {
        it.next();
        fail();
    } catch (ConcurrentModificationException expected) {
    }

    deque = new ArrayDeque<>(asList(getFullNonNullElements()));
    it = deque.descendingIterator();
    it.next();
    it.next();
    deque.removeLast();
    try {
        it.remove();
    } catch (ConcurrentModificationException e) {
        fail();
    }

    deque = new ArrayDeque<>(asList(getFullNonNullElements()));
    it = deque.descendingIterator();
    it.next();
    it.next();
    deque.removeLast();
    deque.removeLast();
    try {
        it.remove();
        fail();
    } catch (ConcurrentModificationException expected) {
    }
}