Example usage for java.util Stack push

List of usage examples for java.util Stack push

Introduction

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

Prototype

public E push(E item) 

Source Link

Document

Pushes an item onto the top of this stack.

Usage

From source file:com.amalto.core.storage.StorageMetadataUtils.java

private static void _path(ComplexTypeMetadata type, FieldMetadata target, Stack<FieldMetadata> path,
        Set<ComplexTypeMetadata> processedTypes, boolean includeReferences) {
    // Various optimizations for very simple cases
    if (type == null) {
        throw new IllegalArgumentException("Origin can not be null");
    }/*from   w  ww  .  j  a  v  a 2  s.  co m*/
    if (target == null) {
        throw new IllegalArgumentException("Target field can not be null");
    }
    if (Storage.PROJECTION_TYPE.equals(type.getName()) && type.hasField(target.getName())) {
        path.push(type.getField(target.getName()));
    }
    if (target.getContainingType() instanceof ContainedComplexTypeMetadata) {
        String targetPath = target.getPath();
        if (type.hasField(targetPath)) {
            StringTokenizer tokenizer = new StringTokenizer(targetPath, "/"); //$NON-NLS-1$
            StringBuilder currentPath = new StringBuilder();
            while (tokenizer.hasMoreTokens()) {
                currentPath.append(tokenizer.nextToken()).append('/');
                path.add(type.getField(currentPath.toString()));
            }
            return;
        }
    }
    //
    if (processedTypes.contains(type)) {
        return;
    }
    processedTypes.add(type);
    Collection<FieldMetadata> fields = type.getFields();
    for (FieldMetadata current : fields) {
        path.push(current);
        if (current.equals(target)) {
            return;
        }
        if (current instanceof ContainedTypeFieldMetadata) {
            ComplexTypeMetadata containedType = ((ContainedTypeFieldMetadata) current).getContainedType();
            _path(containedType, target, path, processedTypes, includeReferences);
            if (path.peek().equals(target)) {
                return;
            }
            for (ComplexTypeMetadata subType : containedType.getSubTypes()) {
                for (FieldMetadata field : subType.getFields()) {
                    if (field.getDeclaringType() == subType) {
                        _path(subType, target, path, processedTypes, includeReferences);
                        if (path.peek().equals(target)) {
                            return;
                        }
                    }
                }
            }
        } else if (current instanceof ReferenceFieldMetadata) {
            if (includeReferences) {
                ComplexTypeMetadata referencedType = ((ReferenceFieldMetadata) current).getReferencedType();
                _path(referencedType, target, path, processedTypes, true);
                if (path.peek().equals(target)) {
                    return;
                }
                for (ComplexTypeMetadata subType : referencedType.getSubTypes()) {
                    for (FieldMetadata field : subType.getFields()) {
                        if (field.getDeclaringType() == subType) {
                            _path(subType, target, path, processedTypes, true);
                            if (path.peek().equals(target)) {
                                return;
                            }
                        }
                    }
                }
            }
        }
        path.pop();
    }
}

From source file:gov.nih.nci.calims2.ui.common.document.DocumentFormTest.java

/**
 * Test the controller getSubmittedEntity method.
 * @throws Exception /*from w  w  w .  jav  a2  s .  c  om*/
 */
@SuppressWarnings("unchecked")
@Test
public void testGetSubmittedEntity() throws Exception {
    DocumentForm form = new DocumentForm();
    form.setStatus(DocumentStatus.DEFAULT.name());
    Stack<StackFrame> context = FlowContextHolder.newContext();
    StackFrame frame = new BaseStackFrame();
    context.push(frame);
    frame.addAttribute("persistentClass", persistentClass);
    frame.addAttribute("id", new Long(1));
    Document entity = form.getSubmittedEntity();
    assertEquals("Wrong status in the entity", DocumentStatus.DEFAULT, entity.getStatus());
    EntityWithId result = (EntityWithId) PropertyUtils.getProperty(entity, propertyName);
    CRUDFormAssert.assertEntity((Class<EntityWithId>) persistentClass, result, 1L);
}

