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:com.usefullc.platform.common.filter.WebCommonFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
    // String url = req.getRequestURL().toString();
    String url = req.getRequestURI();
    if (canExcute) {

        Stack<ActionHandlerInterceptor> actionStack = new Stack<ActionHandlerInterceptor>();
        ActionHandler actionHandler = new ActionHandler(req, res);
        for (ActionHandlerInterceptor interceptor : interceptorList) {
            String urlPattern = interceptor.getUrlPattern();
            // ?url
            Boolean state = PatternMatchUtils.simpleMatch(urlPattern, url);
            if (!state) {
                continue;
            }//from   w w w .  j a v a2 s .  c  o  m
            interceptor.beforeHandler(actionHandler);

            // 
            actionStack.push(interceptor);

        }
        boolean actionState = false;
        try {
            chain.doFilter(request, response);
            actionState = true;
        } catch (Exception e) {
            StringWriter sw = new StringWriter();
            PrintWriter print = new PrintWriter(sw);
            e.printStackTrace(print);
            actionHandler.setErrMsg(sw.toString());
        } finally {
            // 
            actionHandler.setState(actionState);
            while (!actionStack.isEmpty()) {
                ActionHandlerInterceptor interceptor = actionStack.pop();
                interceptor.afterHandler(actionHandler);
            }

        }

    } else {
        chain.doFilter(request, response);
    }

}

From source file:edu.umn.msi.tropix.persistence.service.impl.TropixObjectServiceImpl.java

public void addToSharedFolder(final Iterable<String> inputObjectIds, final String inputFolderId,
        final boolean recursive) {
    final Stack<String> objectIds = new Stack<String>();
    final Stack<String> virtualFolderIds = new Stack<String>();

    for (final String inputObjectId : inputObjectIds) {
        objectIds.add(inputObjectId);/*from www .  j a  v  a 2s . co m*/
        virtualFolderIds.add(inputFolderId);
    }

    while (!objectIds.isEmpty()) {
        final String objectId = objectIds.pop();
        final String folderId = virtualFolderIds.pop();
        final TropixObject object = getTropixObjectDao().loadTropixObject(objectId);
        if (!(object instanceof Folder)) {
            getTropixObjectDao().addToVirtualFolder(folderId, objectId);
            TreeUtils.applyPermissionChange(getTropixObjectDao().loadTropixObject(objectId),
                    new CopyVirtualPermissions(folderId));
        } else {
            final Folder sourceFolder = (Folder) object;
            final VirtualFolder destinationFolder = new VirtualFolder();
            destinationFolder.setName(sourceFolder.getName());
            destinationFolder.setDescription(sourceFolder.getDescription());
            // System.out.println(String.format("Destination is %s", folderId));
            final String destinationId = createNewChildVirtualFolder(folderId, destinationFolder).getId();
            for (final TropixObject child : sourceFolder.getContents()) {
                objectIds.add(child.getId());
                virtualFolderIds.add(destinationId);
            }
        }
    }
}

From source file:com.gargoylesoftware.htmlunit.activex.javascript.msxml.XMLHTTPRequest.java

/**
 * Sends an HTTP request to the server and receives a response.
 * @param body the body of the message being sent with the request.
 *///from w  w w  .j  av  a2s. com
