Example usage for java.util Stack pop

List of usage examples for java.util Stack pop

Introduction

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

Prototype

public synchronized E pop() 

Source Link

Document

Removes the object at the top of this stack and returns that object as the value of this function.

Usage

From source file:org.alfresco.repo.transfer.AlienProcessorImpl.java

public void pruneNode(NodeRef nodeToPrune, String fromRepositoryId) {
    Stack<NodeRef> nodesToPrune = new Stack<NodeRef>();
    nodesToPrune.add(nodeToPrune);//from w  w w .j  a  v a2  s.c o m

    ChildAssociationRef startingParent = nodeService.getPrimaryParent(nodeToPrune);

    Stack<NodeRef> foldersToRecalculate = new Stack<NodeRef>();

    /**
     * Now go and do the pruning.        
     */
    while (!nodesToPrune.isEmpty()) {
        /**
         *  for all alien children
         * 
         *  if from the repo with no (other) aliens - delete
         *  
         *  if from the repo with multiple alien invasions - leave alone but process children
         */
        NodeRef currentNodeRef = nodesToPrune.pop();

        Map<QName, Serializable> properties = null;
        if (log.isDebugEnabled()) {
            properties = nodeService.getProperties(currentNodeRef);
        }

        if (log.isDebugEnabled()) {
            log.debug("Current nodeRef (name: \"" + properties.get(ContentModel.PROP_NAME)
                    + "\", fromRepositoryId: \"" + properties.get(TransferModel.PROP_FROM_REPOSITORY_ID)
                    + "\", manifestId: \"" + fromRepositoryId + "\")" + currentNodeRef);
        }

        log.debug("pruneNode:" + currentNodeRef);

        if (getNodeService().hasAspect(currentNodeRef, TransferModel.ASPECT_ALIEN)) {
            if (log.isDebugEnabled()) {
                log.debug("Current nodeRef has ASPECT_ALIEN (name: \"" + properties.get(ContentModel.PROP_NAME)
                        + "\", fromRepositoryId: \"" + properties.get(TransferModel.PROP_FROM_REPOSITORY_ID)
                        + "\", manifestId: \"" + fromRepositoryId + "\")");
            }

            // Yes this is an alien node
            List<String> invadedBy = (List<String>) getNodeService().getProperty(currentNodeRef,
                    TransferModel.PROP_INVADED_BY);
            String initialRepoId = (String) getNodeService().getProperty(currentNodeRef,
                    TransferModel.PROP_FROM_REPOSITORY_ID);

            if (log.isDebugEnabled()) {
                log.debug("Current nodeRef has PROP_INVADED_BY (name: \""
                        + properties.get(ContentModel.PROP_NAME) + "\", fromRepositoryId: \""
                        + properties.get(TransferModel.PROP_FROM_REPOSITORY_ID) + "\", manifestId: \""
                        + fromRepositoryId + "\"): " + invadedBy);
            }

            if ((null != invadedBy) && invadedBy.contains(fromRepositoryId)) {
                if (log.isDebugEnabled()) {
                    log.debug("Current nodeRef's PROP_INVADED_BY contains current manifestId (name: \""
                            + properties.get(ContentModel.PROP_NAME) + "\", fromRepositoryId: \""
                            + properties.get(TransferModel.PROP_FROM_REPOSITORY_ID) + "\", manifestId: \""
                            + fromRepositoryId + "\")");
                }

                // Yes we are invaded by fromRepositoryId
                if ((1 == invadedBy.size()) && fromRepositoryId.equalsIgnoreCase(initialRepoId)) {
                    if (log.isDebugEnabled()) {
                        log.debug(
                                "Current nodeRef has only 1 element in PROP_INVADED_BY. Also MANIFEST_ID and INITIAL_REPOSITORY_ID are the same. Deleting the node... (name: \""
                                        + properties.get(ContentModel.PROP_NAME) + "\", fromRepositoryId: \""
                                        + properties.get(TransferModel.PROP_FROM_REPOSITORY_ID)
                                        + "\", manifestId: \"" + fromRepositoryId + "\")");
                    }

                    // we are invaded by a single repository which must be fromRepositoryId
                    getNodeService().deleteNode(currentNodeRef);
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug(
                                "Current 'nodeRef' has more than 1 element in PROP_INVADED_BY. Adding its children to 'nodesToPrune' list... (name: \""
                                        + properties.get(ContentModel.PROP_NAME) + "\", fromRepositoryId: \""
                                        + properties.get(TransferModel.PROP_FROM_REPOSITORY_ID)
                                        + "\", manifestId: \"" + fromRepositoryId + "\")");
                    }

                    // multiple invasion - so it must be a folder
                    List<ChildAssociationRef> refs = nodeService.getChildAssocsByPropertyValue(currentNodeRef,
                            TransferModel.PROP_INVADED_BY, fromRepositoryId);
                    for (ChildAssociationRef ref : refs) {
                        if (log.isDebugEnabled()) {
                            log.debug("will need to check child:" + ref);
                        }
                        nodesToPrune.push(ref.getChildRef());
                    }

                    /**
                     * Yes we might do something to the children of this node.
                     */
                    if (!foldersToRecalculate.contains(currentNodeRef)) {
                        if (log.isDebugEnabled()) {
                            log.debug(
                                    "Current 'nodeRef' is not in 'foldersToRecalculate' list. Adding it to the list... (name: \""
                                            + properties.get(ContentModel.PROP_NAME)
                                            + "\", fromRepositoryId: \""
                                            + properties.get(TransferModel.PROP_FROM_REPOSITORY_ID)
                                            + "\", manifestId: \"" + fromRepositoryId + "\")");
                        }

                        foldersToRecalculate.push(currentNodeRef);
                    }
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug(
                            "Current \"nodeRef\"'s PROP_INVADED_BY does not contain current 'manifestId' (name: \""
                                    + properties.get(ContentModel.PROP_NAME) + "\", fromRepositoryId: \""
                                    + properties.get(TransferModel.PROP_FROM_REPOSITORY_ID)
                                    + "\", manifestId: \"" + fromRepositoryId + "\")");
                }

                /**
                 * Current node has been invaded by another repository  
                 *
                 * Need to check fromRepositoryId since its children may need to be pruned
                 */
                getNodeService().hasAspect(currentNodeRef, TransferModel.ASPECT_TRANSFERRED);
                {
                    if (fromRepositoryId.equalsIgnoreCase(initialRepoId)) {
                        if (log.isDebugEnabled()) {
                            log.debug("folder is from the transferring repository");
                            log.debug(
                                    "Current nodeRef has more than 1 element in PROP_INVADED_BY. Adding its children to 'nodesToPrune' list... (name: \""
                                            + properties.get(ContentModel.PROP_NAME)
                                            + "\", fromRepositoryId: \""
                                            + properties.get(TransferModel.PROP_FROM_REPOSITORY_ID)
                                            + "\", manifestId: \"" + fromRepositoryId + "\")");
                        }
                        // invaded from somewhere else - so it must be a folder
                        List<ChildAssociationRef> refs = getNodeService().getChildAssocs(currentNodeRef);
                        for (ChildAssociationRef ref : refs) {
                            if (log.isDebugEnabled()) {
                                log.debug("will need to check child:" + ref);
                            }
                            nodesToPrune.push(ref.getChildRef());

                            /**
                             * This folder can't be deleted so its invaded flag needs to be re-calculated 
                             */
                            if (!foldersToRecalculate.contains(currentNodeRef)) {
                                if (log.isDebugEnabled()) {
                                    log.debug(
                                            "Current 'nodeRef' is not in 'foldersToRecalculate' list. Adding it to the list... (name: \""
                                                    + properties.get(ContentModel.PROP_NAME)
                                                    + "\", fromRepositoryId: \""
                                                    + properties.get(TransferModel.PROP_FROM_REPOSITORY_ID)
                                                    + "\", manifestId: \"" + fromRepositoryId + "\")");
                                }

                                foldersToRecalculate.push(currentNodeRef);
                            }
                        }
                    }
                }
            }
        } else {
            // Current node does not contain alien nodes so it can be deleted.
            getNodeService().hasAspect(currentNodeRef, TransferModel.ASPECT_TRANSFERRED);
            {
                if (log.isDebugEnabled()) {
                    log.debug("Current 'nodeRef' does not have ASPECT_ALIEN (name: \""
                            + properties.get(ContentModel.PROP_NAME) + "\", fromRepositoryId: \""
                            + properties.get(TransferModel.PROP_FROM_REPOSITORY_ID) + "\", manifestId: \""
                            + fromRepositoryId + "\")");
                }

                String initialRepoId = (String) getNodeService().getProperty(currentNodeRef,
                        TransferModel.PROP_REPOSITORY_ID);
                if (fromRepositoryId.equalsIgnoreCase(initialRepoId)) {
                    if (log.isDebugEnabled()) {
                        log.debug(
                                "Current \"nodeRef\"'s has PROP_FROM_REPOSITORY_ID equal to current 'manifestId'. Deleting the node... (name: \""
                                        + properties.get(ContentModel.PROP_NAME) + "\", fromRepositoryId: \""
                                        + properties.get(TransferModel.PROP_FROM_REPOSITORY_ID)
                                        + "\", manifestId: \"" + fromRepositoryId + "\")");
                        // we are invaded by a single repository
                        log.debug("pruned - deleted non alien node:" + currentNodeRef);
                    }

                    getNodeService().deleteNode(currentNodeRef);
                }
            }
        }
    }

    /**
     * Now recalculate the "invadedBy" flag for those folders we could not delete.
     */
    while (!foldersToRecalculate.isEmpty()) {
        NodeRef folderNodeRef = foldersToRecalculate.pop();

        log.debug("recalculate invadedBy :" + folderNodeRef);

        recalcInvasion(folderNodeRef, fromRepositoryId);
    }

    /**
     * Now ripple up the invaded flag - may be a alien retreat.
     */
    log.debug("now ripple upwards");

    ChildAssociationRef ripple = startingParent;
    while (ripple != null) {
        if (log.isDebugEnabled()) {
            log.debug("Checking parent:" + ripple);
        }

        if (nodeService.hasAspect(ripple.getParentRef(), TransferModel.ASPECT_ALIEN)) {
            if (recalcInvasion(ripple.getParentRef(), fromRepositoryId)) {
                log.debug("parent is still invaded");
                ripple = null;
            } else {
                log.debug("parent is no longer invaded");
                ripple = nodeService.getPrimaryParent(ripple.getParentRef());
            }
        } else {
            ripple = null;
        }
    }

    log.debug("pruneNode: end");
}

