Example usage for java.util Stack peek

List of usage examples for java.util Stack peek

Introduction

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

Prototype

public synchronized E peek() 

Source Link

Document

Looks at the object at the top of this stack without removing it from the stack.

Usage

From source file:com.google.dart.compiler.metrics.Tracer.java

public void addDataImpl(String... data) {
    Stack<TraceEvent> threadPendingEvents = pendingEvents.get();
    if (threadPendingEvents.isEmpty()) {
        throw new IllegalStateException("Tried to add data to an event that never started!");
    }//from  w w  w. j  a  v a2  s .  co  m

    TraceEvent currentEvent = threadPendingEvents.peek();
    currentEvent.addData(data);
}

From source file:org.dhatim.json.JSONReader.java

public void parse(InputSource csvInputSource) throws IOException, SAXException {
    if (contentHandler == null) {
        throw new IllegalStateException("'contentHandler' not set.  Cannot parse JSON stream.");
    }// ww  w  . j  a v a2s .c o m
    if (executionContext == null) {
        throw new IllegalStateException(
                "Smooks container 'executionContext' not set.  Cannot parse JSON stream.");
    }

    try {
        // Get a reader for the JSON source...
        Reader jsonStreamReader = csvInputSource.getCharacterStream();
        if (jsonStreamReader == null) {
            jsonStreamReader = new InputStreamReader(csvInputSource.getByteStream(), encoding);
        }

        // Create the JSON parser...
        JsonParser jp = null;
        try {

            if (logger.isTraceEnabled()) {
                logger.trace("Creating JSON parser");
            }

            jp = jsonFactory.createJsonParser(jsonStreamReader);

            // Start the document and add the root "csv-set" element...
            contentHandler.startDocument();
            startElement(rootName, 0);

            if (logger.isTraceEnabled()) {
                logger.trace("Starting JSON parsing");
            }

            boolean first = true;
            Stack<String> elementStack = new Stack<String>();
            Stack<Type> typeStack = new Stack<Type>();
            JsonToken t;
            while ((t = jp.nextToken()) != null) {

                if (logger.isTraceEnabled()) {
                    logger.trace("Token: " + t.name());
                }

                switch (t) {

                case START_OBJECT:
                case START_ARRAY:
                    if (!first) {
                        if (!typeStack.empty() && typeStack.peek() == Type.ARRAY) {
                            startElement(arrayElementName, typeStack.size());
                        }
                    }
                    typeStack.push(t == JsonToken.START_ARRAY ? Type.ARRAY : Type.OBJECT);
                    break;

                case END_OBJECT:
                case END_ARRAY:

                    typeStack.pop();

                    boolean typeStackPeekIsArray = !typeStack.empty() && typeStack.peek() == Type.ARRAY;

                    if (!elementStack.empty() && !typeStackPeekIsArray) {
                        endElement(elementStack.pop(), typeStack.size());
                    }

                    if (typeStackPeekIsArray) {
                        endElement(arrayElementName, typeStack.size());
                    }
                    break;

                case FIELD_NAME:

                    String text = jp.getText();

                    if (logger.isTraceEnabled()) {
                        logger.trace("Field name: " + text);
                    }

                    String name = getElementName(text);

                    startElement(name, typeStack.size());
                    elementStack.add(name);

                    break;

                default:

                    String value;

                    if (t == JsonToken.VALUE_NULL) {
                        value = nullValueReplacement;
                    } else {
                        value = jp.getText();
                    }

                    if (typeStack.peek() == Type.ARRAY) {

                        startElement(arrayElementName, typeStack.size());
                    }

                    contentHandler.characters(value.toCharArray(), 0, value.length());

                    if (typeStack.peek() == Type.ARRAY) {

                        endElement(arrayElementName);

                    } else {

                        endElement(elementStack.pop());

                    }

                    break;

                }

                first = false;
            }
            endElement(rootName, 0);
            contentHandler.endDocument();
        } finally {

            try {
                jp.close();
            } catch (Exception e) {
            }

        }
    } finally {
        // These properties need to be reset for every execution (e.g. when reader is pooled).
        contentHandler = null;
        executionContext = null;
    }
}

From source file:org.dhatim.yaml.handler.YamlEventStreamHandler.java

