Example usage for java.util Stack Stack

List of usage examples for java.util Stack Stack

Introduction

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

Prototype

public Stack() 

Source Link

Document

Creates an empty Stack.

Usage

From source file:forge.limited.BoosterDraft.java

protected boolean generateProduct() {
    switch (this.draftFormat) {
    case Full: // Draft from all cards in Forge
        final Supplier<List<PaperCard>> s = new UnOpenedProduct(SealedProduct.Template.genericBooster);

        for (int i = 0; i < 3; i++) {
            this.product.add(s);
        }/*ww  w .  ja v a  2 s . co  m*/
        IBoosterDraft.LAND_SET_CODE[0] = CardEdition.Predicates
                .getRandomSetWithAllBasicLands(FModel.getMagicDb().getEditions());
        break;

    case Block: // Draft from cards by block or set
    case FantasyBlock:
        final List<CardBlock> blocks = new ArrayList<>();
        final IStorage<CardBlock> storage = this.draftFormat == LimitedPoolType.Block ? FModel.getBlocks()
                : FModel.getFantasyBlocks();

        for (final CardBlock b : storage) {
            if (b.getCntBoostersDraft() > 0) {
                blocks.add(b);
            }
        }

        final CardBlock block = SGuiChoose.oneOrNone("Choose Block", blocks);
        if (block == null) {
            return false;
        }

        final List<CardEdition> cardSets = block.getSets();
        if (cardSets.isEmpty()) {
            SOptionPane.showErrorDialog(block.toString() + " does not contain any set combinations.");
            return false;
        }

        final Stack<String> sets = new Stack<>();
        for (int k = cardSets.size() - 1; k >= 0; k--) {
            sets.add(cardSets.get(k).getCode());
        }

        for (final String setCode : block.getMetaSetNames()) {
            if (block.getMetaSet(setCode).isDraftable()) {
                sets.push(setCode); // to the beginning
            }
        }

        final int nPacks = block.getCntBoostersDraft();

        if (sets.size() > 1) {
            final Object p = SGuiChoose.oneOrNone("Choose Set Combination", getSetCombos(sets));
            if (p == null) {
                return false;
            }

            final String[] pp = p.toString().split("/");
            for (int i = 0; i < nPacks; i++) {
                this.product.add(block.getBooster(pp[i]));
            }
        } else {
            final IUnOpenedProduct product1 = block.getBooster(sets.get(0));

            for (int i = 0; i < nPacks; i++) {
                this.product.add(product1);
            }
        }

        IBoosterDraft.LAND_SET_CODE[0] = block.getLandSet();
        break;

    case Custom:
        final List<CustomLimited> myDrafts = loadCustomDrafts();

        if (myDrafts.isEmpty()) {
            SOptionPane.showMessageDialog("No custom draft files found.");
        } else {
            final CustomLimited customDraft = SGuiChoose.oneOrNone("Choose Custom Draft", myDrafts);
            if (customDraft == null) {
                return false;
            }

            this.setupCustomDraft(customDraft);
        }
        break;

    default:
        throw new NoSuchElementException("Draft for mode " + this.draftFormat + " has not been set up!");
    }

    this.pack = this.get8BoosterPack();
    return true;
}

From source file:com.blackducksoftware.integration.hub.detect.detector.maven.MavenCodeLocationPackager.java