From source file:com.consol.citrus.mail.server.MailServer.java

/**
 * Split mail message into several messages. Each body and each attachment results in separate message
 * invoked on message handler. Mail message response if any should be sent only once within test case.
 * However latest mail response sent by test case is returned, others are ignored.
 *
 * @param bodyPart//from   w ww  .  j  a v a 2 s.c  o m
 * @param messageHeaders
 */
private org.springframework.integration.Message<?> split(BodyPart bodyPart,
        Map<String, String> messageHeaders) {
    MailMessage mailMessage = createMailMessage(messageHeaders);
    mailMessage.setBody(new BodyPart(bodyPart.getContent(), bodyPart.getContentType()));

    Stack<org.springframework.integration.Message<?>> responseStack = new Stack<org.springframework.integration.Message<?>>();
    if (bodyPart instanceof AttachmentPart) {
        fillStack(getEndpointAdapter().handleMessage(org.springframework.integration.support.MessageBuilder
                .withPayload(mailMessageMapper.toXML(mailMessage)).copyHeaders(messageHeaders)
                .setHeader(CitrusMailMessageHeaders.MAIL_CONTENT_TYPE, bodyPart.getContentType())
                .setHeader(CitrusMailMessageHeaders.MAIL_FILENAME, ((AttachmentPart) bodyPart).getFileName())
                .build()), responseStack);
    } else {
        fillStack(getEndpointAdapter().handleMessage(org.springframework.integration.support.MessageBuilder
                .withPayload(mailMessageMapper.toXML(mailMessage)).copyHeaders(messageHeaders)
                .setHeader(CitrusMailMessageHeaders.MAIL_CONTENT_TYPE, bodyPart.getContentType()).build()),
                responseStack);
    }

    if (bodyPart.hasAttachments()) {
        for (AttachmentPart attachmentPart : bodyPart.getAttachments()) {
            fillStack(split(attachmentPart, messageHeaders), responseStack);
        }
    }

    return responseStack.isEmpty() ? null : responseStack.pop();
}

