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:org.trend.hgraph.util.test.GenerateTestData.java

private void doGenerateTestData() throws IOException {
    HTable vertexTable = null;/* ww  w .  j  av a 2  s.c  o m*/
    HTable edgeTable = null;
    Put put = null;
    long vIdx = 0;
    byte[] parentVertexKey = null;
    StopWatch timer = new StopWatch();
    timer.start();
    try {
        vertexTable = new HTable(this.getConf(), this.vertexTable);
        vertexTable.setAutoFlush(false);
        edgeTable = new HTable(this.getConf(), this.edgeTable);
        edgeTable.setAutoFlush(false);

        Queue<byte[]> parentVertexKeysQueue = new ArrayDeque<byte[]>();
        int tmpEdgeCountPerVertex = 0;
        int edgeAcctCount = 0;
        Properties.Pair<Integer, Integer> pair = null;
        for (int rowCount = 0; rowCount < this.vertexCount; rowCount++) {
            put = generateVertexPut();
            vertexTable.put(put);
            parentVertexKeysQueue.offer(put.getRow());

            if (rowCount > 0) {
                vIdx = rowCount % tmpEdgeCountPerVertex;
                if (vIdx == 0) {
                    parentVertexKey = parentVertexKeysQueue.poll();

                    edgeAcctCount++;
                    if (this.isDistributionMode && !this.isFirstVertices[pair.key]
                            && edgeAcctCount == tmpEdgeCountPerVertex) {
                        this.addFirstVertex(Bytes.toString(parentVertexKey));
                        this.isFirstVertices[pair.key] = true;
                    }
                    pair = this.determineEdgeCountPerVertex(rowCount);
                    tmpEdgeCountPerVertex = pair.value;
                    edgeAcctCount = 0;
                } else if (vIdx > 0) {
                    edgeAcctCount++;
                    parentVertexKey = parentVertexKeysQueue.peek();
                } else {
                    throw new RuntimeException("vIdex:" + vIdx + " shall always not small than 0");
                }

                put = generateEdgePut(rowCount, parentVertexKey, put.getRow());
                edgeTable.put(put);
            } else {
                pair = this.determineEdgeCountPerVertex(rowCount);
                tmpEdgeCountPerVertex = pair.value;
                if (!this.isDistributionMode)
                    this.addFirstVertex(Bytes.toString(put.getRow()));
            }
        }
        vertexTable.flushCommits();
        edgeTable.flushCommits();
    } catch (IOException e) {
        LOG.error("doGenerateTestData failed", e);
        throw e;
    } finally {
        if (null != vertexTable)
            vertexTable.close();
        if (null != edgeTable)
            edgeTable.close();
        timer.stop();
        LOG.info("Time elapsed:" + timer.toString() + ", " + timer.getTime() + " for pushing "
                + this.vertexCount + " vertices test data to HBase");
        LOG.info("first vertices id:" + this.firstVertices);
    }
}

From source file:com.heliosdecompiler.helios.gui.controller.FileTreeController.java