From source file:com.pinterest.rocksplicator.controller.tasks.ChainedTask.java

@Override
public void process(Context ctx) throws Exception {
    long id = ctx.getId();
    final String cluster = ctx.getCluster();
    final String worker = ctx.getWorker();
    final TaskQueue taskQueue = ctx.getTaskQueue();

    Stack<TaskBase> tasks = new Stack<>();
    tasks.push(getParameter().getT2());
    tasks.push(getParameter().getT1());//from  w w w  . j  a  v  a  2  s.  c  o m

    while (!tasks.isEmpty()) {
        TaskBase taskBase = tasks.pop();
        AbstractTask task = TaskFactory.getWorkerTask(taskBase);
        if (task == null) {
            taskQueue.failTask(id, "Failed to instantiate task " + taskBase.name);
            return;
        } else if (task instanceof ChainedTask) {
            ChainedTask chainedTask = (ChainedTask) task;
            tasks.push(chainedTask.getParameter().getT2());
            tasks.push(chainedTask.getParameter().getT1());
        } else {
            LocalAckTaskQueue lq = new LocalAckTaskQueue(taskQueue);
            ctx = new Context(id, cluster, lq, worker);
            try {
                task.process(ctx);
            } catch (Exception ex) {
                LOG.error("Unexpected exception from task: {} in task chain.", task.getName(), ex);
                lq.failTask(id, ex.getMessage());
            }

            LocalAckTaskQueue.State state = lq.getState();
            if (state.state == LocalAckTaskQueue.State.StateName.UNFINISHED) {
                LOG.error("Task {} finished processing without ack", id);
                return;
            } else if (state.state == LocalAckTaskQueue.State.StateName.FAILED) {
                LOG.error("Task {} failed with reason: {}. Abort the task chain.", id, state.output);
                taskQueue.failTask(id, state.output);
                return;
            } else if (tasks.isEmpty()) {
                LOG.info("Finished processing chained task");
                taskQueue.finishTask(id, state.output);
                return;
            }

            long nextId = taskQueue.finishTaskAndEnqueueRunningTask(id, state.output, tasks.peek(), worker);
            if (nextId < 0) {
                LOG.error("Failed to finish task {} and enqueue new task {}", id, tasks.peek());
                return;
            } else {
                id = nextId;
            }
        }
    }

}

From source file:gov.nih.nci.calims2.ui.administration.contactinformation.ContactInformationFormTest.java

/**
 * Test the controller getSubmittedEntity method.
 * @throws Exception /*  w ww  .j av  a2 s .com*/
 */
@SuppressWarnings("unchecked")
@Test
public void testGetSubmittedEntity() throws Exception {
    ContactInformationForm form = new ContactInformationForm();
    CRUDFormTestHelper.setNotes(form);
    form.setStatus(ContactInformationStatus.ACTIVE.name());
    form.setTypeId(1L);
    Stack<StackFrame> context = FlowContextHolder.newContext();
    StackFrame frame = new BaseStackFrame();
    context.push(frame);
    frame.addAttribute("persistentClass", persistentClass);
    frame.addAttribute("id", new Long(1));
    ContactInformation entity = form.getSubmittedEntity();
    assertNotNull("No submitted Entity", entity);
    CRUDFormTestHelper.assertNotes(entity);
    assertEquals("Wrong status in the entity", ContactInformationStatus.ACTIVE, entity.getStatus());
    CRUDFormAssert.assertEntity(Type.class, entity.getType(), 1L);
    EntityWithId result = (EntityWithId) PropertyUtils.getProperty(entity, propertyName);
    CRUDFormAssert.assertEntity((Class<EntityWithId>) persistentClass, result, 1L);
}

From source file:com.handcraftedbits.bamboo.plugin.go.parser.GoTestParser.java