From source file:org.apache.tajo.engine.planner.rewrite.ProjectionPushDownRule.java

@Override
public LogicalNode visitUnion(Context context, LogicalPlan plan, LogicalPlan.QueryBlock block, UnionNode node,
        Stack<LogicalNode> stack) throws PlanningException {

    LogicalPlan.QueryBlock leftBlock = plan.getBlock(node.getLeftChild());
    LogicalPlan.QueryBlock rightBlock = plan.getBlock(node.getRightChild());

    Context leftContext = new Context(plan,
            PlannerUtil.toQualifiedFieldNames(context.requiredSet, leftBlock.getName()));
    Context rightContext = new Context(plan,
            PlannerUtil.toQualifiedFieldNames(context.requiredSet, rightBlock.getName()));

    stack.push(node);/*from   w  w w . ja v  a2 s . c o m*/
    visit(leftContext, plan, leftBlock, leftBlock.getRoot(), new Stack<LogicalNode>());
    visit(rightContext, plan, rightBlock, rightBlock.getRoot(), new Stack<LogicalNode>());
    stack.pop();
    return node;
}

From source file:edu.umn.cs.spatialHadoop.indexing.RTree.java

/**
 * Searches the RTree starting from the given start position. This is either
 * a node number or offset of an element. If it's a node number, it performs
 * the search in the subtree rooted at this node. If it's an offset number,
 * it searches only the object found there.
 * It is assumed that the openQuery() has been called before this function
 * and that endQuery() will be called afterwards.
 * @param query_shape/*from   ww  w. ja  va 2s  .c om*/
 * @param output
 * @param start where to start searching
 * @param end where to end searching. Only used when start is an offset of
 *   an object.
 * @return
 * @throws IOException
 */