@JsxFunction
public void send(final Object body) {
    if (webRequest_ == null) {
        setState(STATE_DONE, Context.getCurrentContext());
        return;
    }
    if (sent_) {
        throw Context.reportRuntimeError("Unspecified error (request already sent).");
    }
    sent_ = true;

    prepareRequest(body);

    // quite strange but IE seems to fire state loading twice
    setState(STATE_OPENED, Context.getCurrentContext());

    final WebClient client = getWindow().getWebWindow().getWebClient();
    final AjaxController ajaxController = client.getAjaxController();
    final HtmlPage page = (HtmlPage) getWindow().getWebWindow().getEnclosedPage();
    final boolean synchron = ajaxController.processSynchron(page, webRequest_, async_);
    if (synchron) {
        doSend(Context.getCurrentContext());
    } else {
        // Create and start a thread in which to execute the request.
        final Scriptable startingScope = getWindow();
        final ContextFactory cf = client.getJavaScriptEngine().getContextFactory();
        final ContextAction action = new ContextAction() {
            @Override
            public Object run(final Context cx) {
                // KEY_STARTING_SCOPE maintains a stack of scopes
                @SuppressWarnings("unchecked")
                Stack<Scriptable> stack = (Stack<Scriptable>) cx
                        .getThreadLocal(JavaScriptEngine.KEY_STARTING_SCOPE);
                if (null == stack) {
                    stack = new Stack<>();
                    cx.putThreadLocal(JavaScriptEngine.KEY_STARTING_SCOPE, stack);
                }
                stack.push(startingScope);

                try {
                    doSend(cx);
                } finally {
                    stack.pop();
                }
                return null;
            }
        };
        final JavaScriptJob job = BackgroundJavaScriptFactory.theFactory().createJavascriptXMLHttpRequestJob(cf,
                action);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Starting XMLHTTPRequest thread for asynchronous request");
        }
        jobID_ = getWindow().getWebWindow().getJobManager().addJob(job, page);
    }
}

From source file:edu.unc.lib.dl.services.FolderManager.java

/**
 * Given a repository path string, creates any folders that do not yet exist along this path.
 * //from   w  w w. j a va 2  s  . c o  m
 * @param path
 *           the desired folder path
 * @throws IngestException
 *            if the path cannot be created
 */
public PID createPath(String path, String owner, String user) throws IngestException {
    log.debug("attempting to create path: " + path);
    if (path.endsWith("/")) {
        path = path.substring(0, path.length() - 1);
    }
    if (!PathUtil.isValidPathString(path)) {
        throw new IngestException("The proposed path is not valid: " + path);
    }
    List<String> slugs = new ArrayList<String>();
    slugs.addAll(Arrays.asList(path.split("/")));
    slugs.remove(0);
    Stack<String> createFolders = new Stack<String>();
    String containerPath = null;
    for (int i = slugs.size(); i >= 0; i--) {
        String test = "/" + StringUtils.join(slugs.subList(0, i), "/");
        PID pid = this.getTripleStoreQueryService().fetchByRepositoryPath(test);
        if (pid == null) {
            // does not exist yet, must create it
            createFolders.add(slugs.get(i - 1));
        } else {
            List<URI> types = this.getTripleStoreQueryService().lookupContentModels(pid);
            if (!types.contains(ContentModelHelper.Model.CONTAINER.getURI())) {
                StringBuffer s = new StringBuffer();
                for (URI type : types) {
                    s.append(type.toString()).append("\t");
                }
                throw new IngestException("The object at the path '" + test
                        + "' is not a folder.  It has these content models:\n" + s.toString());
            }
            containerPath = test;
            break;
        }
    }

    // add folders
    PID lastpid = null;
    while (createFolders.size() > 0) {
        String slug = createFolders.pop();
        SingleFolderSIP sip = new SingleFolderSIP();
        PID containerPID = this.getTripleStoreQueryService().fetchByRepositoryPath(containerPath);
        sip.setContainerPID(containerPID);
        if ("/".equals(containerPath)) {
            containerPath = containerPath + slug;
        } else {
            containerPath = containerPath + "/" + slug;
        }
        sip.setSlug(slug);
        sip.setAllowIndexing(true);
        DepositRecord record = new DepositRecord(user, owner, DepositMethod.Unspecified);
        record.setMessage("creating a new folder path");
        IngestResult result = this.getDigitalObjectManager().addWhileBlocking(sip, record);
        lastpid = result.derivedPIDs.iterator().next();
    }
    return lastpid;
}

From source file:edu.uci.ics.asterix.optimizer.rules.IntroduceSecondaryIndexInsertDeleteRule.java