@SuppressWarnings("unchecked")
public static List<PackageTestResults> parseTests(final InputStream input) throws Exception {
    final List<String> lines = IOUtils.readLines(input, "UTF-8");
    final List<PackageTestResults> packageTestResults = new LinkedList<>();
    final Stack<SingleTestResult> testResults = new Stack<>();

    for (final String line : lines) {
        // A test has finished.  Parse it out and push it on the stack until we know which package it belongs to.

        if (line.startsWith("---")) {
            final Matcher matcher = GoTestParser.patternTestFinish.matcher(line);

            if (matcher.matches()) {
                TestStatus status = null;

                switch (matcher.group(1)) {
                case "FAIL": {
                    status = TestStatus.FAILED;

                    break;
                }//from  ww  w . ja  v a2  s.c  om

                case "PASS": {
                    status = TestStatus.PASSED;

                    break;
                }

                case "SKIP": {
                    status = TestStatus.SKIPPED;

                    break;
                }
                }

                if (status != null) {
                    testResults.push(new SingleTestResult(matcher.group(2), status,
                            Double.parseDouble(matcher.group(3))));
                }
            }
        }

        // This is either noise or a finished set of package tests.

        else {
            final Matcher matcher = GoTestParser.patternPackageFinish.matcher(line);

            // We have a finished set of package tests, so create the model for it and clear the stack of tests.

            if (matcher.matches()) {
                final PackageTestResults packageResults = new PackageTestResults(matcher.group(2));

                // In this case, either the go test run did not specify -v or there are no tests in the
                // package.  We'll create a single "AllTests" test and assign it the correct status.  In the
                // case of no tests existing for the package, the status will be "skipped".

                if (testResults.empty()) {
                    double duration = 0.0d;
                    final String durationStr = matcher.group(3);
                    TestStatus testStatus = TestStatus.SKIPPED;

                    switch (matcher.group(1)) {
                    case "FAIL": {
                        testStatus = TestStatus.FAILED;

                        break;
                    }

                    case "ok  ": {
                        testStatus = TestStatus.PASSED;

                        break;
                    }
                    }

                    // If there are tests in the package, we should be able to extract the duration.

                    if (durationStr.endsWith("s")) {
                        duration = Double.parseDouble(durationStr.substring(0, durationStr.length() - 1));
                    }

                    packageResults.addTestResult(new SingleTestResult("AllTests", testStatus, duration));
                }

                while (!testResults.empty()) {
                    packageResults.addTestResult(testResults.pop());
                }

                packageTestResults.add(packageResults);
            }
        }
    }

    IOUtils.closeQuietly(input);

    return packageTestResults;
}

From source file:com.madrobot.di.wizard.json.JSONSerializer.java

/**
 * Serializes the objType into valid JSON format <br/>
 * //from   ww w . j  av a 2s .c o m
 * If there is an error while serializes, if possible it will try to ignore it, otherwise returns a null value.
 * 
 * @param objType
 *            Java Object to write JSON to
 * 
 * @return String valid json string
 * 
 * @see #serializer(JSONObject, Stack)
 */
public String serializer(final Object objType) throws JSONException {

    Stack<Object> stack = new Stack<Object>();
    stack.push(objType);

    JSONObject jsonObject = new JSONObject();

    serializer(jsonObject, stack);

    return jsonObject.toString();
}

From source file:com.blogspot.jadecalyx.webtools.jcPageObjectHelper.java

private Stack<jcPageObjectSet> expandLookupDetails(List<jcPageObjectSet> returnSet,
        List<jcPageObjectSet> incomingSet) {
    if (returnSet == null) {
        returnSet = new Stack<>();
    }/*from  w w w .  j  av a  2 s  .c om*/
    while (incomingSet.size() > 0) {
        jcPageObjectSet currSet = incomingSet.get(incomingSet.size() - 1);
        incomingSet.remove(incomingSet.size() - 1);
        if (currSet.GetType().equals("css")) {
            returnSet.add(currSet);
        } else {
            if (currSet.GetType().equals("handle")) {
                List<jcPageObjectSet> expandedSet = GetLookupDetails(currSet.GetDetails());
                while (expandedSet.size() > 0) {
                    returnSet.add(expandedSet.get(expandedSet.size() - 1));
                    expandedSet.remove(expandedSet.size() - 1);
                }
            }
        }
    }
    Stack<jcPageObjectSet> orderedReturnSet = new Stack<>();
    while (returnSet.size() > 0) {
        orderedReturnSet.push(returnSet.get(returnSet.size() - 1));
        returnSet.remove(returnSet.size() - 1);
    }
    //return orderedReturnSet;
    return orderedReturnSet;
}