protected int search(Shape query_shape, ResultCollector<T> output, int start, int end) throws IOException {
    Rectangle query_mbr = query_shape.getMBR();
    int resultSize = 0;
    // Special case for an empty tree
    if (height == 0)
        return 0;

    Stack<Integer> toBeSearched = new Stack<Integer>();
    // Start from the given node
    toBeSearched.push(start);
    if (start >= nodeCount) {
        toBeSearched.push(end);
    }

    // Holds one data line from tree data
    Text line = new Text2();

    while (!toBeSearched.isEmpty()) {
        int searchNumber = toBeSearched.pop();

        if (searchNumber < nodeCount) {
            // Searching a node
            int nodeID = searchNumber;
            if (query_mbr.isIntersected(nodes[nodeID])) {
                boolean is_leaf = nodeID >= nonLeafNodeCount;
                if (is_leaf) {
                    // Check all objects under this node
                    int start_offset = this.dataOffset[nodeID];
                    int end_offset = this.dataOffset[nodeID + 1];
                    toBeSearched.add(start_offset);
                    toBeSearched.add(end_offset);
                } else {
                    // Add all child nodes
                    for (int iChild = 0; iChild < this.degree; iChild++) {
                        toBeSearched.add(nodeID * this.degree + iChild + 1);
                    }
                }
            }
        } else {
            // searchNumber is the end offset of data search. Start offset is next
            // in stack
            int end_offset = searchNumber;
            int start_offset = toBeSearched.pop();
            // All data offsets are relative to tree start (typically 4)
            this.data.seek(start_offset + this.treeStartOffset);
            // Should not close the line reader because we do not want to close
            // the underlying data stream now. In case future searches are done
            @SuppressWarnings("resource")
            LineReader lineReader = new LineReader(data);
            while (start_offset < end_offset) {
                start_offset += lineReader.readLine(line);
                stockObject.fromText(line);
                if (stockObject.isIntersected(query_shape)) {
                    resultSize++;
                    if (output != null)
                        output.collect(stockObject);
                }
            }
        }
    }
    return resultSize;
}