public void updateTree(List<TreeNode> add, List<TreeNode> remove) {
    Set<TreeItem<TreeNode>> updated = new HashSet<>();

    ArrayDeque<TreeNode> queue = new ArrayDeque<>();
    queue.addAll(add);//from  w  w  w  .j av a  2 s . co m

    while (!queue.isEmpty()) {
        TreeNode thisNode = queue.pop();

        TreeItem<TreeNode> parent;

        if (thisNode.getParent() == null) {
            parent = rootItem;
        } else {
            parent = itemMap.get(thisNode.getParent());
        }

        updated.add(parent);

        TreeItem<TreeNode> thisItem = new TreeItem<>(thisNode);
        thisItem.addEventHandler(TreeItem.<TreeNode>branchExpandedEvent(), event -> {
            if (thisItem.getChildren().size() == 1) {
                thisItem.getChildren().get(0).setExpanded(true);
            }
        });
        thisItem.setGraphic(new ImageView(new Image(getIconForTreeItem(thisNode))));
        FutureTask<Void> call = new FutureTask<>(() -> {
            parent.getChildren().add(thisItem);
            return null;
        });
        Platform.runLater(call);
        try {
            call.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

        itemMap.put(thisNode, thisItem);

        queue.addAll(thisNode.getChildren());
    }

    for (TreeItem<TreeNode> parent : updated) {
        if (parent.getChildren().size() > 1) {
            FutureTask<Void> call = new FutureTask<>(() -> {
                parent.getChildren().sort((a, b) -> {
                    int ac = a.getValue().getChildren().size();
                    int bc = b.getValue().getChildren().size();

                    if (ac == 0 && bc != 0)
                        return 1;
                    else if (ac != 0 && bc == 0)
                        return -1;
                    return a.getValue().getDisplayName().compareTo(b.getValue().getDisplayName());
                });
                return null;
            });
            Platform.runLater(call);
            try {
                call.get();
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
    }

    queue.addAll(remove);

    while (!queue.isEmpty()) {
        TreeNode thisNode = queue.pop();
        TreeItem<TreeNode> thisItem = itemMap.remove(thisNode);
        thisItem.getParent().getChildren().remove(thisItem);
        queue.addAll(thisNode.getChildren());
    }
}

From source file:org.graphwalker.io.factory.yed.YEdContextFactory.java

private Vertex addVertices(Model model, Context context, GraphmlDocument document, Map<String, Vertex> elements)
        throws XmlException {
    Vertex startVertex = null;//ww  w . j a v a 2 s  . c  o m
    Deque<XmlObject> workQueue = new ArrayDeque<>();
    workQueue.addAll(Arrays.asList(document.selectPath(NAMESPACE + "$this/xq:graphml/xq:graph/xq:node")));
    while (!workQueue.isEmpty()) {
        XmlObject object = workQueue.pop();
        if (object instanceof NodeType) {
            NodeType node = (NodeType) object;
            if (0 < node.getGraphArray().length) {
                for (GraphType subgraph : node.getGraphArray()) {
                    workQueue.addAll(Arrays.asList(subgraph.getNodeArray()));
                }
            } else {
                String description = "";
                for (DataType data : node.getDataArray()) {
                    if (0 < data.getDomNode().getChildNodes().getLength()) {
                        if (data.getKey().equals("d5")) {
                            description = ((DataTypeImpl) data).getStringValue();
                        }
                        if (isSupportedNode(data.xmlText())) {
                            StringBuilder label = new StringBuilder();
                            for (NodeLabelType nodeLabel : getSupportedNode(data.xmlText())
                                    .getNodeLabelArray()) {
                                label.append(((NodeLabelTypeImpl) nodeLabel).getStringValue());
                            }
                            YEdVertexParser parser = new YEdVertexParser(getTokenStream(label.toString()));
                            parser.removeErrorListeners();
                            parser.addErrorListener(YEdDescriptiveErrorListener.INSTANCE);
                            YEdVertexParser.ParseContext parseContext = parser.parse();
                            Vertex vertex = new Vertex();
                            if (!description.isEmpty()) {
                                vertex.setProperty("description", description);
                            }
                            vertex.setProperty("x", getSupportedNode(data.xmlText()).getGeometry().getX());
                            vertex.setProperty("y", getSupportedNode(data.xmlText()).getGeometry().getY());
                            boolean blocked = false;
                            if (null != parseContext.start()) {
                                elements.put(node.getId(), vertex);
                                vertex.setId(node.getId());
                                startVertex = vertex;
                            } else {
                                for (YEdVertexParser.FieldContext field : parseContext.field()) {
                                    if (null != field.names()) {
                                        vertex.setName(field.names().getText());
                                    }
                                    if (null != field.shared() && null != field.shared().Identifier()) {
                                        vertex.setSharedState(field.shared().Identifier().getText());
                                    }
                                    if (null != field.reqtags()) {
                                        vertex.setRequirements(convertVertexRequirement(
                                                field.reqtags().reqtagList().reqtag()));
                                    }
                                    if (null != field.actions()) {
                                        model.addActions(convertVertexAction(field.actions().action()));
                                    }
                                    if (null != field.blocked()) {
                                        blocked = true;
                                    }
                                }
                                if (!blocked) {
                                    elements.put(node.getId(), vertex);
                                    vertex.setId(node.getId());
                                    model.addVertex(vertex);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    return startVertex;
}

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

public void testGetLast() {
    Object o1 = new Object();
    Object o2 = new Object();

    ArrayDeque<Object> deque = new ArrayDeque<>();
    try {/* w  ww .  j  a  va2 s .c  o  m*/
        deque.getLast();
        fail();
    } catch (NoSuchElementException expected) {
    }

    deque.add(o1);
    assertEquals(o1, deque.getLast());
    checkDequeSizeAndContent(deque, o1);

    deque.add(o2);
    assertEquals(o2, deque.getLast());
    checkDequeSizeAndContent(deque, o1, o2);

    deque.clear();
    assertTrue(deque.isEmpty());
    try {
        deque.getLast();
        fail();
    } catch (NoSuchElementException expected) {
    }
}

From source file:org.roche.antibody.services.graphsynchronizer.GraphSynchronizer.java

private HELMCode buildHelm(Domain activeDomain) {
    HELMCode code = new HELMCode();
    Deque<Sequence> sequencesToHandle = new ArrayDeque<Sequence>();
    handledConnections.clear();/* w  w  w .  j ava  2s  .  c o m*/
    handledInterDomainConnections.clear();
    handledSequences.clear();
    sequencesToHandle.offer(activeDomain);
    Map<Sequence, HELMElement> helmElemMap = new HashMap<Sequence, HELMElement>();
    while (sequencesToHandle.isEmpty() == false) {
        Sequence seqToHandle = sequencesToHandle.poll();
        Sequence seqForConnectionCheck = seqToHandle;

        if (handledSequences.contains(seqToHandle)) {
            continue;
        } else {
            handledSequences.add(seqToHandle);
        }

        if (seqToHandle instanceof Domain) {
            activeDomain = (Domain) seqToHandle;
            HELMElement pep = seqService.toHELM(activeDomain);
            code.addHELMElement(pep);
            helmElemMap.put(activeDomain.getPeptide(), pep);
            seqForConnectionCheck = activeDomain.getPeptide();
        }

        for (Connection con : seqToHandle.getConnections()) {
            if (handledConnections.contains(con)) {
                continue;
            }
            if (con instanceof GeneralConnection) {
                HELMConnection helmCon = null;
                if (con.getSource() == seqForConnectionCheck && con.getTarget() == seqForConnectionCheck) {
                    HELMElement element = seqService.toHELM(seqToHandle);
                    code.addHELMElement(element);
                    helmCon = connectionService.createConnection(con, element, element);
                } else {
                    HELMElement source = helmElemMap.get(con.getSource());
                    if (source == null) {
                        source = seqService.toHELM(con.getSource());
                        helmElemMap.put(con.getSource(), source);
                        code.addHELMElement(source);
                        sequencesToHandle.push(con.getSource());
                    }

                    HELMElement target = helmElemMap.get(con.getTarget());
                    if (target == null) {
                        target = seqService.toHELM(con.getTarget());
                        helmElemMap.put(con.getTarget(), target);
                        code.addHELMElement(target);
                        sequencesToHandle.push(con.getTarget());
                    }
                    helmCon = connectionService.createConnection(con, source, target);
                }
                code.addHELMConnection(helmCon);
                handledConnections.add(con);
            }
            if (con instanceof CysteinConnection && connectionService.isIntraDomainConnection(con)) {
                HELMConnection helmCon = connectionService.createConnection(con,
                        helmElemMap.get(activeDomain.getPeptide()), helmElemMap.get(activeDomain.getPeptide()));
                handledConnections.add(con);
                code.addHELMConnection(helmCon);
            }
            if (con instanceof CysteinConnection && !connectionService.isIntraDomainConnection(con)) {
                handledInterDomainConnections.add(con);
            }
        }
    }
    return code;
}

From source file:org.ciasaboark.tacere.database.DatabaseInterface.java

public Deque<EventInstance> getAllActiveEvents() {
    //TODO better SQL select
    Deque<EventInstance> events = new ArrayDeque<EventInstance>();
    String whereClause = Columns.EFFECTIVE_END + " > ? AND " + Columns.BEGIN + " < ?";
    long beginTime = System.currentTimeMillis()
            - (EventInstance.MILLISECONDS_IN_MINUTE * (long) prefs.getBufferMinutes());
    long endTime = System.currentTimeMillis()
            + (EventInstance.MILLISECONDS_IN_MINUTE * (long) prefs.getBufferMinutes());
    String[] whereArgs = new String[] { String.valueOf(beginTime), String.valueOf(endTime) };
    Cursor cursor = null;//from  ww  w .  j  av  a 2 s  .c  om

    try {
        cursor = eventsDB.query(EventDatabaseOpenHelper.TABLE_EVENTS, LOCAL_DB_PROJECTION, whereClause,
                whereArgs, null, null, null);

        while (cursor.moveToNext()) {
            long id = cursor.getLong(LOCAL_DB_PROJECTION_ID);
            long calId = cursor.getLong(LOCAL_DB_PROJECTION_CAL_ID);
            long eventId = cursor.getLong(LOCAL_DB_PROJECTION_EVENT_ID);
            long begin = cursor.getLong(LOCAL_DB_PROJECTION_BEGIN);
            long end = cursor.getLong(LOCAL_DB_PROJECTION_ORIGINAL_END);
            String title = cursor.getString(LOCAL_DB_PROJECTION_TITLE);
            String description = cursor.getString(LOCAL_DB_PROJECTION_DESCRIPTION);
            String location = cursor.getString(LOCAL_DB_PROJECTION_LOCATION);
            int displayColor = cursor.getInt(LOCAL_DB_PROJECTION_DISPLAY_COLOR);
            boolean isAllDay = cursor.getInt(LOCAL_DB_PROJECTION_ALLDAY) == 1;
            boolean isAvailable = cursor.getInt(LOCAL_DB_PROJECTION_AVAILABLE) == 1;
            int ringerInt = cursor.getInt(LOCAL_DB_PROJECTION_RINGER);
            RingerType ringerType = RingerType.getTypeForInt(ringerInt);
            int extendMinutes = cursor.getInt(LOCAL_DB_PROJECTION_EXTEND_MINUTES);

            EventInstance e = new EventInstance(calId, id, eventId, title, begin, end, description,
                    displayColor, isAvailable, isAllDay, extendMinutes);
            e.setLocation(location);
            e.setRingerType(ringerType);
            if (e.isActiveBetween(beginTime, endTime)) {
                events.add(e);
            }

        }
    } catch (Exception e) {
        Log.d(TAG, "error getting cursor for active events");
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    return events;
}

From source file:org.openregistry.core.domain.jpa.JpaPersonImpl.java

@Override
public Map<String, Deque<Identifier>> getIdentifiersByType() {
    final Map<String, Deque<Identifier>> identifiersByType = new HashMap<String, Deque<Identifier>>();

    for (final Identifier identifier : this.identifiers) {
        final String identifierType = identifier.getType().getName();
        Deque<Identifier> listIdentifiers = identifiersByType.get(identifierType);

        if (listIdentifiers == null) {
            listIdentifiers = new ArrayDeque<Identifier>();
            identifiersByType.put(identifierType, listIdentifiers);
        }/*w  ww  .  j  a  v  a2 s . c o m*/

        if (identifier.isPrimary()) {
            listIdentifiers.addFirst(identifier);
        } else {
            listIdentifiers.addLast(identifier);
        }
    }

    return identifiersByType;
}

From source file:com.espertech.esper.core.start.EPPreparedExecuteMethodQuery.java

/**
 * Executes the prepared query.//from  w w w. j  a  v  a 2  s .  co m
 * @return query results
 */
public EPPreparedQueryResult execute(ContextPartitionSelector[] contextPartitionSelectors) {
    int numStreams = processors.length;

    if (contextPartitionSelectors != null && contextPartitionSelectors.length != numStreams) {
        throw new IllegalArgumentException(
                "Number of context partition selectors does not match the number of named windows in the from-clause");
    }

    // handle non-context case
    if (statementSpec.getOptionalContextName() == null) {

        Collection<EventBean>[] snapshots = new Collection[numStreams];
        for (int i = 0; i < numStreams; i++) {

            ContextPartitionSelector selector = contextPartitionSelectors == null ? null
                    : contextPartitionSelectors[i];
            snapshots[i] = getStreamFilterSnapshot(i, selector);
        }

        resultSetProcessor.clear();
        return process(snapshots);
    }

    List<ContextPartitionResult> contextPartitionResults = new ArrayList<ContextPartitionResult>();
    ContextPartitionSelector singleSelector = contextPartitionSelectors != null
            && contextPartitionSelectors.length > 0 ? contextPartitionSelectors[0] : null;

    // context partition runtime query
    Collection<Integer> agentInstanceIds = EPPreparedExecuteMethodHelper.getAgentInstanceIds(processors[0],
            singleSelector, services.getContextManagementService(), statementSpec.getOptionalContextName());

    // collect events and agent instances
    for (int agentInstanceId : agentInstanceIds) {
        NamedWindowProcessorInstance processorInstance = processors[0].getProcessorInstance(agentInstanceId);
        if (processorInstance != null) {
            Collection<EventBean> coll = processorInstance.getTailViewInstance().snapshot(filters[0],
                    statementSpec.getAnnotations());
            contextPartitionResults.add(new ContextPartitionResult(coll,
                    processorInstance.getTailViewInstance().getAgentInstanceContext()));
        }
    }

    // process context partitions
    ArrayDeque<EventBean[]> events = new ArrayDeque<EventBean[]>();
    for (ContextPartitionResult contextPartitionResult : contextPartitionResults) {
        Collection<EventBean> snapshot = contextPartitionResult.getEvents();
        if (statementSpec.getFilterRootNode() != null) {
            snapshot = getFiltered(snapshot, Collections.singletonList(statementSpec.getFilterRootNode()));
        }
        EventBean[] rows = snapshot.toArray(new EventBean[snapshot.size()]);
        resultSetProcessor.setAgentInstanceContext(contextPartitionResult.getContext());
        UniformPair<EventBean[]> results = resultSetProcessor.processViewResult(rows, null, true);
        if (results != null && results.getFirst() != null && results.getFirst().length > 0) {
            events.add(results.getFirst());
        }
    }
    return new EPPreparedQueryResult(resultSetProcessor.getResultEventType(), EventBeanUtility.flatten(events));
}

From source file:com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocStyleCheck.java

/**
 * Checks the comment for HTML tags that do not have a corresponding close
 * tag or a close tag that has no previous open tag.  This code was
 * primarily copied from the DocCheck checkHtml method.
 *
 * @param ast the node with the Javadoc//from   w w w. j  a va2 s  .com
 * @param comment the {@code TextBlock} which represents
 *                 the Javadoc comment.
 */
private void checkHtmlTags(final DetailAST ast, final TextBlock comment) {
    final int lineNo = comment.getStartLineNo();
    final Deque<HtmlTag> htmlStack = new ArrayDeque<>();
    final String[] text = comment.getText();

    final TagParser parser = new TagParser(text, lineNo);

    while (parser.hasNextTag()) {
        final HtmlTag tag = parser.nextTag();

        if (tag.isIncompleteTag()) {
            log(tag.getLineNo(), INCOMPLETE_TAG, text[tag.getLineNo() - lineNo]);
            return;
        }
        if (tag.isClosedTag()) {
            //do nothing
            continue;
        }
        if (tag.isCloseTag()) {
            // We have found a close tag.
            if (isExtraHtml(tag.getId(), htmlStack)) {
                // No corresponding open tag was found on the stack.
                log(tag.getLineNo(), tag.getPosition(), EXTRA_HTML, tag);
            } else {
                // See if there are any unclosed tags that were opened
                // after this one.
                checkUnclosedTags(htmlStack, tag.getId());
            }
        } else {
            //We only push html tags that are allowed
            if (isAllowedTag(tag)) {
                htmlStack.push(tag);
            }
        }
    }

    // Identify any tags left on the stack.
    // Skip multiples, like <b>...<b>
    String lastFound = "";
    final List<String> typeParameters = CheckUtils.getTypeParameterNames(ast);
    for (final HtmlTag htmlTag : htmlStack) {
        if (!isSingleTag(htmlTag) && !htmlTag.getId().equals(lastFound)
                && !typeParameters.contains(htmlTag.getId())) {
            log(htmlTag.getLineNo(), htmlTag.getPosition(), UNCLOSED_HTML, htmlTag);
            lastFound = htmlTag.getId();
        }
    }
}

From source file:com.espertech.esper.core.start.EPPreparedExecuteMethod.java

/**
 * Executes the prepared query.//from   w w w  .j  av  a2  s. c o  m
 * @return query results
 */
public EPPreparedQueryResult execute(ContextPartitionSelector[] contextPartitionSelectors) {
    int numStreams = processors.length;

    if (contextPartitionSelectors != null && contextPartitionSelectors.length != numStreams) {
        throw new IllegalArgumentException(
                "Number of context partition selectors does not match the number of named windows in the from-clause");
    }

    // handle non-context case
    if (statementSpec.getOptionalContextName() == null) {

        Collection<EventBean>[] snapshots = new Collection[numStreams];
        for (int i = 0; i < numStreams; i++) {

            ContextPartitionSelector selector = contextPartitionSelectors == null ? null
                    : contextPartitionSelectors[i];
            snapshots[i] = getStreamFilterSnapshot(i, selector);
        }

        resultSetProcessor.clear();
        return process(snapshots);
    }

    List<ContextPartitionResult> contextPartitionResults = new ArrayList<ContextPartitionResult>();

    // context partition runtime query
    Collection<Integer> agentInstanceIds;
    if (contextPartitionSelectors == null
            || contextPartitionSelectors[0] instanceof ContextPartitionSelectorAll) {
        agentInstanceIds = processors[0].getProcessorInstancesAll();
    } else {
        ContextManager contextManager = services.getContextManagementService()
                .getContextManager(statementSpec.getOptionalContextName());
        agentInstanceIds = contextManager.getAgentInstanceIds(contextPartitionSelectors[0]);
    }

    // collect events and agent instances
    for (int agentInstanceId : agentInstanceIds) {
        NamedWindowProcessorInstance processorInstance = processors[0].getProcessorInstance(agentInstanceId);
        if (processorInstance != null) {
            Collection<EventBean> coll = processorInstance.getTailViewInstance().snapshot(filters[0],
                    statementSpec.getAnnotations());
            contextPartitionResults.add(new ContextPartitionResult(coll,
                    processorInstance.getTailViewInstance().getAgentInstanceContext()));
        }
    }

    // process context partitions
    ArrayDeque<EventBean[]> events = new ArrayDeque<EventBean[]>();
    for (ContextPartitionResult contextPartitionResult : contextPartitionResults) {
        Collection<EventBean> snapshot = contextPartitionResult.getEvents();
        if (statementSpec.getFilterRootNode() != null) {
            snapshot = getFiltered(snapshot, Collections.singletonList(statementSpec.getFilterRootNode()));
        }
        EventBean[] rows = snapshot.toArray(new EventBean[snapshot.size()]);
        resultSetProcessor.setAgentInstanceContext(contextPartitionResult.getContext());
        UniformPair<EventBean[]> results = resultSetProcessor.processViewResult(rows, null, true);
        if (results != null && results.getFirst() != null && results.getFirst().length > 0) {
            events.add(results.getFirst());
        }
    }
    return new EPPreparedQueryResult(resultSetProcessor.getResultEventType(), EventBeanUtility.flatten(events));
}