public static ARecordType createEnforcedType(ARecordType initialType, Index index)
        throws AsterixException, AlgebricksException {
    ARecordType enforcedType = initialType;
    for (int i = 0; i < index.getKeyFieldNames().size(); i++) {
        try {//from   ww w .ja  va  2s.  co  m
            Stack<Pair<ARecordType, String>> nestedTypeStack = new Stack<Pair<ARecordType, String>>();
            List<String> splits = index.getKeyFieldNames().get(i);
            ARecordType nestedFieldType = enforcedType;
            boolean openRecords = false;
            String bridgeName = nestedFieldType.getTypeName();
            int j;
            //Build the stack for the enforced type
            for (j = 1; j < splits.size(); j++) {
                nestedTypeStack.push(new Pair<ARecordType, String>(nestedFieldType, splits.get(j - 1)));
                bridgeName = nestedFieldType.getTypeName();
                nestedFieldType = (ARecordType) enforcedType.getSubFieldType(splits.subList(0, j));
                if (nestedFieldType == null) {
                    openRecords = true;
                    break;
                }
            }
            if (openRecords == true) {
                //create the smallest record
                enforcedType = new ARecordType(splits.get(splits.size() - 2),
                        new String[] { splits.get(splits.size() - 1) },
                        new IAType[] { AUnionType.createNullableType(index.getKeyFieldTypes().get(i)) }, true);
                //create the open part of the nested field
                for (int k = splits.size() - 3; k > (j - 2); k--) {
                    enforcedType = new ARecordType(splits.get(k), new String[] { splits.get(k + 1) },
                            new IAType[] { AUnionType.createNullableType(enforcedType) }, true);
                }
                //Bridge the gap
                Pair<ARecordType, String> gapPair = nestedTypeStack.pop();
                ARecordType parent = gapPair.first;

                IAType[] parentFieldTypes = ArrayUtils.addAll(parent.getFieldTypes().clone(),
                        new IAType[] { AUnionType.createNullableType(enforcedType) });
                enforcedType = new ARecordType(bridgeName,
                        ArrayUtils.addAll(parent.getFieldNames(), enforcedType.getTypeName()), parentFieldTypes,
                        true);

            } else {
                //Schema is closed all the way to the field
                //enforced fields are either null or strongly typed
                enforcedType = new ARecordType(nestedFieldType.getTypeName(),
                        ArrayUtils.addAll(nestedFieldType.getFieldNames(), splits.get(splits.size() - 1)),
                        ArrayUtils.addAll(nestedFieldType.getFieldTypes(),
                                AUnionType.createNullableType(index.getKeyFieldTypes().get(i))),
                        nestedFieldType.isOpen());
            }

            //Create the enforcedtype for the nested fields in the schema, from the ground up
            if (nestedTypeStack.size() > 0) {
                while (!nestedTypeStack.isEmpty()) {
                    Pair<ARecordType, String> nestedTypePair = nestedTypeStack.pop();
                    ARecordType nestedRecType = nestedTypePair.first;
                    IAType[] nestedRecTypeFieldTypes = nestedRecType.getFieldTypes().clone();
                    nestedRecTypeFieldTypes[nestedRecType
                            .findFieldPosition(nestedTypePair.second)] = enforcedType;
                    enforcedType = new ARecordType(nestedRecType.getTypeName(), nestedRecType.getFieldNames(),
                            nestedRecTypeFieldTypes, nestedRecType.isOpen());
                }
            }

        } catch (AsterixException e) {
            throw new AlgebricksException(
                    "Cannot enforce typed fields " + StringUtils.join(index.getKeyFieldNames()), e);
        } catch (IOException e) {
            throw new AsterixException(e);
        }
    }
    return enforcedType;
}

From source file:com.espertech.esper.rowregex.EventRowRegexNFAView.java

private void print(List<RegexNFAState> states, PrintWriter writer, int indent,
        Stack<RegexNFAState> currentStack) {

    for (RegexNFAState state : states) {
        indent(writer, indent);//from w w  w.j  a  v a2  s  .co  m
        if (currentStack.contains(state)) {
            writer.println("(self)");
        } else {
            writer.println(printState(state));

            currentStack.push(state);
            print(state.getNextStates(), writer, indent + 4, currentStack);
            currentStack.pop();
        }
    }
}

From source file:gdt.jgui.entity.query.JQueryPanel.java

