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.schibsted.triathlon.operators.GroupByOperatorTest.java

@Test
public void testDeployTwoDataCentersOddNumberOfInstances() throws Exception {
    initializeInstanceInfos(2);//from w  w  w .j  av  a  2  s .c o m

    List<String> constraint = new ArrayList<String>() {
        {
            add("datacenter");
            add("GROUP_BY");
        }
    };
    TriathlonService triathlonService = new TriathlonServiceImpl();

    String content = IOUtils.toString(this.getClass().getResourceAsStream("group_by_operator_1.json"), "UTF-8");

    ByteBuf buffer = Unpooled.copiedBuffer(content.getBytes());

    Marathon appDefinition = triathlonService.parseJson(Observable.just(buffer)).toBlocking().toFuture().get();
    appDefinition.setInstances(5);

    ConstraintModel constraintModel = ConstraintModel.createConstraintModel(constraint);

    Operator cluster = new GroupByOperator(triathlonService, constraintModel);

    Operator spyCluster = Mockito.spy(cluster);
    doReturn(Observable.just(Unpooled.wrappedBuffer("TEST".getBytes()))).when(spyCluster)
            .getMarathonCommand(Mockito.any(InstanceInfo.class), Mockito.anyString());

    Stack<Integer> values = new Stack<>();
    values.push(2);
    values.push(3);

    when(spyCluster.getMarathonCommand(Mockito.any(InstanceInfo.class), Mockito.anyString()))
            .thenAnswer(invocation -> {
                Object[] args = invocation.getArguments();
                Observable<ByteBuf> val = Observable
                        .just(Unpooled.wrappedBuffer(((String) args[1]).getBytes()));
                Marathon appDef = triathlonService.parseJson(val).toBlocking().toFuture().get();
                Integer v = values.pop();
                assertEquals(v, appDef.getInstances());
                return val;
            });

    spyCluster.apply(appDefinition).subscribe();
    verify(spyCluster, times(2)).getMarathonCommand(Mockito.any(InstanceInfo.class), Mockito.anyString());
}

From source file:org.apache.tajo.engine.codegen.ExecutorPreCompiler.java

@Override
public LogicalNode visitTableSubQuery(CompilationContext context, LogicalPlan plan,
        LogicalPlan.QueryBlock block, TableSubQueryNode node, Stack<LogicalNode> stack) throws TajoException {
    stack.push(node);
    visit(context, plan, null, node.getSubQuery(), stack);
    stack.pop();/*from  w w w.ja  va2 s .c  o  m*/

    if (node.hasTargets()) {
        for (Target target : node.getTargets()) {
            compileIfAbsent(context, node.getLogicalSchema(), target.getEvalTree());
        }
    }

    return node;
}

From source file:com.ctriposs.rest4j.tools.snapshot.check.Rest4JSnapshotCompatibilityChecker.java

private CompatibilityInfoMap checkCompatibility(String prevRestModelPath, String currRestModelPath,
        CompatibilityLevel compatLevel, boolean isAgainstRestSpec) {
    final CompatibilityInfoMap infoMap = new CompatibilityInfoMap();
    if (compatLevel == CompatibilityLevel.OFF) {
        // skip check entirely.
        return infoMap;
    }//w w w  . java  2 s. c  o  m

    final Stack<Object> path = new Stack<Object>();
    path.push("");

    FileInputStream prevSnapshotFile = null;
    FileInputStream currSnapshotFile = null;

    try {
        prevSnapshotFile = new FileInputStream(prevRestModelPath);
    } catch (FileNotFoundException e) {
        infoMap.addRestSpecInfo(CompatibilityInfo.Type.RESOURCE_NEW, path, currRestModelPath);
    }

    try {
        currSnapshotFile = new FileInputStream(currRestModelPath);
    } catch (FileNotFoundException e) {
        infoMap.addRestSpecInfo(CompatibilityInfo.Type.RESOURCE_MISSING, path, prevRestModelPath);
    }

    if (prevSnapshotFile == null || currSnapshotFile == null) {
        return infoMap;
    }

    AbstractSnapshot prevSnapshot = null;
    AbstractSnapshot currSnapshot = null;
    try {
        if (isAgainstRestSpec) {
            prevSnapshot = new RestSpec(prevSnapshotFile);
        } else {
            prevSnapshot = new Snapshot(prevSnapshotFile);
        }

        currSnapshot = new Snapshot(currSnapshotFile);
    } catch (IOException e) {
        infoMap.addRestSpecInfo(CompatibilityInfo.Type.OTHER_ERROR, path, e.getMessage());
    }

    if (prevSnapshot == null || currSnapshot == null) {
        return infoMap;
    }

    final DataSchemaResolver currResolver = createResolverFromSnapshot(currSnapshot, _resolverPath);
    final DataSchemaResolver prevResolver;
    if (isAgainstRestSpec) {
        prevResolver = currResolver;
    } else {
        prevResolver = createResolverFromSnapshot(prevSnapshot, _resolverPath);
    }

    final ResourceCompatibilityChecker checker = new ResourceCompatibilityChecker(
            prevSnapshot.getResourceSchema(), prevResolver, currSnapshot.getResourceSchema(), currResolver);
    checker.check(compatLevel);
    infoMap.addAll(checker.getInfoMap());

    return infoMap;
}