From source file:org.apache.hadoop.hive.ql.parse.TezCompiler.java

private void connect(Operator<?> o, AtomicInteger index, Stack<Operator<?>> nodes,
        Map<Operator<?>, Integer> indexes, Map<Operator<?>, Integer> lowLinks,
        Set<Set<Operator<?>>> components) {

    indexes.put(o, index.get());/*from  ww w  . j  a va2 s  .  c o  m*/
    lowLinks.put(o, index.get());
    index.incrementAndGet();
    nodes.push(o);

    List<Operator<?>> children;
    if (o instanceof AppMasterEventOperator) {
        children = new ArrayList<Operator<?>>();
        children.addAll(o.getChildOperators());
        TableScanOperator ts = ((DynamicPruningEventDesc) o.getConf()).getTableScan();
        LOG.debug("Adding special edge: " + o.getName() + " --> " + ts.toString());
        children.add(ts);
    } else {
        children = o.getChildOperators();
    }

    for (Operator<?> child : children) {
        if (!indexes.containsKey(child)) {
            connect(child, index, nodes, indexes, lowLinks, components);
            lowLinks.put(o, Math.min(lowLinks.get(o), lowLinks.get(child)));
        } else if (nodes.contains(child)) {
            lowLinks.put(o, Math.min(lowLinks.get(o), indexes.get(child)));
        }
    }

    if (lowLinks.get(o).equals(indexes.get(o))) {
        Set<Operator<?>> component = new HashSet<Operator<?>>();
        components.add(component);
        Operator<?> current;
        do {
            current = nodes.pop();
            component.add(current);
        } while (current != o);
    }
}

From source file:com.continusec.client.VerifiableLog.java

/**
 * Utility method for auditors that wish to audit the full content of a log, as well as the log operation.
 * This method will retrieve all entries in batch from the log, and ensure that the root hash in head can be confirmed to accurately represent the contents
 * of all of the log entries. If prev is not null, then additionally it is proven that the root hash in head is consistent with the root hash in prev.
 * @param prev a previous LogTreeHead representing the set of entries that have been previously audited. To indicate this is has not previously been audited, pass null,
 * @param head the LogTreeHead up to which we wish to audit the log. Upon successful completion the caller should persist this for a future iteration.
 * @param auditor caller should implemented a LogAuditor which is called sequentially for each log entry as it is encountered.
 * @param factory the factory to use for instantiating log entries. Typically this is one of {@link RawDataEntryFactory#getInstance()}, {@link JsonEntryFactory#getInstance()}, {@link RedactedJsonEntryFactory#getInstance()}.
 * @throws ContinusecException upon error
 *//*from w ww. j  a v a2  s  . c  om*/
public void verifyEntries(LogTreeHead prev, LogTreeHead head, VerifiableEntryFactory factory,
        LogAuditor auditor) throws ContinusecException {
    if ((prev == null) || prev.getTreeSize() < head.getTreeSize()) {
        Stack<byte[]> merkleTreeStack = new Stack<byte[]>();
        if ((prev != null) && (prev.getTreeSize() > 0)) {
            LogInclusionProof p = this.getInclusionProofByIndex(prev.getTreeSize() + 1, prev.getTreeSize());
            byte[] firstHash = null;
            for (byte[] b : p.getAuditPath()) {
                if (firstHash == null) {
                    firstHash = b;
                } else {
                    firstHash = Util.nodeMerkleTreeHash(b, firstHash);
                }
            }
            if (!(Arrays.equals(firstHash, prev.getRootHash()))) {
                throw new VerificationFailedException();
            }
            for (int i = p.getAuditPath().length - 1; i >= 0; i--) {
                merkleTreeStack.push(p.getAuditPath()[i]);
            }
        }

        int idx = (prev == null) ? 0 : prev.getTreeSize();
        try {
            for (VerifiableEntry e : this.getEntries(idx, head.getTreeSize(), factory)) {
                // do whatever content audit is desired on e
                auditor.auditLogEntry(idx, e);

                // update the merkle tree hash stack:
                merkleTreeStack.add(e.getLeafHash());
                for (int z = idx; (z & 1) == 1; z >>= 1) {
                    byte[] right = merkleTreeStack.pop();
                    byte[] left = merkleTreeStack.pop();
                    merkleTreeStack.push(Util.nodeMerkleTreeHash(left, right));
                }
                idx++;
            }
        } catch (RuntimeException e2) {
            // since get entries iterator throws a runtime exception that wraps the real continusec exception...
            Throwable cause = e2.getCause();
            if (cause instanceof ContinusecException) {
                throw (ContinusecException) cause;
            } else {
                throw e2;
            }
        }

        if (idx != head.getTreeSize()) {
            throw new NotAllEntriesReturnedException();
        }

        byte[] headHash = merkleTreeStack.pop();
        while (!merkleTreeStack.empty()) {
            headHash = Util.nodeMerkleTreeHash(merkleTreeStack.pop(), headHash);
        }

        if (!(Arrays.equals(headHash, head.getRootHash()))) {
            throw new VerificationFailedException();
        }
    }
}