public List<MavenParseResult> extractCodeLocations(final String sourcePath, final String mavenOutputText,
        final String targetScope, final String excludedModules, final String includedModules) {
    final ExcludedIncludedFilter filter = new ExcludedIncludedFilter(excludedModules, includedModules);
    codeLocations = new ArrayList<>();
    currentMavenProject = null;/*from  w ww.  ja va  2s  .c  om*/
    dependencyParentStack = new Stack<>();
    parsingProjectSection = false;
    currentGraph = new MutableMapDependencyGraph();

    level = 0;
    for (final String currentLine : mavenOutputText.split(System.lineSeparator())) {
        String line = currentLine.trim();
        if (!isLineRelevant(line)) {
            continue;
        }
        line = trimLogLevel(line);
        if (StringUtils.isBlank(line)) {
            continue;
        }
        if (isProjectSection(line)) {
            parsingProjectSection = true;
            continue;
        }
        if (!parsingProjectSection) {
            continue;
        }
        if (isDependencyTreeUpdates(line)) {
            continue;
        }

        if (parsingProjectSection && currentMavenProject == null) {
            // this is the first line of a new code location, the following lines will be the tree of dependencies for this code location
            currentGraph = new MutableMapDependencyGraph();
            final MavenParseResult mavenProject = createMavenParseResult(sourcePath, line, currentGraph);
            if (null != mavenProject && filter.shouldInclude(mavenProject.projectName)) {
                logger.trace(String.format("Project: %s", mavenProject.projectName));
                this.currentMavenProject = mavenProject;
                codeLocations.add(mavenProject);
            } else {
                logger.trace("Project: unknown");
                currentMavenProject = null;
                dependencyParentStack.clear();
                parsingProjectSection = false;
                level = 0;
            }
            continue;
        }

        final boolean finished = line.contains("--------");
        if (finished) {
            currentMavenProject = null;
            dependencyParentStack.clear();
            parsingProjectSection = false;
            level = 0;
            continue;
        }

        final int previousLevel = level;
        final String cleanedLine = calculateCurrentLevelAndCleanLine(line);
        final ScopedDependency dependency = textToDependency(cleanedLine);
        if (null == dependency) {
            continue;
        }
        if (currentMavenProject != null) {
            if (level == 1) {
                // a direct dependency, clear the stack and add this as a potential parent for the next line
                if (dependency.isInScope(targetScope)) {
                    logger.trace(String.format(
                            "Level 1 component %s:%s:%s:%s is in scope; adding it to hierarchy root",
                            dependency.externalId.group, dependency.externalId.name,
                            dependency.externalId.version, dependency.scope));
                    currentGraph.addChildToRoot(dependency);
                    inOutOfScopeTree = false;
                } else {
                    logger.trace(String.format(
                            "Level 1 component %s:%s:%s:%s is a top-level out-of-scope component; entering non-scoped tree",
                            dependency.externalId.group, dependency.externalId.name,
                            dependency.externalId.version, dependency.scope));
                    inOutOfScopeTree = true;
                }
                dependencyParentStack.clear();
                dependencyParentStack.push(dependency);
            } else {
                // level should be greater than 1
                if (level == previousLevel) {
                    // a sibling of the previous dependency
                    dependencyParentStack.pop();
                    addDependencyIfInScope(currentGraph, orphans, targetScope, inOutOfScopeTree,
                            dependencyParentStack.peek(), dependency);
                    dependencyParentStack.push(dependency);
                } else if (level > previousLevel) {
                    // a child of the previous dependency
                    addDependencyIfInScope(currentGraph, orphans, targetScope, inOutOfScopeTree,
                            dependencyParentStack.peek(), dependency);
                    dependencyParentStack.push(dependency);
                } else {
                    // a child of a dependency further back than 1 line
                    for (int i = previousLevel; i >= level; i--) {
                        dependencyParentStack.pop();
                    }
                    addDependencyIfInScope(currentGraph, orphans, targetScope, inOutOfScopeTree,
                            dependencyParentStack.peek(), dependency);
                    dependencyParentStack.push(dependency);
                }
            }
        }
    }
    addOrphansToGraph(currentGraph, orphans);

    return codeLocations;
}

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

public Stack<Pair<String, String[]>> getFieldsStack() throws WorfException {
    Stack<Pair<String, String[]>> stack = new Stack<>();

    for (Map.Entry<Object, Object> configEntry : config.entrySet()) {
        String key = (String) configEntry.getKey();
        String value = (String) configEntry.getValue();

        ///* w  w w .j  av  a 2 s. c  o  m*/
        // extract template value
        //
        Matcher templateMatcher = templatePattern.matcher(value);

        if (templateMatcher.matches()) {
            String template = templateMatcher.group(1);
            String[] templateValues = template.split(":");

            if (templateValues.length != 3) {
                throw new WorfException("Read template error key=" + key + " t=" + value);
            }
            stack.push(new Pair<>(value, templateValues));
        }
    }

    return stack;
}