From source file:logicProteinHypernetwork.networkStates.NetworkEntityToMinimalNetworkStates.java

/**
 * Calculates all minimally constrained satisfying models using the tableau
 * algorithm and derives the minimal network states.
 * //from  ww w . j  ava  2  s.  c o  m
 * @param e
 *            the network entity
 * @param f
 *            the minimal network state formula
 * @param states
 *            the place where all minimal network states are collected
 */
public void calculateAllTableauPaths(final NetworkEntity e, final Formula<NetworkEntity> f,
        final Collection<MinimalNetworkState> states) {
    f.toNegationNormalForm();
    Stack<Collection<Formula<NetworkEntity>>> blocked = new Stack<Collection<Formula<NetworkEntity>>>();
    blocked.push(new ArrayList<Formula<NetworkEntity>>());
    boolean first = true;
    while (!blocked.isEmpty()) {
        Tableau<NetworkEntity> tableau = new Tableau<NetworkEntity>(tableauRules, propositionComparator, false);
        tableau.setFormula(f);

        Collection<Formula<NetworkEntity>> bs = blocked.pop();
        World start = new World(0, propositionComparator);
        for (Formula<NetworkEntity> b : bs) {
            tableau.block(start, b);
        }

        boolean satisfiable = tableau.proofSearch();
        if (!satisfiable && first) {
            System.err.println("Formula not satisfiable for entity " + e
                    + ". This indicates a circular interaction dependency which is not allowed. Until you fix this, we assume that the entity does not have any competitors or dependencies.");
            MinimalNetworkState mns = new MinimalNetworkState();
            mns.setEntity(e);
            mns.addNecessary(e);
            if (e instanceof Interaction) {
                for (Protein p : ((Interaction) e).getProteins())
                    mns.addNecessary(p);
            }
            states.add(mns);

        }
        if (satisfiable) {
            MinimalNetworkState s = ts.transform(tableau);
            s.setEntity(e);
            states.add(s);

            for (LabelledFormula<NetworkEntity> d : tableau.getDisjunctions()) {
                Formula<NetworkEntity> active = tableau.getActiveDisjunct(d).getFormula();
                int index = active.getParent().indexOf(active);
                if (index != 0) {
                    // find other children that are not yet pre-blocked
                    for (Formula<NetworkEntity> child : d.getFormula()) {
                        LabelledFormula<NetworkEntity> lf = tableau.getLabelledFormula(d.getWorld(), child);
                        if (lf != null) {
                            for (Formula<NetworkEntity> el : lf.getEliminationExplanation()) {
                                if (el.indexOf(
                                        tableau.getActiveDisjunct(tableau.getLabelledFormula(d.getWorld(), el))
                                                .getFormula()) == 0) {
                                    Collection<Formula<NetworkEntity>> bs2 = new ArrayList<Formula<NetworkEntity>>(
                                            bs);
                                    bs2.add(tableau.getActiveDisjunct(d).getFormula());
                                    blocked.push(bs2);
                                }
                            }
                        }
                    }
                }
            }
        }
        first = false;
    }
}

From source file:com.linkedin.restli.tools.snapshot.check.RestLiSnapshotCompatibilityChecker.java