From source file:edu.umn.cs.spatialHadoop.nasa.StockQuadTree.java

/**
 * Make a path relative to another path by removing all common ancestors
 * @param parent/*from  w  ww  .java  2 s .co m*/
 * @param descendant
 * @return
 */
private static Path makeRelative(Path parent, Path descendant) {
    Stack<String> components = new Stack<String>();
    while (descendant.depth() > parent.depth()) {
        components.push(descendant.getName());
        descendant = descendant.getParent();
    }
    if (!descendant.equals(parent))
        throw new RuntimeException("descendant not a child of parent");
    if (components.isEmpty())
        return new Path(".");
    Path relative = new Path(components.pop());
    while (!components.isEmpty())
        relative = new Path(relative, components.pop());
    return relative;
}

From source file:com.galenframework.parser.IndentationStructureParser.java

public List<StructNode> parse(InputStream stream, String source) throws IOException {
    Stack<IndentationNode> nodeStack = new Stack<IndentationNode>();

    StructNode rootNode = new StructNode();
    nodeStack.push(new IndentationNode(-1, rootNode, null));

    List<String> lines = IOUtils.readLines(stream);

    int lineNumber = 0;
    for (String line : lines) {
        lineNumber++;//from w  w  w.  j a  va  2 s.  c o m
        if (isProcessable(line)) {
            processLine(nodeStack, line, lineNumber, source);
        }
    }

    return rootNode.getChildNodes();
}

From source file:org.bpmscript.web.view.JavascriptView.java

/**
 * @see org.springframework.web.servlet.view.AbstractView#renderMergedOutputModel(java.util.Map, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *//* w  ww .j  a  va2 s  .  c  o m*/
@SuppressWarnings("unchecked")
@Override
protected void renderMergedTemplateModel(Map model, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    Locale locale = RequestContextUtils.getLocale(request);
    Context cx = new ContextFactory().enterContext();
    try {
        // create scripting environment (i.e. load everything)
        ScriptableObject scope = new Global(cx);
        cx.putThreadLocal(Global.LIBRARY_ASSOCIATION_QUEUE, libraryAssociationQueue);
        ScriptableObject.putProperty(scope, "log", Context.javaToJS(log, scope));
        ScriptableObject.putProperty(scope, "request", Context.javaToJS(request, scope));
        ScriptableObject.putProperty(scope, "response", Context.javaToJS(response, scope));
        ScriptableObject.putProperty(scope, "base", Context.javaToJS(request.getContextPath(), scope));
        ScriptableObject.putProperty(scope, "locale", Context.javaToJS(locale, scope));
        Set<Map.Entry> entrySet = model.entrySet();
        for (Map.Entry<String, Object> entry : entrySet) {
            ScriptableObject.putProperty(scope, entry.getKey(),
                    mapToJsConverter.convertObject(scope, entry.getValue()));
        }
        Stack<String> sourceStack = new Stack<String>();
        sourceStack.push(configResource);
        cx.putThreadLocal(Global.SOURCE_STACK, sourceStack);
        if (libraryAssociationQueue != null) {
            cx.putThreadLocal(Global.LIBRARY_ASSOCIATION_QUEUE, libraryAssociationQueue);
        }
        Script configScript = javascriptSourceCache.getScript(
                new String(StreamUtils
                        .getBytes(getApplicationContext().getResource(configResource).getInputStream())),
                configResource);
        configScript.exec(cx, scope);
        sourceStack.pop();

        sourceStack.push(getUrl());
        Script script = javascriptSourceCache.getScript(
                new String(
                        StreamUtils.getBytes(getApplicationContext().getResource(getUrl()).getInputStream())),
                getUrl());
        Object result = script.exec(cx, scope);
        response.getWriter().write(result.toString());
        // not sure if this is necessary
        response.getWriter().flush();
    } finally {
        Context.exit();
    }
}