From source file:com.linuxbox.enkive.message.MessageImpl.java

/**
 * @throws IOException//from   w w  w  . java2 s.  c o m
 * @throws MimeIOException
 * @throws MimeException
 * @throws CannotTransferMessageContentException
 * 
 * @param InputStream
 *            in An InputStream of the message to be parsed
 * 
 *            Constructs a com.linuxbox.enkive.message object from a raw
 *            email message InputStream
 * @throws BadMessageException
 */
public void ConstructMessage(InputStream in)
        throws IOException, CannotTransferMessageContentException, BadMessageException {

    Stack<MultiPartHeader> headerStack = new Stack<MultiPartHeader>();
    MultiPartHeader mp;
    StringBuilder headers = new StringBuilder();
    boolean messageHeadersParsed = false;
    boolean isMultiPart = false;

    // TODO Get line ending from message
    final String lineEnding = "\r\n";

    final MessageStreamParser stream = new MessageStreamParser(config);
    stream.setRecursionMode(RecursionMode.M_NO_RECURSE);

    stream.parse(in);

    try {
        for (EntityState state = stream.getState(); state != EntityState.T_END_OF_STREAM; state = stream
                .next()) {
            switch (state) {

            // At the start of a header section we want to reset the local
            // header variable since we only want to store the headers
            // for the section currently being parsed
            case T_START_HEADER:
                headers = new StringBuilder();
                break;

            // Append each header field to the local header variable
            case T_FIELD:
                headers.append(stream.getField());
                headers.append(lineEnding);
                break;

            // If we haven't set the message headers set them and
            // clear the variable so they don't get stored in a
            // ContentHeader object
            case T_END_HEADER:
                if (!messageHeadersParsed) {
                    setOriginalHeaders(headers.toString());
                    messageHeadersParsed = true;
                    headers = new StringBuilder();
                }
                break;

            // If we have a multipart message, create a new object,
            // grab the information we need and push it on the stack
            case T_START_MULTIPART:
                isMultiPart = true;
                mp = new MultiPartHeaderImpl();
                mp.setBoundary(stream.getBodyDescriptor().getBoundary());
                mp.setOriginalHeaders(headers.toString());
                mp.setLineEnding(lineEnding);
                headerStack.push(mp);
                break;

            // If there's a preamble, get the multipartheader off
            // the top of the stack, set it, and push back on the stack
            case T_PREAMBLE:
                BufferedReader reader = new BufferedReader(stream.getReader());

                String tempString;
                String preamble = "";
                while ((tempString = reader.readLine()) != null) {
                    preamble += tempString + lineEnding;
                }
                mp = headerStack.pop();
                mp.setPreamble(preamble);
                headerStack.push(mp);
                break;

            // If there's an epilogue, get the multipartheader off
            // the top of the stack, set it, and push back on the stack
            case T_EPILOGUE:
                BufferedReader epilogueReader = new BufferedReader(stream.getReader());

                String tempEpilogueString;
                String epilogue = "";
                while ((tempEpilogueString = epilogueReader.readLine()) != null) {
                    epilogue += tempEpilogueString + lineEnding;
                }
                mp = headerStack.pop();
                mp.setEpilogue(epilogue);
                headerStack.push(mp);
                break;

            // Create a new singlepartheader, set the headers,
            // set the content_data
            case T_BODY:
                SinglePartHeader single = new SinglePartHeaderImpl();
                final String transferEncoding = stream.getBodyDescriptor().getTransferEncoding();
                EncodedContentDataImpl cd = new EncodedContentDataImpl(transferEncoding);
                cd.setBinaryContent(stream.getInputStream());
                single.setContentTransferEncoding(transferEncoding);

                single.setOriginalHeaders(headers.toString());
                single.parseHeaders(headers.toString(), config);
                single.setEncodedContentData(cd);
                single.setLineEnding(lineEnding);
                // If we're working with a multipart message,
                // pop, add the singlepartheader, and push.
                // Otherwise just set the singlepartheader
                if (isMultiPart) {
                    mp = headerStack.pop();
                    mp.addPartHeader(single);
                    headerStack.push(mp);
                } else
                    this.setContentHeader(single);
                break;

            // If we've reached the end of a multipart, it could
            // be a nested multipart. In that case we'll need to
            // Add the nested multipart to the multipart a level above.
            // If not nested, we've reached the end of the content headers
            // so set it.
            case T_END_MULTIPART:
                mp = headerStack.pop();
                if (headerStack.isEmpty())
                    this.setContentHeader(mp);
                else {
                    MultiPartHeader mp2 = headerStack.pop();
                    mp2.addPartHeader(mp);
                    headerStack.push(mp2);
                }
                break;
            default:
                // ignore other tags
                break;
            } // switch
        } // for
    } catch (MimeException e) {
        throw new BadMessageException(e);
    } catch (MimeIOException e) {
        throw new BadMessageException(e);
    }
    if (LOGGER.isTraceEnabled())
        LOGGER.trace("Message " + this.messageId + " successfully parsed.");
}