private CompatibilityInfoMap checkCompatibility(String prevRestModelPath, String currRestModelPath,
        CompatibilityLevel compatLevel, boolean isAgainstRestSpec) {
    final CompatibilityInfoMap infoMap = _infoMap;
    if (compatLevel == CompatibilityLevel.OFF) {
        // skip check entirely.
        return infoMap;
    }//  w w w .  java 2 s .  c  om

    final Stack<Object> path = new Stack<Object>();
    path.push("");

    FileInputStream prevSnapshotFile = null;
    FileInputStream currSnapshotFile = null;

    try {
        prevSnapshotFile = new FileInputStream(prevRestModelPath);
    } catch (FileNotFoundException e) {
        infoMap.addRestSpecInfo(CompatibilityInfo.Type.RESOURCE_NEW, path, currRestModelPath);
    }

    try {
        currSnapshotFile = new FileInputStream(currRestModelPath);
    } catch (FileNotFoundException e) {
        infoMap.addRestSpecInfo(CompatibilityInfo.Type.RESOURCE_MISSING, path, prevRestModelPath);
    }

    if (prevSnapshotFile == null || currSnapshotFile == null) {
        return infoMap;
    }

    AbstractSnapshot prevSnapshot = null;
    AbstractSnapshot currSnapshot = null;
    try {
        if (isAgainstRestSpec) {
            prevSnapshot = new RestSpec(prevSnapshotFile);
        } else {
            prevSnapshot = new Snapshot(prevSnapshotFile);
        }

        currSnapshot = new Snapshot(currSnapshotFile);
    } catch (IOException e) {
        infoMap.addRestSpecInfo(CompatibilityInfo.Type.OTHER_ERROR, path, e.getMessage());
    }

    if (prevSnapshot == null || currSnapshot == null) {
        return infoMap;
    }

    final DataSchemaResolver currResolver = createResolverFromSnapshot(currSnapshot, _resolverPath);
    final DataSchemaResolver prevResolver;
    if (isAgainstRestSpec) {
        prevResolver = currResolver;
    } else {
        prevResolver = createResolverFromSnapshot(prevSnapshot, _resolverPath);
    }

    final ResourceCompatibilityChecker checker = new ResourceCompatibilityChecker(
            prevSnapshot.getResourceSchema(), prevResolver, currSnapshot.getResourceSchema(), currResolver);
    checker.check(compatLevel);
    infoMap.addAll(checker.getInfoMap());

    return infoMap;
}

From source file:org.abstracthorizon.proximity.storage.local.WritableFileSystemStorage.java

public void recreateMetadata(Map extraProps) throws StorageException {

    // issue #44, we will not delete existing metadata,
    // instead, we will force to "recreate" those the properties factory
    // eventually appending it with new ones.

    int processed = 0;
    Stack stack = new Stack();
    List dir = listItems(ItemProperties.PATH_ROOT);
    stack.push(dir);
    while (!stack.isEmpty()) {
        dir = (List) stack.pop();
        for (Iterator i = dir.iterator(); i.hasNext();) {
            ItemProperties ip = (ItemProperties) i.next();

            if (ip.isDirectory()) {
                List subdir = listItems(ip.getPath());
                stack.push(subdir);/*from www  . ja va  2s. co  m*/
            } else {
                logger.debug("**** {}", ip.getPath());
                File target = new File(getStorageBaseDir(), ip.getPath());
                ItemProperties nip = getProxiedItemPropertiesFactory().expandItemProperties(ip.getPath(),
                        target, false);
                if (ip.getMetadata(DefaultExpiringProxyingRepositoryLogic.METADATA_EXPIRES) != null) {
                    logger.debug("We have an " + DefaultExpiringProxyingRepositoryLogic.METADATA_EXPIRES
                            + " property");
                    nip.setMetadata(DefaultExpiringProxyingRepositoryLogic.METADATA_EXPIRES,
                            ip.getMetadata(DefaultExpiringProxyingRepositoryLogic.METADATA_EXPIRES));
                }
                logger.debug("Recreating metadata : adding " + extraProps + " to " + nip.getAllMetadata());
                if (extraProps != null) {
                    nip.getAllMetadata().putAll(extraProps);
                }
                storeItemProperties(nip);
                processed++;
            }
        }
    }
    logger.info("Recreated metadata on {} items.", Integer.toString(processed));
}

From source file:csns.importer.parser.MFTScoreParser.java

public void parse(MFTScoreImporter importer) {
    Department department = importer.getDepartment();
    Date date = importer.getDate();

    Scanner scanner = new Scanner(importer.getText());
    scanner.useDelimiter("\\s+|\\r\\n|\\r|\\n");
    while (scanner.hasNext()) {
        // last name
        String lastName = scanner.next();
        while (!lastName.endsWith(","))
            lastName += " " + scanner.next();
        lastName = lastName.substring(0, lastName.length() - 1);

        // first name
        String firstName = scanner.next();

        // score/*ww w  .  ja  v  a  2  s . co m*/
        Stack<String> stack = new Stack<String>();
        String s = scanner.next();
        while (!isScore(s)) {
            stack.push(s);
            s = scanner.next();
        }
        int value = Integer.parseInt(s);

        // authorization code
        stack.pop();

        // cin
        String cin = null;
        if (!stack.empty() && isCin(stack.peek()))
            cin = stack.pop();

        // user
        User user = null;
        if (cin != null)
            user = userDao.getUserByCin(cin);
        else {
            List<User> users = userDao.getUsers(lastName, firstName);
            if (users.size() == 1)
                user = users.get(0);
        }

        if (user != null) {
            MFTScore score = mftScoreDao.getScore(department, date, user);
            if (score == null) {
                score = new MFTScore();
                score.setDepartment(department);
                score.setDate(date);
                score.setUser(user);
            } else {
                logger.info(user.getId() + ": " + score.getValue() + " => " + value);
            }
            score.setValue(value);
            importer.getScores().add(score);
        } else {
            User failedUser = new User();
            failedUser.setLastName(lastName);
            failedUser.setFirstName(firstName);
            failedUser.setCin(cin);
            importer.getFailedUsers().add(failedUser);
        }

        logger.debug(lastName + "," + firstName + "," + cin + "," + value);
    }

    scanner.close();
}

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

