List of usage examples for java.util Stack pop
public synchronized E pop()
From source file:hudson.gridmaven.MavenModuleSet.java
public void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException { modules = Collections.emptyMap(); // needed during load super.onLoad(parent, name); modules = loadChildren(this, getModulesDir(), new Function1<ModuleName, MavenModule>() { public ModuleName call(MavenModule module) { return module.getModuleName(); }//from w w w. ja va 2 s. c o m }); // update the transient nest level field. MavenModule root = getRootModule(); if (root != null && root.getChildren() != null) { List<MavenModule> sortedList = new ArrayList<MavenModule>(); Stack<MavenModule> q = new Stack<MavenModule>(); root.nestLevel = 0; q.push(root); while (!q.isEmpty()) { MavenModule p = q.pop(); sortedList.add(p); List<MavenModule> children = p.getChildren(); if (children != null) { for (MavenModule m : children) m.nestLevel = p.nestLevel + 1; for (int i = children.size() - 1; i >= 0; i--) // add them in the reverse order q.push(children.get(i)); } } this.sortedActiveModules = sortedList; } else { this.sortedActiveModules = getDisabledModules(false); } if (reporters == null) { reporters = new DescribableList<MavenReporter, Descriptor<MavenReporter>>(this); } reporters.setOwner(this); if (publishers == null) { publishers = new DescribableList<Publisher, Descriptor<Publisher>>(this); } publishers.setOwner(this); if (buildWrappers == null) { buildWrappers = new DescribableList<BuildWrapper, Descriptor<BuildWrapper>>(this); } buildWrappers.setOwner(this); if (prebuilders == null) { prebuilders = new DescribableList<Builder, Descriptor<Builder>>(this); } prebuilders.setOwner(this); if (postbuilders == null) { postbuilders = new DescribableList<Builder, Descriptor<Builder>>(this); } postbuilders.setOwner(this); if (perModuleEmail == null) { perModuleEmail = Boolean.TRUE; } if (Boolean.TRUE.equals(usePrivateRepository)) { this.localRepository = new PerJobLocalRepositoryLocator(); usePrivateRepository = null; } updateTransientActions(); }
From source file:com.concentricsky.android.khanacademy.app.ManageDownloadsActivity.java
private void launchVideoDetailActivity(Video video, String parentTopicId) { // This may be a video in a different topic from where the user came from. // We synthesize the correct back stack for this video. Stack<Topic> stack = new Stack<Topic>(); Topic topic = null;/*from w w w .j a v a 2 s .c om*/ try { Dao<Topic, String> topicDao = getDataService().getHelper().getTopicDao(); topic = topicDao.queryForId(parentTopicId); while (topic != null) { stack.push(topic); topicDao.refresh(topic); topic = topic.getParentTopic(); } } catch (SQLException e) { e.printStackTrace(); } catch (ServiceUnavailableException e) { e.printStackTrace(); } TaskStackBuilder t = TaskStackBuilder.create(this); Intent intent; while (!stack.isEmpty()) { topic = stack.pop(); if (topic.getParentTopic() == null) { // Root topic gets the HomeActivity. intent = new Intent(this, HomeActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); } else if (stack.isEmpty()) { // The video's immediate parent topic gets a VideoList. intent = new Intent(this, VideoListActivity.class); intent.putExtra(PARAM_TOPIC_ID, topic.getId()); } else { // All other intermediate topics get TopicLists. intent = new Intent(this, TopicListActivity.class); intent.putExtra(PARAM_TOPIC_ID, topic.getId()); } t.addNextIntent(intent); } // Add a manage downloads activity also, for back. It is skipped when going "up" from videos. intent = new Intent(this, ManageDownloadsActivity.class); t.addNextIntent(intent); intent = new Intent(this, VideoDetailActivity.class); intent.putExtra(PARAM_VIDEO_ID, video.getId()); intent.putExtra(PARAM_TOPIC_ID, parentTopicId); t.addNextIntent(intent); t.startActivities(); /* TaskStackBuilder just does this: intents[0].addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK | IntentCompat.FLAG_ACTIVITY_TASK_ON_HOME); and then uses Activity#startActivities. Support library fallback pre-honeycomb is to just start the top activity and allow back to progress back through the actual back stack (no synthesis). */ // startActivity(intent); }
From source file:com.abstratt.mdd.internal.frontend.textuml.TextUMLCompiler.java
/** * Given a position in a compilation unit, finds the contextual package name. * /*ww w. j av a 2s .com*/ * @param toParse source of compilation unit * @param line line number, starting from 1 * @param col column number, starting from 1 * @return the name of the contextual package */ public String findPackageName(String toParse, final int line, final int col) { Token token = findTokenAt(toParse, line, col); if (token == null) return null; final Stack<String> segments = new Stack<String>(); for (Node current = token; current != null; current = current.parent()) { current.apply(new AnalysisAdapter() { @Override public void caseAStart(AStart node) { segments.push(TextUMLCore.getSourceMiner().getQualifiedIdentifier( ((APackageHeading) node.getPackageHeading()).getQualifiedIdentifier())); } public void caseASubNamespace(ASubNamespace node) { segments.push(TextUMLCore.getSourceMiner() .getQualifiedIdentifier(((APackageHeading) node.getPackageHeading()))); } }); } if (segments.isEmpty()) return null; StringBuffer result = new StringBuffer(); while (!segments.isEmpty()) { result.append(segments.pop()); result.append(NamedElement.SEPARATOR); } result.delete((result.length() - NamedElement.SEPARATOR.length()), result.length()); return result.toString(); }
From source file:com.autentia.bcbp.elements.ConditionalItemsRepeated.java
private ConditionalItemsRepeated(String airlineNumericCode, String serialNumber, String selecteeIndicator, String internationalDocumentVerification, String marketingCarrierDesignator, String frecuentFlyerAirlineDesignator, String frecuentFlyerNumber, String iDADIndicator, String freeBaggageAllowance, String fastTrack) { Stack<Item> items = new Stack<Item>(); items.push(new Item(airlineNumericCode, airlineNumericCodeLength, 142, PaddingType.Number)); items.push(new Item(serialNumber, serialNumberLength, 143, PaddingType.Number)); items.push(new Item(selecteeIndicator, selecteeIndicatorLength, 18, PaddingType.String)); items.push(new Item(internationalDocumentVerification, internationalDocumentVerificationLength, 108, PaddingType.String)); items.push(new Item(marketingCarrierDesignator, marketingCarrierDesignatorLength, 19, PaddingType.String)); items.push(new Item(frecuentFlyerAirlineDesignator, frecuentFlyerAirlineDesignatorLength, 20, PaddingType.String)); items.push(new Item(frecuentFlyerNumber, frecuentFlyerNumberLength, 236, PaddingType.String)); items.push(new Item(iDADIndicator, IDADIndicatorLength, 89, PaddingType.String)); items.push(new Item(freeBaggageAllowance, freeBaggageAllowanceLength, 118, PaddingType.String)); items.push(new Item(fastTrack, fastTrackLength, 254, PaddingType.String)); final StringBuilder codeBuilder = new StringBuilder(); boolean starting = true; while (!items.isEmpty()) { Item item = items.pop(); if (starting && StringUtils.isNotBlank(item.getEncoded()) || !removeEndingEmptyElements) starting = false;//from ww w . j av a 2 s .co m if (!starting) codeBuilder.insert(0, item.getEncoded()); } final String baseCode = codeBuilder.toString(); if (StringUtils.isBlank(baseCode)) { code = ""; } else { code = StringUtils.leftPad(Integer.toHexString(baseCode.length()), variableSizeLength, "0") .toUpperCase() + baseCode; } }
From source file:net.firejack.platform.core.utils.Factory.java
public Class getGenericParameterClass(Class actualClass, Class genericClass, int parameterIndex) { if (!genericClass.isAssignableFrom(actualClass) || genericClass.equals(actualClass)) { throw new IllegalArgumentException( "Class " + genericClass.getName() + " is not a superclass of " + actualClass.getName() + "."); }//from w w w . ja v a2s .com Stack<ParameterizedType> types = new Stack<ParameterizedType>(); Class clazz = actualClass; while (true) { Type currentType = genericClass.isInterface() ? getGenericInterface(clazz, genericClass) : clazz.getGenericSuperclass(); Type rawType; if (currentType instanceof ParameterizedType) { ParameterizedType type = (ParameterizedType) currentType; types.push(type); rawType = type.getRawType(); } else { types.clear(); rawType = currentType; } if (!rawType.equals(genericClass)) { clazz = (Class) rawType; } else { break; } } if (types.isEmpty()) { return (Class) genericClass.getTypeParameters()[parameterIndex].getGenericDeclaration(); } Type result = types.pop().getActualTypeArguments()[parameterIndex]; while (result instanceof TypeVariable && !types.empty()) { int actualArgumentIndex = getParameterTypeDeclarationIndex((TypeVariable) result); ParameterizedType type = types.pop(); result = type.getActualTypeArguments()[actualArgumentIndex]; } if (result instanceof TypeVariable) { throw new IllegalStateException("Unable to resolve type variable " + result + "." + " Try to replace instances of parametrized class with its non-parameterized subtype."); } if (result instanceof ParameterizedType) { result = ((ParameterizedType) result).getRawType(); } if (result == null) { throw new IllegalStateException( "Unable to determine actual parameter type for " + actualClass.getName() + "."); } if (!(result instanceof Class)) { throw new IllegalStateException( "Actual parameter type for " + actualClass.getName() + " is not a Class."); } return (Class) result; }
From source file:nl.nn.adapterframework.batch.RecordTransformer.java
public Object handleRecord(IPipeLineSession session, List parsedRecord, ParameterResolutionContext prc) throws Exception { StringBuffer output = new StringBuffer(); Stack conditions = new Stack(); for (Iterator outputFieldIt = outputFields.iterator(); outputFieldIt.hasNext();) { IOutputField outputField = (IOutputField) outputFieldIt.next(); // if outputfields are to be seperator with delimiter if (outputSeparator != null && output.length() > 0) { output.append(outputSeparator); }/* w ww . java 2s . co m*/ // if not in a condition if (conditions.isEmpty()) { IOutputField condition = outputField.appendValue(outputField, output, parsedRecord); if (condition != null) { conditions.push(condition); } } // in condition else { IOutputField condition = (IOutputField) conditions.pop(); IOutputField newCondition = condition.appendValue(outputField, output, parsedRecord); if (newCondition != null) { conditions.push(condition); if (newCondition != condition) { conditions.push(newCondition); } } } } if (output.length() > 0) { return output.toString(); } return null; }
From source file:com.webcohesion.ofx4j.io.tagsoup.TestTagSoupOFXReader.java
/** * tests using sax to parse an OFX doc./*from ww w. jav a 2 s .co m*/ */ public void testVersion1() throws Exception { TagSoupOFXReader reader = new TagSoupOFXReader(); final Map<String, String> headers = new HashMap<String, String>(); final Stack<Map<String, Object>> aggregateStack = new Stack<Map<String, Object>>(); TreeMap<String, Object> root = new TreeMap<String, Object>(); aggregateStack.push(root); reader.setContentHandler(new DefaultHandler() { @Override public void onHeader(String name, String value) { LOG.debug(name + ":" + value); headers.put(name, value); } @Override public void onElement(String name, String value) { char[] tabs = new char[aggregateStack.size() * 2]; Arrays.fill(tabs, ' '); LOG.debug(new String(tabs) + name + "=" + value); aggregateStack.peek().put(name, value); } @Override public void startAggregate(String aggregateName) { char[] tabs = new char[aggregateStack.size() * 2]; Arrays.fill(tabs, ' '); LOG.debug(new String(tabs) + aggregateName + " {"); TreeMap<String, Object> aggregate = new TreeMap<String, Object>(); aggregateStack.peek().put(aggregateName, aggregate); aggregateStack.push(aggregate); } @Override public void endAggregate(String aggregateName) { aggregateStack.pop(); char[] tabs = new char[aggregateStack.size() * 2]; Arrays.fill(tabs, ' '); LOG.debug(new String(tabs) + "}"); } }); reader.parse(TestNanoXMLOFXReader.class.getResourceAsStream("example-response.ofx")); assertEquals(9, headers.size()); assertEquals(1, aggregateStack.size()); assertSame(root, aggregateStack.pop()); }
From source file:com.webcohesion.ofx4j.io.tagsoup.TestTagSoupOFXReader.java
/** * tests using sax to parse an OFX doc./*from w w w . j av a 2 s . c om*/ */ public void testSimpleVersion1() throws Exception { TagSoupOFXReader reader = new TagSoupOFXReader(); final Map<String, String> headers = new HashMap<String, String>(); final Stack<Map<String, Object>> aggregateStack = new Stack<Map<String, Object>>(); TreeMap<String, Object> root = new TreeMap<String, Object>(); aggregateStack.push(root); reader.setContentHandler(new DefaultHandler() { @Override public void onHeader(String name, String value) { LOG.debug(name + ":" + value); headers.put(name, value); } @Override public void onElement(String name, String value) { char[] tabs = new char[aggregateStack.size() * 2]; Arrays.fill(tabs, ' '); LOG.debug(new String(tabs) + name + "=" + value); aggregateStack.peek().put(name, value); } @Override public void startAggregate(String aggregateName) { char[] tabs = new char[aggregateStack.size() * 2]; Arrays.fill(tabs, ' '); LOG.debug(new String(tabs) + aggregateName + " {"); TreeMap<String, Object> aggregate = new TreeMap<String, Object>(); aggregateStack.peek().put(aggregateName, aggregate); aggregateStack.push(aggregate); } @Override public void endAggregate(String aggregateName) { aggregateStack.pop(); char[] tabs = new char[aggregateStack.size() * 2]; Arrays.fill(tabs, ' '); LOG.debug(new String(tabs) + "}"); } }); reader.parse(TestNanoXMLOFXReader.class.getResourceAsStream("simple.ofx")); assertEquals(9, headers.size()); assertEquals(1, aggregateStack.size()); assertSame(root, aggregateStack.pop()); }
From source file:org.apache.tajo.engine.planner.rewrite.FilterPushDownRule.java
@Override public LogicalNode visitProjection(FilterPushDownContext context, LogicalPlan plan, LogicalPlan.QueryBlock block, ProjectionNode projectionNode, Stack<LogicalNode> stack) throws PlanningException { LogicalNode childNode = projectionNode.getChild(); List<EvalNode> notMatched = new ArrayList<EvalNode>(); //copy -> origin BiMap<EvalNode, EvalNode> transformedMap = findCanPushdownAndTransform(context, block, projectionNode, childNode, notMatched, null, false, 0); context.setFiltersTobePushed(transformedMap.keySet()); stack.push(projectionNode);/*from w w w . java 2s . c om*/ childNode = visit(context, plan, plan.getBlock(childNode), childNode, stack); stack.pop(); // find not matched after visiting child for (EvalNode eval : context.pushingDownFilters) { notMatched.add(transformedMap.get(eval)); } EvalNode qual = null; if (notMatched.size() > 1) { // merged into one eval tree qual = AlgebraicUtil.createSingletonExprFromCNF(notMatched.toArray(new EvalNode[notMatched.size()])); } else if (notMatched.size() == 1) { // if the number of matched expr is one qual = notMatched.get(0); } // If there is not matched node add SelectionNode and clear context.pushingDownFilters if (qual != null && LogicalPlanner.checkIfBeEvaluatedAtThis(qual, projectionNode)) { SelectionNode selectionNode = plan.createNode(SelectionNode.class); selectionNode.setInSchema(childNode.getOutSchema()); selectionNode.setOutSchema(childNode.getOutSchema()); selectionNode.setQual(qual); block.registerNode(selectionNode); projectionNode.setChild(selectionNode); selectionNode.setChild(childNode); // clean all remain filters because all conditions are merged into a qual context.pushingDownFilters.clear(); } // if there are remain filters, recover the original names and give back to the upper query block. if (context.pushingDownFilters.size() > 0) { ImmutableSet<EvalNode> copy = ImmutableSet.copyOf(context.pushingDownFilters); context.pushingDownFilters.clear(); context.pushingDownFilters.addAll(reverseTransform(transformedMap, copy)); } return projectionNode; }
From source file:com.unboundid.scim2.common.utils.Parser.java
/** * Read a filter from the reader./*from w w w.j ava 2 s .c om*/ * * @param reader The reader to read the filter from. * @param isValueFilter Whether to read the filter as a value filter. * @return The parsed filter. * @throws BadRequestException If the filter string could not be parsed. */ private static Filter readFilter(final StringReader reader, final boolean isValueFilter) throws BadRequestException { final Stack<Filter> outputStack = new Stack<Filter>(); final Stack<String> precedenceStack = new Stack<String>(); String token; String previousToken = null; while ((token = readFilterToken(reader, isValueFilter)) != null) { if (token.equals("(") && expectsNewFilter(previousToken)) { precedenceStack.push(token); } else if (token.equalsIgnoreCase(FilterType.NOT.getStringValue()) && expectsNewFilter(previousToken)) { // "not" should be followed by an ( String nextToken = readFilterToken(reader, isValueFilter); if (nextToken == null) { throw BadRequestException.invalidFilter("Unexpected end of filter string"); } if (!nextToken.equals("(")) { final String msg = String.format("Expected '(' at position %d", reader.mark); throw BadRequestException.invalidFilter(msg); } precedenceStack.push(token); } else if (token.equals(")") && !expectsNewFilter(previousToken)) { String operator = closeGrouping(precedenceStack, outputStack, false); if (operator == null) { final String msg = String.format( "No opening parenthesis matching closing " + "parenthesis at position %d", reader.mark); throw BadRequestException.invalidFilter(msg); } if (operator.equalsIgnoreCase(FilterType.NOT.getStringValue())) { // Treat "not" the same as "(" except wrap everything in a not filter. outputStack.push(Filter.not(outputStack.pop())); } } else if (token.equalsIgnoreCase(FilterType.AND.getStringValue()) && !expectsNewFilter(previousToken)) { // and has higher precedence than or. precedenceStack.push(token); } else if (token.equalsIgnoreCase(FilterType.OR.getStringValue()) && !expectsNewFilter(previousToken)) { // pop all the pending ands first before pushing or. LinkedList<Filter> andComponents = new LinkedList<Filter>(); while (!precedenceStack.isEmpty()) { if (precedenceStack.peek().equalsIgnoreCase(FilterType.AND.getStringValue())) { precedenceStack.pop(); andComponents.addFirst(outputStack.pop()); } else { break; } if (!andComponents.isEmpty()) { andComponents.addFirst(outputStack.pop()); outputStack.push(Filter.and(andComponents)); } } precedenceStack.push(token); } else if (token.endsWith("[") && expectsNewFilter(previousToken)) { // This is a complex value filter. final Path filterAttribute; try { filterAttribute = parsePath(token.substring(0, token.length() - 1)); } catch (final BadRequestException e) { Debug.debugException(e); final String msg = String.format("Invalid attribute path at position %d: %s", reader.mark, e.getMessage()); throw BadRequestException.invalidFilter(msg); } if (filterAttribute.isRoot()) { final String msg = String.format("Attribute path expected at position %d", reader.mark); throw BadRequestException.invalidFilter(msg); } outputStack.push(Filter.hasComplexValue(filterAttribute, readFilter(reader, true))); } else if (isValueFilter && token.equals("]") && !expectsNewFilter(previousToken)) { break; } else if (expectsNewFilter(previousToken)) { // This must be an attribute path followed by operator and maybe value. final Path filterAttribute; try { filterAttribute = parsePath(token); } catch (final BadRequestException e) { Debug.debugException(e); final String msg = String.format("Invalid attribute path at position %d: %s", reader.mark, e.getMessage()); throw BadRequestException.invalidFilter(msg); } if (filterAttribute.isRoot()) { final String msg = String.format("Attribute path expected at position %d", reader.mark); throw BadRequestException.invalidFilter(msg); } String op = readFilterToken(reader, isValueFilter); if (op == null) { throw BadRequestException.invalidFilter("Unexpected end of filter string"); } if (op.equalsIgnoreCase(FilterType.PRESENT.getStringValue())) { outputStack.push(Filter.pr(filterAttribute)); } else { ValueNode valueNode; try { // Mark the beginning of the JSON value so we can later reset back // to this position and skip the actual chars that were consumed // by Jackson. The Jackson parser is buffered and reads everything // until the end of string. reader.mark(0); ScimJsonFactory scimJsonFactory = (ScimJsonFactory) JsonUtils.getObjectReader() .getFactory(); JsonParser parser = scimJsonFactory.createScimFilterParser(reader); // The object mapper will return a Java null for JSON null. // Have to distinguish between reading a JSON null and encountering // the end of string. if (parser.getCurrentToken() == null && parser.nextToken() == null) { // End of string. valueNode = null; } else { valueNode = parser.readValueAsTree(); // This is actually a JSON null. Use NullNode. if (valueNode == null) { valueNode = JsonUtils.getJsonNodeFactory().nullNode(); } } // Reset back to the beginning of the JSON value. reader.reset(); // Skip the number of chars consumed by JSON parser. reader.skip(parser.getCurrentLocation().getCharOffset()); } catch (IOException e) { final String msg = String.format("Invalid comparison value at position %d: %s", reader.mark, e.getMessage()); throw BadRequestException.invalidFilter(msg); } if (valueNode == null) { throw BadRequestException.invalidFilter("Unexpected end of filter string"); } if (op.equalsIgnoreCase(FilterType.EQUAL.getStringValue())) { outputStack.push(Filter.eq(filterAttribute, valueNode)); } else if (op.equalsIgnoreCase(FilterType.NOT_EQUAL.getStringValue())) { outputStack.push(Filter.ne(filterAttribute, valueNode)); } else if (op.equalsIgnoreCase(FilterType.CONTAINS.getStringValue())) { outputStack.push(Filter.co(filterAttribute, valueNode)); } else if (op.equalsIgnoreCase(FilterType.STARTS_WITH.getStringValue())) { outputStack.push(Filter.sw(filterAttribute, valueNode)); } else if (op.equalsIgnoreCase(FilterType.ENDS_WITH.getStringValue())) { outputStack.push(Filter.ew(filterAttribute, valueNode)); } else if (op.equalsIgnoreCase(FilterType.GREATER_THAN.getStringValue())) { outputStack.push(Filter.gt(filterAttribute, valueNode)); } else if (op.equalsIgnoreCase(FilterType.GREATER_OR_EQUAL.getStringValue())) { outputStack.push(Filter.ge(filterAttribute, valueNode)); } else if (op.equalsIgnoreCase(FilterType.LESS_THAN.getStringValue())) { outputStack.push(Filter.lt(filterAttribute, valueNode)); } else if (op.equalsIgnoreCase(FilterType.LESS_OR_EQUAL.getStringValue())) { outputStack.push(Filter.le(filterAttribute, valueNode)); } else { final String msg = String.format("Unrecognized attribute operator '%s' at position %d. " + "Expected: eq,ne,co,sw,ew,pr,gt,ge,lt,le", op, reader.mark); throw BadRequestException.invalidFilter(msg); } } } else { final String msg = String.format("Unexpected character '%s' at position %d", token, reader.mark); throw BadRequestException.invalidFilter(msg); } previousToken = token; } closeGrouping(precedenceStack, outputStack, true); if (outputStack.isEmpty()) { throw BadRequestException.invalidFilter("Unexpected end of filter string"); } return outputStack.pop(); }