From source file:org.liberty.android.fantastischmemopro.downloader.DownloaderSS.java

@Override
protected void initialRetrieve() {
    dlAdapter = new DownloadListAdapter(this, R.layout.filebrowser_item);
    dlStack = new Stack<List<DownloadItem>>();
    categoryIdStack = new Stack<String>();
    mHandler = new Handler();
    listView = (ListView) findViewById(R.id.file_list);
    listView.setOnScrollListener(this);
    listView.setAdapter(dlAdapter);/* w ww  . j  av a  2 s  .  co m*/
    mProgressDialog = ProgressDialog.show(DownloaderSS.this, getString(R.string.loading_please_wait),
            getString(R.string.loading_connect_net), true, true, new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    finish();
                }
            });
    new Thread() {
        public void run() {
            try {
                categoryList = retrieveCategories();
                mHandler.post(new Runnable() {
                    public void run() {
                        showRootCategories();
                        mProgressDialog.dismiss();
                    }
                });
            } catch (final Exception e) {
                mHandler.post(new Runnable() {
                    public void run() {
                        mProgressDialog.dismiss();
                        new AlertDialog.Builder(DownloaderSS.this)
                                .setTitle(R.string.downloader_connection_error)
                                .setMessage(
                                        getString(R.string.downloader_connection_error_message) + e.toString())
                                .setPositiveButton(getString(R.string.ok_text),
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                finish();
                                            }
                                        })
                                .create().show();
                    }
                });
            }

        }
    }.start();

}

From source file:net.sf.eventgraphj.centrality.EgoNetworkBetweennessCentrality.java

