List of usage examples for java.util Stack push
public E push(E item)
From source file:com.unboundid.scim2.common.utils.Parser.java
/** * Read a filter from the reader.//from ww w. j a va 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(); }
From source file:com.espertech.esper.epl.spec.PatternStreamSpecRaw.java
private static void recursiveCompile(EvalFactoryNode evalNode, StatementContext context, ExprEvaluatorContext evaluatorContext, Set<String> eventTypeReferences, boolean isInsertInto, MatchEventSpec tags, Deque<Integer> subexpressionIdStack, Stack<EvalFactoryNode> parentNodeStack, LinkedHashSet<String> allTagNamesOrdered) throws ExprValidationException { int counter = 0; parentNodeStack.push(evalNode); for (EvalFactoryNode child : evalNode.getChildNodes()) { subexpressionIdStack.addLast(counter++); recursiveCompile(child, context, evaluatorContext, eventTypeReferences, isInsertInto, tags, subexpressionIdStack, parentNodeStack, allTagNamesOrdered); subexpressionIdStack.removeLast(); }//from w w w .ja v a2 s . c o m parentNodeStack.pop(); LinkedHashMap<String, Pair<EventType, String>> newTaggedEventTypes = null; LinkedHashMap<String, Pair<EventType, String>> newArrayEventTypes = null; if (evalNode instanceof EvalFilterFactoryNode) { EvalFilterFactoryNode filterNode = (EvalFilterFactoryNode) evalNode; String eventName = filterNode.getRawFilterSpec().getEventTypeName(); EventType resolvedEventType = FilterStreamSpecRaw.resolveType(context.getEngineURI(), eventName, context.getEventAdapterService(), context.getPlugInTypeResolutionURIs()); EventType finalEventType = resolvedEventType; String optionalTag = filterNode.getEventAsName(); boolean isPropertyEvaluation = false; boolean isParentMatchUntil = isParentMatchUntil(evalNode, parentNodeStack); // obtain property event type, if final event type is properties if (filterNode.getRawFilterSpec().getOptionalPropertyEvalSpec() != null) { PropertyEvaluator optionalPropertyEvaluator = PropertyEvaluatorFactory.makeEvaluator( filterNode.getRawFilterSpec().getOptionalPropertyEvalSpec(), resolvedEventType, filterNode.getEventAsName(), context.getEventAdapterService(), context.getMethodResolutionService(), context.getSchedulingService(), context.getVariableService(), context.getEngineURI(), context.getStatementId(), context.getStatementName(), context.getAnnotations(), subexpressionIdStack, context.getConfigSnapshot()); finalEventType = optionalPropertyEvaluator.getFragmentEventType(); isPropertyEvaluation = true; } if (finalEventType instanceof EventTypeSPI) { eventTypeReferences.add(((EventTypeSPI) finalEventType).getMetadata().getPrimaryName()); } // If a tag was supplied for the type, the tags must stay with this type, i.e. a=BeanA -> b=BeanA -> a=BeanB is a no if (optionalTag != null) { Pair<EventType, String> pair = tags.getTaggedEventTypes().get(optionalTag); EventType existingType = null; if (pair != null) { existingType = pair.getFirst(); } if (existingType == null) { pair = tags.getArrayEventTypes().get(optionalTag); if (pair != null) { throw new ExprValidationException("Tag '" + optionalTag + "' for event '" + eventName + "' used in the repeat-until operator cannot also appear in other filter expressions"); } } if ((existingType != null) && (existingType != finalEventType)) { throw new ExprValidationException("Tag '" + optionalTag + "' for event '" + eventName + "' has already been declared for events of type " + existingType.getUnderlyingType().getName()); } pair = new Pair<EventType, String>(finalEventType, eventName); // add tagged type if (isPropertyEvaluation || isParentMatchUntil) { newArrayEventTypes = new LinkedHashMap<String, Pair<EventType, String>>(); newArrayEventTypes.put(optionalTag, pair); } else { newTaggedEventTypes = new LinkedHashMap<String, Pair<EventType, String>>(); newTaggedEventTypes.put(optionalTag, pair); } } // For this filter, filter types are all known tags at this time, // and additionally stream 0 (self) is our event type. // Stream type service allows resolution by property name event if that name appears in other tags. // by defaulting to stream zero. // Stream zero is always the current event type, all others follow the order of the map (stream 1 to N). String selfStreamName = optionalTag; if (selfStreamName == null) { selfStreamName = "s_" + UuidGenerator.generate(); } LinkedHashMap<String, Pair<EventType, String>> filterTypes = new LinkedHashMap<String, Pair<EventType, String>>(); Pair<EventType, String> typePair = new Pair<EventType, String>(finalEventType, eventName); filterTypes.put(selfStreamName, typePair); filterTypes.putAll(tags.getTaggedEventTypes()); // for the filter, specify all tags used LinkedHashMap<String, Pair<EventType, String>> filterTaggedEventTypes = new LinkedHashMap<String, Pair<EventType, String>>( tags.getTaggedEventTypes()); filterTaggedEventTypes.remove(optionalTag); // handle array tags (match-until clause) LinkedHashMap<String, Pair<EventType, String>> arrayCompositeEventTypes = null; if (tags.getArrayEventTypes() != null && !tags.getArrayEventTypes().isEmpty()) { arrayCompositeEventTypes = new LinkedHashMap<String, Pair<EventType, String>>(); String patternSubexEventType = getPatternSubexEventType(context.getStatementId(), "pattern", subexpressionIdStack); for (Map.Entry<String, Pair<EventType, String>> entry : tags.getArrayEventTypes().entrySet()) { LinkedHashMap<String, Pair<EventType, String>> specificArrayType = new LinkedHashMap<String, Pair<EventType, String>>(); specificArrayType.put(entry.getKey(), entry.getValue()); EventType arrayTagCompositeEventType = context.getEventAdapterService() .createSemiAnonymousMapType(patternSubexEventType, Collections.<String, Pair<EventType, String>>emptyMap(), specificArrayType, isInsertInto); String tag = entry.getKey(); if (!filterTypes.containsKey(tag)) { Pair<EventType, String> pair = new Pair<EventType, String>(arrayTagCompositeEventType, tag); filterTypes.put(tag, pair); arrayCompositeEventTypes.put(tag, pair); } } } StreamTypeService streamTypeService = new StreamTypeServiceImpl(filterTypes, context.getEngineURI(), true, false); List<ExprNode> exprNodes = filterNode.getRawFilterSpec().getFilterExpressions(); FilterSpecCompiled spec = FilterSpecCompiler.makeFilterSpec(resolvedEventType, eventName, exprNodes, filterNode.getRawFilterSpec().getOptionalPropertyEvalSpec(), filterTaggedEventTypes, arrayCompositeEventTypes, streamTypeService, null, context, subexpressionIdStack); filterNode.setFilterSpec(spec); } else if (evalNode instanceof EvalObserverFactoryNode) { EvalObserverFactoryNode observerNode = (EvalObserverFactoryNode) evalNode; try { ObserverFactory observerFactory = context.getPatternResolutionService() .create(observerNode.getPatternObserverSpec()); StreamTypeService streamTypeService = getStreamTypeService(context.getEngineURI(), context.getStatementId(), context.getEventAdapterService(), tags.getTaggedEventTypes(), tags.getArrayEventTypes(), subexpressionIdStack, "observer"); ExprValidationContext validationContext = new ExprValidationContext(streamTypeService, context.getMethodResolutionService(), null, context.getSchedulingService(), context.getVariableService(), evaluatorContext, context.getEventAdapterService(), context.getStatementName(), context.getStatementId(), context.getAnnotations(), context.getContextDescriptor()); List<ExprNode> validated = validateExpressions( observerNode.getPatternObserverSpec().getObjectParameters(), validationContext); MatchedEventConvertor convertor = new MatchedEventConvertorImpl(tags.getTaggedEventTypes(), tags.getArrayEventTypes(), allTagNamesOrdered, context.getEventAdapterService()); observerNode.setObserverFactory(observerFactory); observerFactory.setObserverParameters(validated, convertor); } catch (ObserverParameterException e) { throw new ExprValidationException("Invalid parameter for pattern observer: " + e.getMessage(), e); } catch (PatternObjectException e) { throw new ExprValidationException("Failed to resolve pattern observer: " + e.getMessage(), e); } } else if (evalNode instanceof EvalGuardFactoryNode) { EvalGuardFactoryNode guardNode = (EvalGuardFactoryNode) evalNode; try { GuardFactory guardFactory = context.getPatternResolutionService() .create(guardNode.getPatternGuardSpec()); StreamTypeService streamTypeService = getStreamTypeService(context.getEngineURI(), context.getStatementId(), context.getEventAdapterService(), tags.getTaggedEventTypes(), tags.getArrayEventTypes(), subexpressionIdStack, "guard"); ExprValidationContext validationContext = new ExprValidationContext(streamTypeService, context.getMethodResolutionService(), null, context.getSchedulingService(), context.getVariableService(), evaluatorContext, context.getEventAdapterService(), context.getStatementName(), context.getStatementId(), context.getAnnotations(), context.getContextDescriptor()); List<ExprNode> validated = validateExpressions( guardNode.getPatternGuardSpec().getObjectParameters(), validationContext); MatchedEventConvertor convertor = new MatchedEventConvertorImpl(tags.getTaggedEventTypes(), tags.getArrayEventTypes(), allTagNamesOrdered, context.getEventAdapterService()); guardNode.setGuardFactory(guardFactory); guardFactory.setGuardParameters(validated, convertor); } catch (GuardParameterException e) { throw new ExprValidationException("Invalid parameter for pattern guard: " + e.getMessage(), e); } catch (PatternObjectException e) { throw new ExprValidationException("Failed to resolve pattern guard: " + e.getMessage(), e); } } else if (evalNode instanceof EvalEveryDistinctFactoryNode) { EvalEveryDistinctFactoryNode distinctNode = (EvalEveryDistinctFactoryNode) evalNode; MatchEventSpec matchEventFromChildNodes = analyzeMatchEvent(distinctNode); StreamTypeService streamTypeService = getStreamTypeService(context.getEngineURI(), context.getStatementId(), context.getEventAdapterService(), matchEventFromChildNodes.getTaggedEventTypes(), matchEventFromChildNodes.getArrayEventTypes(), subexpressionIdStack, "every-distinct"); ExprValidationContext validationContext = new ExprValidationContext(streamTypeService, context.getMethodResolutionService(), null, context.getSchedulingService(), context.getVariableService(), evaluatorContext, context.getEventAdapterService(), context.getStatementName(), context.getStatementId(), context.getAnnotations(), context.getContextDescriptor()); List<ExprNode> validated; try { validated = validateExpressions(distinctNode.getExpressions(), validationContext); } catch (ExprValidationPropertyException ex) { throw new ExprValidationPropertyException(ex.getMessage() + ", every-distinct requires that all properties resolve from sub-expressions to the every-distinct", ex.getCause()); } MatchedEventConvertor convertor = new MatchedEventConvertorImpl( matchEventFromChildNodes.getTaggedEventTypes(), matchEventFromChildNodes.getArrayEventTypes(), allTagNamesOrdered, context.getEventAdapterService()); distinctNode.setConvertor(convertor); // Determine whether some expressions are constants or time period List<ExprNode> distinctExpressions = new ArrayList<ExprNode>(); Long msecToExpire = null; for (ExprNode expr : validated) { if (expr instanceof ExprTimePeriod) { Double secondsExpire = (Double) ((ExprTimePeriod) expr).evaluate(null, true, evaluatorContext); if ((secondsExpire != null) && (secondsExpire > 0)) { msecToExpire = Math.round(1000d * secondsExpire); } log.debug("Setting every-distinct msec-to-expire to " + msecToExpire); } else if (expr.isConstantResult()) { log.warn( "Every-distinct node utilizes an expression returning a constant value, please check expression '" + expr.toExpressionString() + "', not adding expression to distinct-value expression list"); } else { distinctExpressions.add(expr); } } if (distinctExpressions.isEmpty()) { throw new ExprValidationException( "Every-distinct node requires one or more distinct-value expressions that each return non-constant result values"); } distinctNode.setDistinctExpressions(distinctExpressions, msecToExpire); } else if (evalNode instanceof EvalMatchUntilFactoryNode) { EvalMatchUntilFactoryNode matchUntilNode = (EvalMatchUntilFactoryNode) evalNode; // compile bounds expressions, if any MatchEventSpec untilMatchEventSpec = new MatchEventSpec(tags.getTaggedEventTypes(), tags.getArrayEventTypes()); StreamTypeService streamTypeService = getStreamTypeService(context.getEngineURI(), context.getStatementId(), context.getEventAdapterService(), untilMatchEventSpec.getTaggedEventTypes(), untilMatchEventSpec.getArrayEventTypes(), subexpressionIdStack, "until"); ExprValidationContext validationContext = new ExprValidationContext(streamTypeService, context.getMethodResolutionService(), null, context.getSchedulingService(), context.getVariableService(), evaluatorContext, context.getEventAdapterService(), context.getStatementName(), context.getStatementId(), context.getAnnotations(), context.getContextDescriptor()); String message = "Match-until bounds value expressions must return a numeric value"; if (matchUntilNode.getLowerBounds() != null) { ExprNode validated = ExprNodeUtility.getValidatedSubtree(matchUntilNode.getLowerBounds(), validationContext); matchUntilNode.setLowerBounds(validated); if ((validated.getExprEvaluator().getType() == null) || (!JavaClassHelper.isNumeric(validated.getExprEvaluator().getType()))) { throw new ExprValidationException(message); } } if (matchUntilNode.getUpperBounds() != null) { ExprNode validated = ExprNodeUtility.getValidatedSubtree(matchUntilNode.getUpperBounds(), validationContext); matchUntilNode.setUpperBounds(validated); if ((validated.getExprEvaluator().getType() == null) || (!JavaClassHelper.isNumeric(validated.getExprEvaluator().getType()))) { throw new ExprValidationException(message); } } MatchedEventConvertor convertor = new MatchedEventConvertorImpl( untilMatchEventSpec.getTaggedEventTypes(), untilMatchEventSpec.getArrayEventTypes(), allTagNamesOrdered, context.getEventAdapterService()); matchUntilNode.setConvertor(convertor); // compile new tag lists Set<String> arrayTags = null; EvalNodeAnalysisResult matchUntilAnalysisResult = EvalNodeUtil .recursiveAnalyzeChildNodes(matchUntilNode.getChildNodes().get(0)); for (EvalFilterFactoryNode filterNode : matchUntilAnalysisResult.getFilterNodes()) { String optionalTag = filterNode.getEventAsName(); if (optionalTag != null) { if (arrayTags == null) { arrayTags = new HashSet<String>(); } arrayTags.add(optionalTag); } } if (arrayTags != null) { for (String arrayTag : arrayTags) { if (!tags.getArrayEventTypes().containsKey(arrayTag)) { tags.getArrayEventTypes().put(arrayTag, tags.getTaggedEventTypes().get(arrayTag)); tags.getTaggedEventTypes().remove(arrayTag); } } } matchUntilNode.setTagsArrayedSet(getIndexesForTags(allTagNamesOrdered, arrayTags)); } else if (evalNode instanceof EvalFollowedByFactoryNode) { EvalFollowedByFactoryNode followedByNode = (EvalFollowedByFactoryNode) evalNode; StreamTypeService streamTypeService = new StreamTypeServiceImpl(context.getEngineURI(), false); ExprValidationContext validationContext = new ExprValidationContext(streamTypeService, context.getMethodResolutionService(), null, context.getSchedulingService(), context.getVariableService(), evaluatorContext, context.getEventAdapterService(), context.getStatementName(), context.getStatementId(), context.getAnnotations(), context.getContextDescriptor()); if (followedByNode.getOptionalMaxExpressions() != null) { List<ExprNode> validated = new ArrayList<ExprNode>(); for (ExprNode maxExpr : followedByNode.getOptionalMaxExpressions()) { if (maxExpr == null) { validated.add(null); } else { ExprNodeSummaryVisitor visitor = new ExprNodeSummaryVisitor(); maxExpr.accept(visitor); if (!visitor.isPlain()) { String errorMessage = "Invalid maximum expression in followed-by, " + visitor.getMessage() + " are not allowed within the expression"; log.error(errorMessage); throw new ExprValidationException(errorMessage); } ExprNode validatedExpr = ExprNodeUtility.getValidatedSubtree(maxExpr, validationContext); validated.add(validatedExpr); if ((validatedExpr.getExprEvaluator().getType() == null) || (!JavaClassHelper.isNumeric(validatedExpr.getExprEvaluator().getType()))) { String message = "Invalid maximum expression in followed-by, the expression must return an integer value"; throw new ExprValidationException(message); } } } followedByNode.setOptionalMaxExpressions(validated); } } if (newTaggedEventTypes != null) { tags.getTaggedEventTypes().putAll(newTaggedEventTypes); } if (newArrayEventTypes != null) { tags.getArrayEventTypes().putAll(newArrayEventTypes); } }
From source file:org.sift.batch.tuple.ProcessorChainItemProcessor.java
/** * Interface method implementation. Subjects the specified Tuple through a set of configured {@link Processor} instances, * @see org.springframework.batch.item.ItemProcessor#process(java.lang.Object) *///from w w w .j a v a 2 s . c o m @SuppressWarnings("unchecked") public S process(T paramTuple) throws Exception { Tuple tuple = (Tuple) paramTuple; //Stack holding list of tuples to be passed on to the next Processor Stack<Tuple> returnedTuples = new Stack<Tuple>(); returnedTuples.push(tuple); for (Processor p : this.getProcessors()) { MemOutputCollector collector = new MemOutputCollector(); //Process all the tuples for (Tuple returnTuple : returnedTuples) { p.process(returnTuple, collector); } //Clear and add the new tuples returnedTuples.clear(); returnedTuples.addAll(collector.getEmittedTuples()); // clear the collector as we are done processing the Tuple instances that it is holding collector.getEmittedTuples().clear(); } List<Tuple> returnTuples = new LinkedList<Tuple>(returnedTuples); return (S) returnTuples; }
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 v a 2 s .c o 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.amalto.core.history.UniqueIdTransformer.java
public void addIds(org.w3c.dom.Document document) { Stack<Integer> levels = new Stack<Integer>(); levels.push(0); {/*from ww w .j a va2s . c om*/ Element documentElement = document.getDocumentElement(); if (documentElement != null) { _addIds(document, documentElement, levels); } } levels.pop(); }
From source file:com.frostwire.android.gui.Librarian.java
/** * Given a folder path it'll return all the files contained within it and it's subfolders * as a flat set of Files./* ww w . j a v a 2 s. co m*/ * <p> * Non-recursive implementation, up to 20% faster in tests than recursive implementation. :) * * @param folder * @param extensions If you only need certain files filtered by their extensions, use this string array (without the "."). or set to null if you want all files. e.g. ["txt","jpg"] if you only want text files and jpegs. * @return The set of files. * @author gubatron */ private static Collection<File> getAllFolderFiles(File folder, String[] extensions) { Set<File> results = new HashSet<>(); Stack<File> subFolders = new Stack<>(); File currentFolder = folder; while (currentFolder != null && currentFolder.isDirectory() && currentFolder.canRead()) { File[] fs = null; try { fs = currentFolder.listFiles(); } catch (SecurityException e) { } if (fs != null && fs.length > 0) { for (File f : fs) { if (!f.isDirectory()) { if (extensions == null || FilenameUtils.isExtension(f.getName(), extensions)) { results.add(f); } } else { subFolders.push(f); } } } if (!subFolders.isEmpty()) { currentFolder = subFolders.pop(); } else { currentFolder = null; } } return results; }
From source file:edu.umn.cs.spatialHadoop.core.RectangleNN.java
/** * Directly unions the given list of polygons using a safe method that tries * to avoid geometry exceptions. First, it tries the buffer(0) method. It it * fails, it falls back to the tradition union method. * @param polys//from w ww.ja v a 2 s. c om * @param progress * @return * @throws IOException */ public static Geometry safeUnion(List<Geometry> polys, Progressable progress) throws IOException { if (polys.size() == 1) return polys.get(0); Stack<Integer> rangeStarts = new Stack<Integer>(); Stack<Integer> rangeEnds = new Stack<Integer>(); rangeStarts.push(0); rangeEnds.push(polys.size()); List<Geometry> results = new ArrayList<Geometry>(); final GeometryFactory geomFactory = new GeometryFactory(); // Minimum range size that is broken into two subranges final int MinimumThreshold = 10; // Progress numerator and denominator int progressNum = 0, progressDen = polys.size(); while (!rangeStarts.isEmpty()) { int rangeStart = rangeStarts.pop(); int rangeEnd = rangeEnds.pop(); try { // Union using the buffer operation GeometryCollection rangeInOne = (GeometryCollection) geomFactory .buildGeometry(polys.subList(rangeStart, rangeEnd)); Geometry rangeUnion = rangeInOne.buffer(0); results.add(rangeUnion); progressNum += rangeEnd - rangeStart; } catch (Exception e) { LOG.warn("Exception in merging " + (rangeEnd - rangeStart) + " polygons", e); // Fall back to the union operation if (rangeEnd - rangeStart < MinimumThreshold) { LOG.info("Error in union " + rangeStart + "-" + rangeEnd); // Do the union directly using the old method (union) Geometry rangeUnion = geomFactory.buildGeometry(new ArrayList<Geometry>()); for (int i = rangeStart; i < rangeEnd; i++) { LOG.info(polys.get(i).toText()); } for (int i = rangeStart; i < rangeEnd; i++) { try { rangeUnion = rangeUnion.union(polys.get(i)); } catch (Exception e1) { // Log the error and skip it to allow the method to finish LOG.error("Error computing union", e); } } results.add(rangeUnion); progressNum += rangeEnd - rangeStart; } else { // Further break the range into two subranges rangeStarts.push(rangeStart); rangeEnds.push((rangeStart + rangeEnd) / 2); rangeStarts.push((rangeStart + rangeEnd) / 2); rangeEnds.push(rangeEnd); progressDen++; } } if (progress != null) progress.progress(progressNum / (float) progressDen); } // Finally, union all the results Geometry finalResult = results.remove(results.size() - 1); while (!results.isEmpty()) { try { finalResult = finalResult.union(results.remove(results.size() - 1)); } catch (Exception e) { LOG.error("Error in union", e); } progressNum++; progress.progress(progressNum / (float) progressDen); } return finalResult; }
From source file:net.bulletin.pdi.xero.step.support.XMLChunkerTest.java
private Stack<String> createExpectedContainerElementsStack() { Stack<String> result = new Stack<String>(); result.push("Response"); result.push("Artists"); result.push("Artist"); return result; }
From source file:gov.nih.nci.calims2.ui.common.externalidentifier.ExternalIdentifierFormTest.java
/** * Test the controller getSubmittedEntity method. * @throws Exception /*from w ww .j a va 2s .c o m*/ */ @SuppressWarnings("unchecked") @Test public void testGetSubmittedEntity() throws Exception { ExternalIdentifierForm form = new ExternalIdentifierForm(); form.setStatus(ExternalIdentifierStatus.DEFAULT.getName()); Stack<StackFrame> context = FlowContextHolder.newContext(); StackFrame frame = new BaseStackFrame(); context.push(frame); frame.addAttribute("persistentClass", persistentClass); frame.addAttribute("id", new Long(1)); ExternalIdentifier entity = form.getSubmittedEntity(); EntityWithId result = (EntityWithId) PropertyUtils.getProperty(entity, propertyName); CRUDFormAssert.assertEntity((Class<EntityWithId>) persistentClass, result, 1L); assertEquals("Wrong status in the entity", ExternalIdentifierStatus.DEFAULT, entity.getStatus()); }
From source file:net.servicefixture.fitnesse.FixtureTemplateCreator.java
/** * Generates the test table template for the ServiceFixture and prints out * to standard console./*from w ww .j av a2s .com*/ * * @param clazz */ private void generateServiceFixtureTemplate(Class clazz) throws Exception { ServiceFixture fixture = (ServiceFixture) clazz.newInstance(); Method operation = fixture.getServiceOperation(); if (operation == null) { writeLine("Unable to generate template for fixture:" + fixture.getClass().getName() + " because service operation is unknown."); return; } Class[] parameterTypes = operation.getParameterTypes(); Class returnType = operation.getReturnType(); for (int i = 0; i < parameterTypes.length; i++) { String prefix = "|set|" + getParameterName(parameterTypes[i]); Stack<Class> ancestors = new Stack<Class>(); ancestors.push(CollectionBuilderFactory.getElementType(parameterTypes[i])); addTableRowsForType(ancestors, prefix, CollectionBuilderFactory.getElementType(parameterTypes[i]), true); } writeLine("|invoke||"); if ("void".equals(returnType.getName())) { writeLine("|check|response == null|true|"); } else { writeLine("|check|response != null|true|"); String prefix = "|check|response"; if (CollectionBuilderFactory.isCollectionType(returnType)) { writeLine("|check|response.size() > 0|true|"); writeLine("|check|response.size()||"); prefix = prefix + "[0]"; } Stack<Class> ancestors = new Stack<Class>(); ancestors.push(CollectionBuilderFactory.getElementType(returnType)); addTableRowsForType(ancestors, prefix, CollectionBuilderFactory.getElementType(returnType), false); } }