From source file:io.warp10.worf.WorfInteractive.java

public String runTemplate(Properties config, String warp10Configuration) throws WorfException {
    try {/*from   w ww .ja v a 2 s  .  c  o m*/
        out.println("The configuration file is a template");
        WorfTemplate template = new WorfTemplate(config, warp10Configuration);

        out.println("Generating crypto keys...");
        for (String cryptoKey : template.getCryptoKeys()) {
            String keySize = template.generateCryptoKey(cryptoKey);
            if (keySize != null) {
                out.println(keySize + " bits secured key for " + cryptoKey + "  generated");
            } else {
                out.println("Unable to generate " + cryptoKey + ", template error");
            }
        }

        out.println("Crypto keys generated");

        Stack<Pair<String, String[]>> fieldsStack = template.getFieldsStack();

        if (fieldsStack.size() > 0) {
            out.println("Update configuration...");
        }

        while (!fieldsStack.isEmpty()) {
            Pair<String, String[]> templateValues = fieldsStack.peek();
            String replaceValue = null;
            // get user input
            switch (templateValues.getValue()[0]) {
            case "path":
                replaceValue = readInputPath(reader, out, templateValues.getValue()[2]);
                break;
            case "host":
                replaceValue = readHost(reader, out, templateValues.getValue()[2]);
                break;
            case "int":
                replaceValue = readInteger(reader, out, templateValues.getValue()[2]);
                break;
            }

            if (replaceValue == null) {
                out.println("Unable to update " + templateValues.getValue()[1] + " key, enter a valid "
                        + templateValues.getValue()[0]);
                continue;
            }

            // replace template value
            template.updateField(templateValues.getKey(), replaceValue);

            // field updated pop
            fieldsStack.pop();
        }

        out.println("Configuration updated.");

        // save file
        Path warp10ConfigurationPath = Paths.get(warp10Configuration);
        String outputFileName = warp10ConfigurationPath.getFileName().toString();
        outputFileName = outputFileName.replace("template", "conf");
        String outputPath = readInputPath(reader, out, "save config:output path",
                warp10ConfigurationPath.getParent().toString());
        String outputFilename = readInputString(reader, out, "save config:output filename", outputFileName);

        if (Strings.isNullOrEmpty(outputPath) || Strings.isNullOrEmpty(outputFilename)) {
            throw new Exception("Path or filename empty, unable to save configuration file!");
        }

        StringBuilder sb = new StringBuilder();
        sb.append(outputPath);
        if (!outputPath.endsWith(File.separator)) {
            sb.append(File.separator);
        }
        sb.append(outputFilename);

        warp10Configuration = sb.toString();
        template.saveConfig(warp10Configuration);

        out.println("Configuration saved. filepath=" + warp10Configuration);
        out.println("Reading warp10 configuration " + warp10Configuration);
        return warp10Configuration;
    } catch (Exception exp) {
        throw new WorfException("Unexpected Worf error:" + exp.getMessage());
    }
}

From source file:com.wavemaker.json.JSONMarshaller.java