protected void computeBetweenness(Queue<V> queue, Transformer<E, ? extends Number> edge_weights) {
    for (V v : graph.getVertices()) {
        // initialize the betweenness data for this new vertex
        for (V s : graph.getVertices())
            this.vertex_data.put(s, new BetweennessData());

        //         if (v.equals(new Integer(0)))
        //            System.out.println("pause");

        vertex_data.get(v).numSPs = 1;//from  w  w  w. j  a v a 2  s.  c  o m
        vertex_data.get(v).distance = 0;

        Stack<V> stack = new Stack<V>();
        //            Buffer<V> queue = new UnboundedFifoBuffer<V>();
        //            queue.add(v);
        queue.offer(v);

        while (!queue.isEmpty()) {
            //                V w = queue.remove();
            V w = queue.poll();
            stack.push(w);
            BetweennessData w_data = vertex_data.get(w);
            for (E e : graph.getOutEdges(w)) {
                // TODO (jrtom): change this to getOtherVertices(w, e)
                V x = graph.getOpposite(w, e);
                if (x.equals(w))
                    continue;
                double wx_weight = edge_weights.transform(e).doubleValue();

                //                for(V x : graph.getSuccessors(w)) 
                //                {
                //                   if (x.equals(w))
                //                      continue;

                // FIXME: the other problem is that I need to 
                // keep putting the neighbors of things we've just 
                // discovered in the queue, if they're undiscovered or
                // at greater distance.

                // FIXME: this is the problem, right here, I think: 
                // need to update position in queue if distance changes
                // (which can only happen with weighted edges).
                // for each outgoing edge e from w, get other end x
                // if x not already visited (dist x < 0)
                //   set x's distance to w's dist + edge weight
                //   add x to queue; pri in queue is x's dist
                // if w's dist + edge weight < x's dist 
                //   update x's dist
                //   update x in queue (MapBinaryHeap)
                //   clear x's incoming edge list
                // if w's dist + edge weight = x's dist
                //   add e to x's incoming edge list

                BetweennessData x_data = vertex_data.get(x);
                double x_potential_dist = w_data.distance + wx_weight;
                if (x_potential_dist > this.egoNetworkSize)
                    continue;

                if (x_data.distance < 0) {
                    //                        queue.add(x);
                    //                        vertex_data.get(x).distance = vertex_data.get(w).distance + 1;
                    x_data.distance = x_potential_dist;
                    queue.offer(x);
                }

                // note:
                // (1) this can only happen with weighted edges
                // (2) x's SP count and incoming edges are updated below 
                if (x_data.distance > x_potential_dist) {
                    x_data.distance = x_potential_dist;
                    // invalidate previously identified incoming edges
                    // (we have a new shortest path distance to x)
                    x_data.incomingEdges.clear();
                    // update x's position in queue
                    ((MapBinaryHeap<V>) queue).update(x);
                }
                //                  if (vertex_data.get(x).distance == vertex_data.get(w).distance + 1) 
                // 
                //                    if (x_data.distance == x_potential_dist) 
                //                    {
                //                        x_data.numSPs += w_data.numSPs;
                ////                        vertex_data.get(x).predecessors.add(w);
                //                        x_data.incomingEdges.add(e);
                //                    }
            }
            for (E e : graph.getOutEdges(w)) {
                V x = graph.getOpposite(w, e);
                if (x.equals(w))
                    continue;
                double e_weight = edge_weights.transform(e).doubleValue();
                BetweennessData x_data = vertex_data.get(x);
                double x_potential_dist = w_data.distance + e_weight;
                if (x_data.distance == x_potential_dist) {
                    x_data.numSPs += w_data.numSPs;
                    //                        vertex_data.get(x).predecessors.add(w);
                    x_data.incomingEdges.add(e);
                }
            }
        }
        while (!stack.isEmpty()) {
            V x = stack.pop();

            //              for (V w : vertex_data.get(x).predecessors) 
            for (E e : vertex_data.get(x).incomingEdges) {
                V w = graph.getOpposite(x, e);
                double partialDependency = vertex_data.get(w).numSPs / vertex_data.get(x).numSPs
                        * (1.0 + vertex_data.get(x).dependency);
                vertex_data.get(w).dependency += partialDependency;
                //                  E w_x = graph.findEdge(w, x);
                //                  double w_x_score = edge_scores.get(w_x).doubleValue();
                //                  w_x_score += partialDependency;
                //                  edge_scores.put(w_x, w_x_score);
                double e_score = edge_scores.get(e).doubleValue();
                edge_scores.put(e, e_score + partialDependency);
            }
            if (!x.equals(v)) {
                double x_score = vertex_scores.get(x).doubleValue();
                x_score += vertex_data.get(x).dependency;
                vertex_scores.put(x, x_score);
            }
        }
    }

    if (graph instanceof UndirectedGraph) {
        for (V v : graph.getVertices()) {
            double v_score = vertex_scores.get(v).doubleValue();
            v_score /= 2.0;
            vertex_scores.put(v, v_score);
        }
        for (E e : graph.getEdges()) {
            double e_score = edge_scores.get(e).doubleValue();
            e_score /= 2.0;
            edge_scores.put(e, e_score);
        }
    }

    vertex_data.clear();
}