/**
 * Execute the response locator./*  w  w  w  . ja va  2  s.c o m*/
 * @param console the main console.
 * @param locator$ the response locator.
 * 
 */
@Override
public void response(JMainConsole console, String locator$) {
    try {
        Properties locator = Locator.toProperties(locator$);
        String action$ = locator.getProperty(JRequester.REQUESTER_ACTION);
        if (ACTION_CREATE_QUERY.equals(action$)) {
            String entihome$ = locator.getProperty(Entigrator.ENTIHOME);
            String entityKey$ = locator.getProperty(EntityHandler.ENTITY_KEY);
            String text$ = locator.getProperty(JTextEditor.TEXT);
            Entigrator entigrator = console.getEntigrator(entihome$);
            Sack query = entigrator.ent_new("query", text$);
            query = entigrator.ent_assignProperty(query, "query", query.getProperty("label"));
            query.putAttribute(new Core(null, "icon", "query.png"));

            query.createElement("fhandler");
            query.putElementItem("fhandler", new Core(null, QueryHandler.class.getName(), null));
            query.putElementItem("fhandler", new Core(null, FolderHandler.class.getName(), null));
            query.createElement("jfacet");
            query.putElementItem("jfacet", new Core(JFolderFacetAddItem.class.getName(),
                    FolderHandler.class.getName(), JFolderFacetOpenItem.class.getName()));
            query.putElementItem("jfacet",
                    new Core(null, QueryHandler.class.getName(), JQueryFacetOpenItem.class.getName()));
            entigrator.save(query);
            entigrator.ent_assignProperty(query, "query", text$);
            entigrator.ent_assignProperty(query, "folder", text$);
            entigrator.saveHandlerIcon(getClass(), "query.png");
            entigrator.saveHandlerIcon(JEntitiesPanel.class, "query.png");
            entityKey$ = query.getKey();
            File folderHome = new File(entihome$ + "/" + entityKey$);
            if (!folderHome.exists())
                folderHome.mkdir();
            createSource(entihome$, entityKey$);
            createProjectFile(entihome$, entityKey$);
            createClasspathFile(entihome$, entityKey$);
            //createClass(entihome$,entityKey$);
            JQueryPanel qp = new JQueryPanel();
            String qpLocator$ = qp.getLocator();
            qpLocator$ = Locator.append(qpLocator$, Entigrator.ENTIHOME, entihome$);
            qpLocator$ = Locator.append(qpLocator$, EntityHandler.ENTITY_KEY, entityKey$);
            JEntityPrimaryMenu.reindexEntity(console, qpLocator$);
            Stack<String> s = console.getTrack();
            s.pop();
            console.setTrack(s);
            JConsoleHandler.execute(console, qpLocator$);
            return;
        }
    } catch (Exception e) {
        LOGGER.severe(e.toString());
    }

}

From source file:ca.weblite.codename1.ios.CodenameOneIOSBuildTask.java

/**
 * Based on https://github.com/shannah/cn1/blob/master/Ports/iOSPort/xmlvm/src/xmlvm/org/xmlvm/proc/out/build/XCodeFile.java
 * @param template/* w  w w  . ja v  a 2  s  .c o  m*/
 * @param filter 
 */