public void handle(EventHandler eventHandler, Iterable<Event> yamlEventStream) throws SAXException {

    Stack<String> elementNameStack = new Stack<String>();
    Stack<Type> typeStack = new Stack<Type>();

    boolean isNextElementName = true;
    boolean outputStructAsElement = false;
    for (Event e : yamlEventStream) {

        if (logger.isTraceEnabled()) {
            logger.trace("Event: " + e);
        }/* w w  w . j  a  v a  2 s .c  o m*/

        if (e.is(ID.DocumentStart)) {
            elementNameStack.push(documentName);

            outputStructAsElement = true;
        } else if (e.is(ID.Scalar)) {
            ScalarEvent es = (ScalarEvent) e;

            if (isNextElementName && !lastTypeIsArray(typeStack)) {
                String name = nameFormatter.format(es.getValue());

                if (logger.isTraceEnabled()) {
                    logger.trace("Element name: " + name);
                }

                elementNameStack.push(name);

                eventHandler.addNameEvent(es, name);

                isNextElementName = false;
            } else {
                String elementName = typeStack.peek() == Type.SEQUENCE ? arrayElementName
                        : elementNameStack.pop();

                eventHandler.addValueEvent(es, elementName, es.getValue());

                isNextElementName = true;
            }
        } else if (e.is(ID.MappingStart) || e.is(ID.SequenceStart)) {
            CollectionStartEvent cse = (CollectionStartEvent) e;

            if (outputStructAsElement) {
                String elementName = lastTypeIsArray(typeStack) ? arrayElementName : elementNameStack.peek();
                eventHandler.startStructureEvent(cse, elementName);
            }

            typeStack.push(e.is(ID.SequenceStart) ? Type.SEQUENCE : Type.MAPPING);

            outputStructAsElement = true;
            isNextElementName = true;
        } else if (e.is(ID.MappingEnd) || e.is(ID.SequenceEnd)) {
            typeStack.pop();

            boolean typeStackPeekIsArray = lastTypeIsArray(typeStack);

            if (!elementNameStack.empty() && !typeStackPeekIsArray) {
                eventHandler.endStructureEvent(e, elementNameStack.pop());
            }

            if (typeStackPeekIsArray) {
                eventHandler.endStructureEvent(e, arrayElementName);
            }

        } else if (e.is(ID.Alias)) {
            String elementName = lastTypeIsArray(typeStack) ? arrayElementName : elementNameStack.pop();

            eventHandler.addAliasEvent((AliasEvent) e, elementName);

            isNextElementName = true;
        }

    }
}

From source file:ca.mcgill.cs.swevo.qualyzer.editors.RTFDocumentProvider2.java

/**
 * Returns the set of tags at the top of the stack. Return an empty set if the stack is empty. This should never
 * occur, but some badly-formatted RTF documents seem to lead to this situation.
 * // w w  w  .j av  a  2 s  . c o m
 * @param state
 * @param pop
 * @return
 */
private Map<String, Integer> safeState(Stack<Map<String, Integer>> state, boolean pop) {
    if (!state.isEmpty()) {
        if (pop) {
            return state.pop();
        } else {
            return state.peek();
        }
    } else {
        gLogger.error("State was empty.");
        return new HashMap<String, Integer>();
    }
}

From source file:org.breizhbeans.thrift.tools.thriftmongobridge.protocol.TBSONUnstackedProtocol.java

@Override
public void writeMapEnd() throws TException {
    //System.out.println("writeMapEnd");
    // Collapse the map into the structure

    // Get the DBObject produced (the map)
    Stack<ThriftIO> thriftIOStack = threadSafeSIOStack.get();
    ThriftIO mapThriftIO = thriftIOStack.pop();

    // add {fieldName:value} to the current object
    ThriftFieldMetadata field = peekWriteField();

    ThriftIO documentThriftIO = thriftIOStack.peek();
    // write the document (hash)
    documentThriftIO.mongoIO.put(field.tfield.name, mapThriftIO.mongoIO);
    // write the secured (hash)
    if (documentThriftIO.securedMongoIO != null) {
        documentThriftIO.securedMongoIO.put(Short.toString(field.tfield.id), mapThriftIO.securedMongoIO);
    }/*from   w w  w . j av a  2s  .c om*/
}

From source file:com.blackducksoftware.integration.hub.detect.detector.pip.PipenvGraphParser.java