private static boolean handleObjectInternal(Object object, Object root, String key, Object value,
        boolean firstProperty, JSONState js, Writer writer, Stack<Object> touchedObjects,
        Stack<String> propertyNames, boolean sort, FieldDefinition fieldDefinition, int arrayLevel,
        TypeState typeState, boolean prettyPrint, int level, Logger logger) throws IOException {

    if (fieldDefinition == null) {
        throw new NullArgumentException("fieldDefinition");
    }/*from ww  w  .  j  a v a  2s.  c om*/

    propertyNames.push(key);
    String propertyName = getPropertyName(propertyNames, js);
    try {
        if (js.getExcludes().contains(propertyName)) {
            return firstProperty;
        }

        if (js.getPropertyFilter() != null) {
            if (js.getPropertyFilter().filter(object, key, value)) {
                return firstProperty;
            }
        }

        // cycle
        if (isCycle(value, touchedObjects, propertyName, js)) {
            if (logger.isInfoEnabled()) {
                logger.info(MessageResource.JSON_CYCLE_FOUND.getMessage(value, js.getCycleHandler()));
            }

            if (js.getCycleHandler().equals(JSONState.CycleHandler.FAIL)) {
                throw new WMRuntimeException(MessageResource.JSON_CYCLE_FOUND, value, js.getCycleHandler());
            } else if (js.getCycleHandler().equals(JSONState.CycleHandler.NULL)) {
                value = null;
            } else if (js.getCycleHandler().equals(JSONState.CycleHandler.NO_PROPERTY)) {
                return firstProperty;
            } else {
                throw new WMRuntimeException(MessageResource.JSON_BAD_CYCLE_HANDLER, js.getCycleHandler());
            }
        }

        if (!firstProperty) {
            writer.write(',');
        }

        if (prettyPrint) {
            writer.write("\n");
            writeIndents(writer, level);
        }

        if (js.isUnquoteKeys()) {
            writer.write(key + ":");
        } else {
            writer.write("\"" + key + "\":");
        }

        if (prettyPrint) {
            writer.write(" ");
        }

        doMarshal(writer, value, root, js, sort, false, touchedObjects, propertyNames, fieldDefinition,
                arrayLevel, typeState, prettyPrint, level, logger);

        if (firstProperty) {
            firstProperty = false;
        }

        return firstProperty;
    } finally {
        propertyNames.pop();
    }
}

From source file:org.amanzi.neo.services.impl.statistics.PropertyStatisticsService.java

protected void updatePropertyVault(final Node propertyVault, final PropertyVault vault)
        throws ServiceException {
    nodeService.updateProperty(propertyVault, statisticsNodeProperties.getClassProperty(),
            vault.getClassName());//from ww w.  j  a v  a  2 s.c  o m

    int size = nodeService.getNodeProperty(propertyVault, getGeneralNodeProperties().getSizeProperty(),
            NumberUtils.INTEGER_ZERO, false);

    Map<Object, Integer> values = new HashMap<Object, Integer>(vault.getValuesMap());

    Queue<Integer> removedIndexes = new LinkedList<Integer>();
    Stack<Integer> processedIndex = new Stack<Integer>();

    if (size > 0) {
        for (int i = 0; i < size; i++) {
            Object property = nodeService.getNodeProperty(propertyVault,
                    statisticsNodeProperties.getValuePrefix() + i, null, true);

            Integer newCount = values.remove(property);
            if (newCount != null) {
                nodeService.updateProperty(propertyVault, statisticsNodeProperties.getCountPrefix() + i,
                        newCount);
            } else {
                removedIndexes.add(i);
            }
            processedIndex.add(i);
        }
    }

    // remove old values
    for (Integer index : removedIndexes) {
        nodeService.removeNodeProperty(propertyVault, statisticsNodeProperties.getValuePrefix() + index, false);
        nodeService.removeNodeProperty(propertyVault, statisticsNodeProperties.getCountPrefix() + index, false);
    }

    int counter = size;
    for (Entry<Object, Integer> statEntry : values.entrySet()) {
        counter = removedIndexes.isEmpty() ? counter : removedIndexes.remove();

        nodeService.updateProperty(propertyVault, statisticsNodeProperties.getValuePrefix() + counter,
                statEntry.getKey());
        nodeService.updateProperty(propertyVault, statisticsNodeProperties.getCountPrefix() + counter,
                statEntry.getValue());

        counter++;
    }

    for (Integer newIndex : removedIndexes) {
        int oldIndex = processedIndex.pop();
        nodeService.renameNodeProperty(propertyVault, statisticsNodeProperties.getValuePrefix() + oldIndex,
                statisticsNodeProperties.getValuePrefix() + newIndex, false);
        nodeService.renameNodeProperty(propertyVault, statisticsNodeProperties.getCountPrefix() + oldIndex,
                statisticsNodeProperties.getCountPrefix() + newIndex, false);
    }

    nodeService.updateProperty(propertyVault, getGeneralNodeProperties().getSizeProperty(), values.size());
    nodeService.updateProperty(propertyVault, statisticsNodeProperties.getDefaultValueProperty(),
            vault.getDefaultValue());
}