private String injectFilesIntoXcodeProject(String template, File[] files) {

    int nextid = 0;
    Pattern idPattern = Pattern.compile(" (\\d+) ");
    Matcher m = idPattern.matcher(template);
    while (m.find()) {
        int curr = Integer.parseInt(m.group(1));
        if (curr > nextid) {
            nextid = curr;
        }
    }
    nextid++;

    StringBuilder filerefs = new StringBuilder();
    StringBuilder buildrefs = new StringBuilder();
    StringBuilder display = new StringBuilder();
    StringBuilder source = new StringBuilder();
    StringBuilder resource = new StringBuilder();

    for (File f : files) {
        String fname = f.getName();
        if (template.indexOf(" " + fname + " ") >= 0) {
            continue;
        }
        FileResource fres = new FileResource(fname);
        if (f.exists()) {
            filerefs.append("\t\t").append(nextid);
            filerefs.append(" /* ").append(fname).append(" */");
            filerefs.append(" = { isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = ");
            filerefs.append(fres.type).append("; path = \"");
            filerefs.append(fname).append("\"; sourceTree = \"<group>\"; };");
            filerefs.append('\n');

            display.append("\t\t\t\t").append(nextid);
            display.append(" /* ").append(fname).append(" */");
            display.append(",\n");

            if (fres.isBuildable) {
                int fileid = nextid;
                nextid++;
                buildrefs.append("\t\t").append(nextid);
                buildrefs.append(" /* ").append(fname);
                buildrefs.append(" in ").append(fres.isSource ? "Sources" : "Resources");
                buildrefs.append(" */ = {isa = PBXBuildFile; fileRef = ").append(fileid);
                buildrefs.append(" /* ").append(fname);
                buildrefs.append(" */; };\n");

                if (fres.isSource) {
                    source.append("\t\t\t\t").append(nextid);
                    source.append(" /* ").append(fname).append(" */");
                    source.append(",\n");
                }
            }
            nextid++;
        }
    }
    String data = template;
    data = data.replace("/* End PBXFileReference section */",
            filerefs.toString() + "/* End PBXFileReference section */");
    data = data.replace("/* End PBXBuildFile section */",
            buildrefs.toString() + "/* End PBXBuildFile section */");

    // The next two we probably shouldn't do by regex because there is no clear pattern.
    Stack<String> buffer = new Stack<String>();

    Stack<String> backtrackStack = new Stack<String>();

    Scanner scanner = new Scanner(data);
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        if (line.indexOf("/* End PBXSourcesBuildPhase section */") >= 0) {
            // Found the end, let's backtrack
            while (!buffer.isEmpty()) {
                String l = buffer.pop();
                backtrackStack.push(l);
                if (");".equals(l.trim())) {
                    // This is the closing of the sources list
                    // we can insert the sources here
                    buffer.push(source.toString());
                    while (!backtrackStack.isEmpty()) {
                        buffer.push(backtrackStack.pop());
                    }
                    break;
                }
            }
        } else if (line.indexOf("name = Application;") >= 0) {
            while (!buffer.isEmpty()) {
                String l = buffer.pop();
                backtrackStack.push(l);
                if (");".equals(l.trim())) {
                    buffer.push(display.toString());
                    while (!backtrackStack.isEmpty()) {
                        buffer.push(backtrackStack.pop());
                    }
                    break;
                }
            }
        }
        buffer.push(line);
    }
    StringBuilder sb = new StringBuilder();
    String[] lines = buffer.toArray(new String[0]);
    for (String line : lines) {
        sb.append(line).append("\n");
    }
    data = sb.toString();
    return data;
}

From source file:org.apache.atlas.repository.graph.GraphHelper.java

/**
 * Get the GUIDs and vertices for all composite entities owned/contained by the specified root entity AtlasVertex.
 * The graph is traversed from the root entity through to the leaf nodes of the containment graph.
 *
 * @param entityVertex the root entity vertex
 * @return set of VertexInfo for all composite entities
 * @throws AtlasException/*from w ww.ja  v  a  2 s.  co  m*/
 */