public PipParseResult parse(final String projectName, final String projectVersionName,
        final List<String> pipFreezeOutput, final List<String> pipenvGraphOutput, final String sourcePath) {
    final MutableMapDependencyGraph dependencyGraph = new MutableMapDependencyGraph();
    final Stack<Dependency> dependencyStack = new Stack<>();

    final Map<String, String[]> pipFreezeMap = pipFreezeOutput.stream()
            .map(line -> line.split(TOP_LEVEL_SEPARATOR)).filter(splitLine -> splitLine.length == 2)
            .collect(Collectors.toMap(splitLine -> splitLine[0].trim().toLowerCase(), splitLine -> splitLine));

    int lastLevel = -1;
    for (final String line : pipenvGraphOutput) {
        final int currentLevel = getLevel(line);
        final Optional<Dependency> parsedDependency = getDependencyFromLine(pipFreezeMap, line);

        if (!parsedDependency.isPresent()) {
            continue;
        }//www . j  a  v a2  s .c o  m

        final Dependency dependency = parsedDependency.get();

        if (currentLevel == lastLevel) {
            dependencyStack.pop();
        } else {
            for (; lastLevel >= currentLevel; lastLevel--) {
                dependencyStack.pop();
            }
        }

        if (dependencyStack.size() > 0) {
            dependencyGraph.addChildWithParent(dependency, dependencyStack.peek());
        } else {
            dependencyGraph.addChildrenToRoot(dependency);
        }

        lastLevel = currentLevel;
        dependencyStack.push(dependency);
    }

    if (!dependencyGraph.getRootDependencyExternalIds().isEmpty()) {
        final ExternalId projectExternalId = externalIdFactory.createNameVersionExternalId(Forge.PYPI,
                projectName, projectVersionName);
        final DetectCodeLocation codeLocation = new DetectCodeLocation.Builder(DetectCodeLocationType.PIP,
                sourcePath, projectExternalId, dependencyGraph).build();
        return new PipParseResult(projectName, projectVersionName, codeLocation);
    } else {
        return null;
    }
}

From source file:org.breizhbeans.thrift.tools.thriftmongobridge.protocol.TBSONUnstackedProtocol.java

private DBObject collapseIOStack() throws TException {
    // Get the DBObject produced
    Stack<ThriftIO> thriftIOStack = threadSafeSIOStack.get();
    ThriftIO thriftIO = thriftIOStack.pop();

    //System.out.println("Collapse thrift IO : " + thriftIO.toString());

    //Collapse// ww  w  .  ja v a  2s  . co m
    if (thriftIOStack.size() > 0) {
        ThriftIO lastThriftIO = thriftIOStack.peek();

        if (lastThriftIO.map) {
            // add {key:value} to the current object and reset the key
            lastThriftIO.mongoIO.put(lastThriftIO.key, thriftIO.mongoIO);
            lastThriftIO.key = null;
        } else if (lastThriftIO.list) {
            ((BasicDBList) lastThriftIO.mongoIO).add(thriftIO.mongoIO);
        } else {
            // Dont forget to collapse the secured wrap to the current object
            if (thriftIO.securedMongoIO != null) {
                thriftIO.mongoIO.put("securedwrap", thriftIO.securedMongoIO);
            }

            // add {fieldName:value} to the current object
            String fieldName = peekWriteField().tfield.name;
            lastThriftIO.mongoIO.put(fieldName, thriftIO.mongoIO);

        }
        return null;
    }

    // not collapsed
    // Dont forget to add the secured wrap
    if (thriftIO.securedMongoIO != null) {
        thriftIO.mongoIO.put("securedwrap", thriftIO.securedMongoIO);
    }
    return thriftIO.mongoIO;
}

From source file:org.sakaiproject.poll.service.impl.PollListManagerImpl.java

@SuppressWarnings("unchecked")
public String archive(String siteId, Document doc, Stack stack, String archivePath, List attachments) {
    log.debug("archive: poll " + siteId);
    // prepare the buffer for the results log
    StringBuilder results = new StringBuilder();

    // String assignRef = assignmentReference(siteId, SiteService.MAIN_CONTAINER);
    results.append("archiving " + getLabel() + " context " + Entity.SEPARATOR + siteId + Entity.SEPARATOR
            + SiteService.MAIN_CONTAINER + ".\n");

    // start with an element with our very own (service) name
    Element element = doc.createElement(PollListManager.class.getName());
    ((Element) stack.peek()).appendChild(element);
    stack.push(element);/*from w ww  .j  a v a  2s . c  om*/

    List pollsList = findAllPolls(siteId);
    log.debug("got list of " + pollsList.size() + " polls");
    for (int i = 0; pollsList.size() > i; i++) {
        try {
            Poll poll = (Poll) pollsList.get(i);
            log.info("got poll " + poll.getId());

            // archive this assignment
            Element el = poll.toXml(doc, stack);

            // since we aren't archiving votes too, don't worry about archiving the
            // soft-deleted options -- only "visible".
            List options = getVisibleOptionsForPoll(poll.getPollId());

            for (int q = 0; options.size() > q; q++) {
                Option opt = (Option) options.get(q);
                Element el2 = PollUtil.optionToXml(opt, doc, stack);
                el.appendChild(el2);
            }

            element.appendChild(el);
        } catch (Exception e) {
            e.printStackTrace();
        }

    } // while

    stack.pop();

    return results.toString();
}

From source file:org.apache.fop.fo.FONode.java

/**
 * Collect the sequence of delimited text ranges, where each new
 * range is pushed onto RANGES./*  w w w  .  ja va  2s  .c om*/
 * @param ranges a stack of delimited text ranges
 * @return the (possibly) updated stack of delimited text ranges
 */