From source file:com.joliciel.jochre.stats.DBSCANClusterer.java

private void expandCluster(int index, Set<Integer> neighbours, Set<T> cluster, double epsilon, int minPoints) {
    /*// ww  w.j ava 2s  .  c om
    expandCluster(P, N, C, eps, MinPts)
       add P to cluster C
       for each point P' in N 
    if P' is not visited
       mark P' as visited
       N' = getNeighbors(P', eps)
       if sizeof(N') >= MinPts
          N = N joined with N'
    if P' is not yet member of any cluster
       add P' to cluster C
    */
    cluster.add(objectSet.get(index));
    clusterList.set(index, cluster);
    Stack<Integer> points = new Stack<Integer>();
    points.addAll(neighbours);

    while (!points.isEmpty()) {
        int i = points.pop();
        if (!visited[i]) {
            visited[i] = true;
            Set<Integer> nPrime = this.getNeighbours(i, epsilon);
            if (nPrime.size() >= minPoints - 1) {
                points.addAll(nPrime);
            }
        }
        if (clusterList.get(i) == null) {
            cluster.add(objectSet.get(i));
            clusterList.set(i, cluster);
        }
    }
}

From source file:com.samsung.sjs.backend.IRCBackend.java

public IRCBackend(Script r, CompilerOptions opts, IRFieldCollector.FieldMapping m, FFILinkage ffi,
        JSEnvironment env, ModuleSystem modsys) {
    super(new TypeTagSerializer(m));
    program = r;/*from   w w  w.j a  va 2 s  . co m*/
    this.debug = opts.debug();
    this.options = opts;
    field_codes = m;
    assert (m != null);
    functions = new Stack<Function>();
    compiled_functions = new Stack<FunctionDeclaration>();
    this.ffi = ffi;
    this.toplevel = env;
    live_tmp_vars = new HashSet<>();
    slowgen = new SlowPathGenerator(tts, m);
    this.modsys = modsys;
}

From source file:org.ojai.json.impl.JsonDocumentBuilder.java

private void initJsonGenerator(OutputStream out) {
    try {//from w ww.  j  a  va  2 s  .c  om
        JsonFactory jFactory = new JsonFactory();
        jsonGenerator = jFactory.createGenerator(out, JsonEncoding.UTF8);
        ctxStack = new Stack<ContainerContext>();
        currentContext = ContainerContext.NULL;
        checkContext = true;
        setJsonOptions(JsonOptions.WITH_TAGS);
    } catch (IOException ie) {
        throw transformIOException(ie);
    }
}

From source file:com.haulmont.cuba.core.app.EntityDiffManager.java

protected EntityDiff getDifferenceByView(EntitySnapshot first, EntitySnapshot second, View diffView) {
    EntityDiff result = new EntityDiff(diffView);
    result.setBeforeSnapshot(first);/*from www.  j av a2 s.  c o  m*/
    result.setAfterSnapshot(second);

    if (!diffView.getProperties().isEmpty()) {
        Entity firstEntity = first != null ? snapshotAPI.extractEntity(first) : null;
        Entity secondEntity = snapshotAPI.extractEntity(second);

        result.setBeforeEntity(firstEntity);
        result.setAfterEntity(secondEntity);

        Stack<Object> diffBranch = new Stack<>();
        if (secondEntity != null) {
            diffBranch.push(secondEntity);
        }

        List<EntityPropertyDiff> propertyDiffs = getPropertyDiffs(diffView, firstEntity, secondEntity,
                diffBranch);
        result.setPropertyDiffs(propertyDiffs);
    }
    return result;
}