public Set<VertexInfo> getCompositeVertices(AtlasVertex entityVertex) throws AtlasException {
    Set<VertexInfo> result = new HashSet<>();
    Stack<AtlasVertex> vertices = new Stack<>();
    vertices.push(entityVertex);
    while (vertices.size() > 0) {
        AtlasVertex vertex = vertices.pop();
        String typeName = GraphHelper.getTypeName(vertex);
        String guid = GraphHelper.getGuid(vertex);
        Id.EntityState state = GraphHelper.getState(vertex);
        if (state == Id.EntityState.DELETED) {
            //If the reference vertex is marked for deletion, skip it
            continue;
        }
        result.add(new VertexInfo(guid, vertex, typeName));
        ClassType classType = typeSystem.getDataType(ClassType.class, typeName);
        for (AttributeInfo attributeInfo : classType.fieldMapping().fields.values()) {
            if (!attributeInfo.isComposite) {
                continue;
            }
            String edgeLabel = GraphHelper.getEdgeLabel(classType, attributeInfo);
            switch (attributeInfo.dataType().getTypeCategory()) {
            case CLASS:
                AtlasEdge edge = getEdgeForLabel(vertex, edgeLabel);
                if (edge != null && GraphHelper.getState(edge) == Id.EntityState.ACTIVE) {
                    AtlasVertex compositeVertex = edge.getInVertex();
                    vertices.push(compositeVertex);
                }
                break;
            case ARRAY:
                IDataType elementType = ((DataTypes.ArrayType) attributeInfo.dataType()).getElemType();
                DataTypes.TypeCategory elementTypeCategory = elementType.getTypeCategory();
                if (elementTypeCategory != TypeCategory.CLASS) {
                    continue;
                }
                Iterator<AtlasEdge> edges = getOutGoingEdgesByLabel(vertex, edgeLabel);
                if (edges != null) {
                    while (edges.hasNext()) {
                        edge = edges.next();
                        if (edge != null && GraphHelper.getState(edge) == Id.EntityState.ACTIVE) {
                            AtlasVertex compositeVertex = edge.getInVertex();
                            vertices.push(compositeVertex);
                        }
                    }
                }
                break;
            case MAP:
                DataTypes.MapType mapType = (DataTypes.MapType) attributeInfo.dataType();
                DataTypes.TypeCategory valueTypeCategory = mapType.getValueType().getTypeCategory();
                if (valueTypeCategory != TypeCategory.CLASS) {
                    continue;
                }
                String propertyName = GraphHelper.getQualifiedFieldName(classType, attributeInfo.name);
                List<String> keys = vertex.getProperty(propertyName, List.class);
                if (keys != null) {
                    for (String key : keys) {
                        String mapEdgeLabel = GraphHelper.getQualifiedNameForMapKey(edgeLabel, key);
                        edge = getEdgeForLabel(vertex, mapEdgeLabel);
                        if (edge != null && GraphHelper.getState(edge) == Id.EntityState.ACTIVE) {
                            AtlasVertex compositeVertex = edge.getInVertex();
                            vertices.push(compositeVertex);
                        }
                    }
                }
                break;
            default:
            }
        }
    }
    return result;
}

From source file:com.cyclopsgroup.waterview.tool.PopulateToolsValve.java

/**
 * Override or implement method of parent class or interface
 * //from   ww  w.j a v a 2s .c  om
 * @see com.cyclopsgroup.waterview.Valve#invoke(com.cyclopsgroup.waterview.UIRuntime)
 */
public void invoke(UIRuntime runtime) throws Exception {
    Stack processedTools = new Stack();
    for (Iterator i = toolDefinitions.values().iterator(); i.hasNext();) {
        ToolDef def = (ToolDef) i.next();
        UITool tool = null;
        try {
            if (def.lifecycle == ToolLifecycle.REQUEST) {
                tool = createRequestTool(runtime, def);
            } else if (def.lifecycle == ToolLifecycle.SESSION) {
                tool = createSessionTool(runtime, def);
            } else if (def.lifecycle == ToolLifecycle.APPLICATION) {
                tool = createApplicationTool(runtime, def);
            }
            tool.setName(def.name);
            processedTools.push(tool);
            runtime.getPageContext().put(def.name, tool);
            if (tool instanceof RequestListener) {
                ((RequestListener) tool).prepareForRequest(runtime);
            }
        } catch (Exception e) {
            getLogger().warn("Tool initialization error", e);
        }
    }

    try {
        invokeNext(runtime);
    } catch (Exception e) {
        throw e;
    } finally {
        while (!processedTools.isEmpty()) {
            UITool tool = (UITool) processedTools.pop();
            runtime.getPageContext().remove(tool.getName());
            try {
                if (tool instanceof RequestListener) {
                    ((RequestListener) tool).disposeForRequest(runtime);
                }
            } catch (Exception e) {
                getLogger().warn("Tool disposing error", e);
            }
        }
    }
}