From source file:com.taobao.tdhs.jdbc.sqlparser.ParseSQL.java

public TreeNode parseWhere(TreeNode rootnode, String str_where, int loop) {
    // /*from w  w w  .java 2 s .c o m*/
    loop++;
    if (loop > 10000)
        return null;

    String str = str_where.trim();
    TreeNode node = new TreeNode();
    int addr_and;
    int addr_or;
    // ??,??
    if (str.substring(0, 1).equalsIgnoreCase("(")) {
        // ???
        // SQL??in,???
        Stack<String> stack = new Stack<String>();
        int k = 0;
        String tmp_s;
        while (k < str.length()) {
            tmp_s = str.substring(k, k + 1);
            if (!tmp_s.equalsIgnoreCase(")"))
                // 
                stack.push(tmp_s);
            else {
                // ,??
                while (!stack.pop().equalsIgnoreCase("(")) {
                    ;
                }
                // ?,,?
                if (stack.isEmpty())
                    break;
            }

            k++;
        } // end while

        if (k == str.length() - 1) {
            // ??
            return parseWhere(rootnode, str.substring(1, k), loop);
        } else {
            // ??,and  or,
            if (str.substring(k + 1, k + 6).equalsIgnoreCase(" and ")) {
                node.node_content = "and";
                node.node_type = 4;
                node.left_node = parseWhere(node, str.substring(1, k), loop);
                node.right_node = parseWhere(node, str.substring(k + 6), loop);
                node.parent_node = rootnode;
            } else if (str.substring(k + 1, k + 5).equalsIgnoreCase(" or ")) {
                node.node_content = "or";
                node.node_type = 4;
                node.left_node = parseWhere(node, str.substring(1, k), loop);
                node.right_node = parseWhere(node, str.substring(k + 5), loop);
                node.parent_node = rootnode;
            }

            return node;

        }
    } else {
        addr_and = StringUtils.indexOfIgnoreCase(str, " and ");
        addr_or = StringUtils.indexOfIgnoreCase(str, " or ");
        if (addr_and > 0 && addr_or > 0)
            if (addr_and < addr_or) {
                // and
                node.node_content = "and";
                node.node_type = 4;
                node.parent_node = rootnode;
                node.left_node = parseBase(node, str.substring(0, addr_and).trim());
                node.right_node = parseWhere(node, str.substring(addr_and + 5), loop);
                return node;
            } else {
                // or
                node.node_content = "or";
                node.node_type = 4;
                node.parent_node = rootnode;
                node.left_node = parseBase(node, str.substring(0, addr_or).trim());
                node.right_node = parseWhere(node, str.substring(addr_or + 4), loop);
                return node;
            }
        else if (addr_and > 0) {
            node.node_content = "and";
            node.node_type = 4;
            node.parent_node = rootnode;
            node.left_node = parseBase(node, str.substring(0, addr_and).trim());
            node.right_node = parseWhere(node, str.substring(addr_and + 5), loop);
            return node;
        } else if (addr_or > 0) {
            node.node_content = "or";
            node.node_type = 4;
            node.parent_node = rootnode;
            node.left_node = parseBase(node, str.substring(0, addr_or).trim());
            node.right_node = parseWhere(node, str.substring(addr_or + 4), loop);
            return node;
        } else {
            // ??
            return parseBase(rootnode, str);
        }
    }
}