public static ArrayList<PTFInvocationSpec> componentize(PTFInvocationSpec ptfInvocation)
        throws SemanticException {

    ArrayList<PTFInvocationSpec> componentInvocations = new ArrayList<PTFInvocationSpec>();

    Stack<PTFInputSpec> ptfChain = new Stack<PTFInvocationSpec.PTFInputSpec>();
    PTFInputSpec spec = ptfInvocation.getFunction();
    while (spec instanceof PartitionedTableFunctionSpec) {
        ptfChain.push(spec);
        spec = spec.getInput();/*from  w  ww  .j  a v  a2 s.co m*/
    }

    PartitionedTableFunctionSpec prevFn = (PartitionedTableFunctionSpec) ptfChain.pop();
    applyConstantPartition(prevFn);
    PartitionSpec partSpec = prevFn.getPartition();
    OrderSpec orderSpec = prevFn.getOrder();

    if (partSpec == null) {
        // oops this should have been caught before trying to componentize
        throw new SemanticException("No Partitioning specification specified at start of a PTFChain");
    }
    if (orderSpec == null) {
        orderSpec = new OrderSpec(partSpec);
        prevFn.setOrder(orderSpec);
    }

    while (!ptfChain.isEmpty()) {
        PartitionedTableFunctionSpec currentFn = (PartitionedTableFunctionSpec) ptfChain.pop();
        String fnName = currentFn.getName();
        if (!FunctionRegistry.isTableFunction(fnName)) {
            throw new SemanticException(ErrorMsg.INVALID_FUNCTION.getMsg(fnName));
        }
        boolean transformsRawInput = FunctionRegistry.getTableFunctionResolver(fnName).transformsRawInput();

        /*
         * if the current table function has no partition info specified: inherit it from the PTF up
         * the chain.
         */
        if (currentFn.getPartition() == null) {
            currentFn.setPartition(prevFn.getPartition());
            if (currentFn.getOrder() == null) {
                currentFn.setOrder(prevFn.getOrder());
            }
        }
        /*
         * If the current table function has no order info specified;
         */
        if (currentFn.getOrder() == null) {
            currentFn.setOrder(new OrderSpec(currentFn.getPartition()));
        }

        if (!currentFn.getPartition().equals(partSpec) || !currentFn.getOrder().equals(orderSpec)
                || transformsRawInput) {
            PTFInvocationSpec component = new PTFInvocationSpec();
            component.setFunction(prevFn);
            componentInvocations.add(component);
            PTFQueryInputSpec cQInSpec = new PTFQueryInputSpec();
            cQInSpec.setType(PTFQueryInputType.PTFCOMPONENT);
            currentFn.setInput(cQInSpec);
        }

        prevFn = currentFn;
        partSpec = prevFn.getPartition();
        orderSpec = prevFn.getOrder();
    }
    componentInvocations.add(ptfInvocation);
    return componentInvocations;
}

From source file:FlightInfo.java

void route(String to) {
    Stack rev = new Stack();
    int dist = 0;
    FlightInfo f;/*w  w w. ja  va2 s. c  o  m*/
    int num = btStack.size();

    // Reverse the stack to display route.
    for (int i = 0; i < num; i++)
        rev.push(btStack.pop());

    for (int i = 0; i < num; i++) {
        f = (FlightInfo) rev.pop();
        System.out.print(f.from + " to ");
        dist += f.distance;
    }

    System.out.println(to);
    System.out.println("Distance is " + dist);
}

From source file:roboguice.calculator.view.TickerTapeView.java

public void refresh() {
    Stack<String> lines = new Stack<String>();
    String digitAccumulator = stack.getDigitAccumulator();

    // Include the current number that the user is typing in the display
    if (digitAccumulator.length() > 0)
        lines.push(digitAccumulator);

    // Include up to 3 lines of stack
    for (int i = 0; lines.size() < 3 && i < stack.size(); ++i)
        lines.push(stack.get(stack.size() - i - 1).toString());

    // Convert to text
    String text = "";
    for (String line : lines)
        text = line + "\n" + text + "\n";

    setText(text.trim());//  w ww  .j  ava  2  s.c om
}