public Stack collectDelimitedTextRanges(Stack ranges) {
    // if boundary before, then push new range
    if (isRangeBoundaryBefore()) {
        maybeNewRange(ranges);
    }
    // get current range, if one exists
    DelimitedTextRange currentRange;
    if (ranges.size() > 0) {
        currentRange = (DelimitedTextRange) ranges.peek();
    } else {
        currentRange = null;
    }
    // proceses this node
    ranges = collectDelimitedTextRanges(ranges, currentRange);
    // if boundary after, then push new range
    if (isRangeBoundaryAfter()) {
        maybeNewRange(ranges);
    }
    return ranges;
}

From source file:gr.abiss.calipso.wicket.customattrs.CustomAttributeUtils.java

/**
 * Parses the given user intput to create the custom attribute lookup values (options) and their translations, 
 * then add them to the given CustomAttribute.
 * @param optionsTextIput//  w  ww. j  a va 2  s .  c o  m
 * @param attribute
 * @param languages
 */
public static void parseOptionsIntoAttribute(Map<String, String> optionsTextIput, CustomAttribute attribute,
        List<Language> languages) {
    //logger.info("parseOptionsIntoAttribute, attribute: "+attribute);
    // add options
    attribute.setPersistedVersion(attribute.getVersion());
    attribute.setVersion(attribute.getVersion() + 1);
    attribute.removeAllLookupValues();
    List<CustomAttributeLookupValue> optionsList = new LinkedList<CustomAttributeLookupValue>();
    String languageId = null;
    for (Language language : languages) {
        if (languageId == null) {
            languageId = language.getId();
        }
        String input = optionsTextIput.get(language.getId());
        //logger.info("textAreaOptions.get(language.getId(): "+input);
        if (StringUtils.isNotBlank(input)) {
            Stack<CustomAttributeLookupValue> parents = new Stack<CustomAttributeLookupValue>();
            String[] lines = input.split("\\r?\\n");
            int listIndex = -1;
            for (int j = 0; j < lines.length; j++) {

                listIndex++;
                // count whitespace characters to determine level
                String line = lines[j];
                //logger.info("Reading option line: "+line);
                int countLevel = 1;
                int limit = line.length();
                for (int i = 0; i < limit; ++i) {
                    if (Character.isWhitespace(line.charAt(i))) {
                        ++countLevel;
                    } else {
                        break;
                    }
                }
                String translatedName = line.substring(countLevel - 1).trim();

                //logger.info("translatedName: "+translatedName);
                // build CustomAttributeLookupValue if it doesn't already exist
                CustomAttributeLookupValue lookupValue;
                if (language.getId().equalsIgnoreCase(languageId)) {
                    //logger.info("creating new lookupValue and adding to list index " + listIndex + " for " + translatedName);
                    lookupValue = new CustomAttributeLookupValue();
                    optionsList.add(lookupValue);
                } else {
                    //logger.info("trying to get lookupValue from list index " + listIndex + "for "+translatedName);
                    lookupValue = optionsList.get(listIndex);
                }
                lookupValue.setShowOrder(listIndex);
                if (language.getId().equalsIgnoreCase("en")) {
                    lookupValue.setName(translatedName);
                    lookupValue.setValue(translatedName);
                }
                lookupValue.setLevel(countLevel);

                // fix parent/child
                while ((!parents.isEmpty()) && parents.peek().getLevel() >= lookupValue.getLevel()) {
                    parents.pop();
                }
                // pile it
                if (lookupValue.getLevel() > 1) {
                    //logger.info("Adding child "+lookupValue.getName() + "to parent " +parents.peek());
                    parents.peek().addChild(lookupValue);
                }
                parents.push(lookupValue);
                // add the translation
                //logger.info("Adding lookup value "+language.getId()+" translation: "+translatedName);
                lookupValue.addNameTranslation(language.getId(), translatedName);
                //logger.info("translations afre now: "+lookupValue.getNameTranslations());

            }
        }
        //Set<CustomAttributeLookupValue> lookupValueSet = new HashSet<CustomAttributeLookupValue>();
        //lookupValueSet.addAll(optionsList);

    }
    // update attribute lookup values
    attribute.removeAllLookupValues();
    /*
    List<CustomAttributeLookupValue> toRemove = new LinkedList<CustomAttributeLookupValue>();
    for(CustomAttributeLookupValue value : attribute.getAllowedLookupValues()){
       toRemove.add(value);
    }
    attribute.removeAll(toRemove);*/
    for (CustomAttributeLookupValue value : optionsList) {
        //logger.info("Adding lookupValue  with translations: "+value.getNameTranslations());
        attribute.addAllowedLookupValue(value);
    }
    //logger.info("Added lookup values: "+attribute.getAllowedLookupValues());
}