List of usage examples for java.util Stack peek
public synchronized E peek()
From source file:com.sun.socialsite.pojos.PropDefinition.java
protected void init(PropDefinition profileDef, InputStream input) throws SocialSiteException { try {// w w w.jav a 2 s. co m XMLInputFactory factory = XMLInputFactory.newInstance(); XMLStreamReader parser = factory.createXMLStreamReader(input); String ns = null; // TODO: namespace for ProfileDef // hold the current things we're working on Map<String, DisplaySectionDefinition> sdefs = new LinkedHashMap<String, DisplaySectionDefinition>(); Stack<PropertyDefinitionHolder> propertyHolderStack = new Stack<PropertyDefinitionHolder>(); List<AllowedValue> allowedValues = null; PropertyDefinition pdef = null; for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()) { switch (event) { case XMLStreamConstants.START_ELEMENT: log.debug("START ELEMENT -- " + parser.getLocalName()); if ("display-section".equals(parser.getLocalName())) { propertyHolderStack.push(new DisplaySectionDefinition(parser.getAttributeValue(ns, "name"), parser.getAttributeValue(ns, "namekey"))); } else if ("property".equals(parser.getLocalName())) { PropertyDefinitionHolder holder = propertyHolderStack.peek(); pdef = new PropertyDefinition(holder.getBasePath(), parser.getAttributeValue(ns, "name"), parser.getAttributeValue(ns, "namekey"), parser.getAttributeValue(ns, "type")); } else if ("object".equals(parser.getLocalName())) { PropertyDefinitionHolder holder = propertyHolderStack.peek(); propertyHolderStack.push(new PropertyObjectDefinition(holder.getBasePath(), parser.getAttributeValue(ns, "name"), parser.getAttributeValue(ns, "namekey"))); } else if ("collection".equals(parser.getLocalName())) { PropertyDefinitionHolder holder = propertyHolderStack.peek(); propertyHolderStack.push(new PropertyObjectCollectionDefinition(holder.getBasePath(), parser.getAttributeValue(ns, "name"), parser.getAttributeValue(ns, "namekey"))); } else if ("allowed-values".equals(parser.getLocalName())) { allowedValues = new ArrayList<AllowedValue>(); } else if ("value".equals(parser.getLocalName())) { AllowedValue allowedValue = new AllowedValue(parser.getAttributeValue(ns, "name"), parser.getAttributeValue(ns, "namekey")); allowedValues.add(allowedValue); } else if ("default-value".equals(parser.getLocalName())) { pdef.setDefaultValue(parser.getText()); } break; case XMLStreamConstants.END_ELEMENT: log.debug("END ELEMENT -- " + parser.getLocalName()); if ("display-section".equals(parser.getLocalName())) { DisplaySectionDefinition sdef = (DisplaySectionDefinition) propertyHolderStack.pop(); sdefs.put(sdef.getName(), sdef); } else if ("property".equals(parser.getLocalName())) { PropertyDefinitionHolder holder = propertyHolderStack.peek(); holder.getPropertyDefinitions().add(pdef); propertyDefs.put(pdef.getName(), pdef); pdef = null; } else if ("object".equals(parser.getLocalName())) { PropertyObjectDefinition odef = (PropertyObjectDefinition) propertyHolderStack.pop(); PropertyDefinitionHolder holder = propertyHolderStack.peek(); holder.getPropertyObjectDefinitions().add(odef); // add to list of all property object defs propertyObjectDefs.put(odef.getName(), odef); odef = null; } else if ("collection".equals(parser.getLocalName())) { PropertyObjectCollectionDefinition cdef = (PropertyObjectCollectionDefinition) propertyHolderStack .pop(); PropertyDefinitionHolder holder = propertyHolderStack.peek(); holder.getPropertyObjectCollectionDefinitions().add(cdef); // add to list of all property object defs propertyObjectCollectionDefs.put(cdef.getName(), cdef); cdef = null; } else if ("allowed-values".equals(parser.getLocalName())) { pdef.setAllowedValues(allowedValues); allowedValues = null; } break; case XMLStreamConstants.CHARACTERS: break; case XMLStreamConstants.CDATA: break; } // end switch } // end while parser.close(); profileDef.sectionDefs = sdefs; } catch (Exception ex) { throw new SocialSiteException("ERROR parsing profile definitions", ex); } }
From source file:org.xlrnet.tibaija.processor.FullTIBasicVisitor.java
private int internalHandleSkipFlowLogic(int currentCommandCounter, List<TIBasicParser.CommandContext> commandList, Stack<ControlFlowElement.ControlFlowToken> skipCommandsStack, TIBasicParser.CommandContext nextCommand) { int commandListSize = commandList.size(); final String enumName = nextCommand.controlFlowStatement().flowType; ControlFlowElement.ControlFlowToken currentFlowToken = EnumUtils .getEnum(ControlFlowElement.ControlFlowToken.class, enumName); ControlFlowElement.ControlFlowToken topToken = skipCommandsStack.peek(); if (currentFlowToken == null) { throw new IllegalStateException( "Internal error: control flow token is null at command " + currentCommandCounter); }// w w w . j a v a 2s. c om switch (currentFlowToken) { case IF: // Look ahead if the next command might be a "Then" i.e. if it is a controlflow statement if (commandListSize <= currentCommandCounter + 1) { throw new IllegalControlFlowException(-1, -1, "Illegal 'If' at the end of the program"); } else if (commandList.get(currentCommandCounter + 1).isControlFlowStatement) { skipCommandsStack.push(currentFlowToken); LOGGER.debug("Predicted multiline IF while skipping over command {}", currentCommandCounter); } else { LOGGER.debug("Skipping over single line IF at command {}", currentCommandCounter); currentCommandCounter++; } break; case THEN: if (topToken != ControlFlowElement.ControlFlowToken.IF) throw new IllegalControlFlowException(-1, -1, "Illegal 'Then' Statement without preceding 'If'"); skipCommandsStack.pop(); skipCommandsStack.push(currentFlowToken); break; case ELSE: if (skipCommandsStack.size() > 1 && topToken != ControlFlowElement.ControlFlowToken.THEN) throw new IllegalControlFlowException(-1, -1, "Illegal 'Else' Statement without preceding 'Then' "); skipCommandsStack.pop(); if (!skipCommandsStack.empty()) skipCommandsStack.push(topToken); break; case FOR: case WHILE: case REPEAT: skipCommandsStack.push(currentFlowToken); break; case END: skipCommandsStack.pop(); break; case GOTO: case LABEL: break; default: throw new IllegalStateException("Illegal flow token: " + currentFlowToken); } if (skipCommandsStack.empty()) { LOGGER.debug("Skip stack is now empty - continuing execution at command {}", currentCommandCounter + 1); } return currentCommandCounter; }
From source file:org.apache.tajo.plan.rewrite.rules.FilterPushDownRule.java
@Override public LogicalNode visitFilter(FilterPushDownContext context, LogicalPlan plan, LogicalPlan.QueryBlock block, SelectionNode selNode, Stack<LogicalNode> stack) throws TajoException { context.pushingDownFilters.addAll(/*from ww w. j a va 2 s .c o m*/ new HashSet<>(Arrays.asList(AlgebraicUtil.toConjunctiveNormalFormArray(selNode.getQual())))); stack.push(selNode); visit(context, plan, block, selNode.getChild(), stack); stack.pop(); if (context.pushingDownFilters.size() == 0) { // remove the selection operator if there is no search condition after selection push. LogicalNode node = stack.peek(); if (node instanceof UnaryNode) { UnaryNode unary = (UnaryNode) node; unary.setChild(selNode.getChild()); } else { throw new TajoInternalError("The node must be an unary node"); } } else { // if there remain search conditions // check if it can be evaluated here Set<EvalNode> matched = new HashSet<>(); for (EvalNode eachEval : context.pushingDownFilters) { if (LogicalPlanner.checkIfBeEvaluatedAtThis(eachEval, selNode)) { matched.add(eachEval); } } // if there are search conditions which can be evaluated here, // push down them and remove them from context.pushingDownFilters. if (matched.size() > 0) { selNode.setQual( AlgebraicUtil.createSingletonExprFromCNF(matched.toArray(new EvalNode[matched.size()]))); context.pushingDownFilters.removeAll(matched); } } return selNode; }
From source file:tajo.engine.planner.LogicalOptimizer.java
/** * Groupby, Join, and Scan can project necessary columns. * This method has three roles:/*from w w w . ja va2 s . c om*/ * 1) collect column reference necessary for sortkeys, join keys, selection conditions, grouping fields, * and having conditions * 2) shrink the output schema of each operator so that the operator reduces the output columns according to * the necessary columns of their parent operators * 3) shrink the input schema of each operator according to the shrunk output schemas of the child operators. * * * @param ctx * @param node * //@param necessary - columns necessary for above logical nodes, but it excepts the fields for the target list * //@param targetList * @return */ private static LogicalNode pushProjectionRecursive(final PlanningContext ctx, final OptimizationContext optContext, final LogicalNode node, final Stack<LogicalNode> stack, final Set<Column> necessary) throws CloneNotSupportedException { LogicalNode outer; LogicalNode inner; switch (node.getType()) { case ROOT: // It does not support the projection LogicalRootNode root = (LogicalRootNode) node; stack.add(root); outer = pushProjectionRecursive(ctx, optContext, root.getSubNode(), stack, necessary); root.setInSchema(outer.getOutSchema()); root.setOutSchema(outer.getOutSchema()); break; case STORE: StoreTableNode store = (StoreTableNode) node; stack.add(store); outer = pushProjectionRecursive(ctx, optContext, store.getSubNode(), stack, necessary); store.setInSchema(outer.getOutSchema()); store.setOutSchema(outer.getOutSchema()); break; case PROJECTION: ProjectionNode projNode = (ProjectionNode) node; stack.add(projNode); outer = pushProjectionRecursive(ctx, optContext, projNode.getSubNode(), stack, necessary); stack.pop(); LogicalNode childNode = projNode.getSubNode(); if (optContext.getTargetListManager().isAllEvaluated() // if all exprs are evaluated && (childNode.getType() == ExprType.JOIN || childNode.getType() == ExprType.GROUP_BY || childNode.getType() == ExprType.SCAN)) { // if the child node is projectable projNode.getSubNode().setOutSchema(optContext.getTargetListManager().getUpdatedSchema()); LogicalNode parent = stack.peek(); ((UnaryNode) parent).setSubNode(projNode.getSubNode()); return projNode.getSubNode(); } else { // the output schema is not changed. projNode.setInSchema(outer.getOutSchema()); projNode.setTargetList(optContext.getTargetListManager().getUpdatedTarget()); } return projNode; case SELECTION: // It does not support the projection SelectionNode selNode = (SelectionNode) node; if (selNode.getQual() != null) { necessary.addAll(EvalTreeUtil.findDistinctRefColumns(selNode.getQual())); } stack.add(selNode); outer = pushProjectionRecursive(ctx, optContext, selNode.getSubNode(), stack, necessary); stack.pop(); selNode.setInSchema(outer.getOutSchema()); selNode.setOutSchema(outer.getOutSchema()); break; case GROUP_BY: { GroupbyNode groupByNode = (GroupbyNode) node; if (groupByNode.hasHavingCondition()) { necessary.addAll(EvalTreeUtil.findDistinctRefColumns(groupByNode.getHavingCondition())); } stack.add(groupByNode); outer = pushProjectionRecursive(ctx, optContext, groupByNode.getSubNode(), stack, necessary); stack.pop(); groupByNode.setInSchema(outer.getOutSchema()); // set all targets groupByNode.setTargetList(optContext.getTargetListManager().getUpdatedTarget()); TargetListManager targets = optContext.getTargetListManager(); List<Target> groupbyPushable = Lists.newArrayList(); List<Integer> groupbyPushableId = Lists.newArrayList(); EvalNode expr; for (int i = 0; i < targets.size(); i++) { expr = targets.getTarget(i).getEvalTree(); if (canBeEvaluated(expr, groupByNode) && EvalTreeUtil.findDistinctAggFunction(expr).size() > 0 && expr.getType() != EvalNode.Type.FIELD) { targets.setEvaluated(i); groupbyPushable.add((Target) targets.getTarget(i).clone()); groupbyPushableId.add(i); } } return groupByNode; } case SORT: // It does not support the projection SortNode sortNode = (SortNode) node; for (QueryBlock.SortSpec spec : sortNode.getSortKeys()) { necessary.add(spec.getSortKey()); } stack.add(sortNode); outer = pushProjectionRecursive(ctx, optContext, sortNode.getSubNode(), stack, necessary); stack.pop(); sortNode.setInSchema(outer.getOutSchema()); sortNode.setOutSchema(outer.getOutSchema()); break; case JOIN: { JoinNode joinNode = (JoinNode) node; Set<Column> parentNecessary = Sets.newHashSet(necessary); if (joinNode.hasJoinQual()) { necessary.addAll(EvalTreeUtil.findDistinctRefColumns(joinNode.getJoinQual())); } stack.add(joinNode); outer = pushProjectionRecursive(ctx, optContext, joinNode.getOuterNode(), stack, necessary); inner = pushProjectionRecursive(ctx, optContext, joinNode.getInnerNode(), stack, necessary); stack.pop(); Schema merged = SchemaUtil.merge(outer.getOutSchema(), inner.getOutSchema()); joinNode.setInSchema(merged); TargetListManager targets = optContext.getTargetListManager(); List<Target> joinPushable = Lists.newArrayList(); List<Integer> joinPushableId = Lists.newArrayList(); EvalNode expr; for (int i = 0; i < targets.size(); i++) { expr = targets.getTarget(i).getEvalTree(); if (canBeEvaluated(expr, joinNode) && EvalTreeUtil.findDistinctAggFunction(expr).size() == 0 && expr.getType() != EvalNode.Type.FIELD) { targets.setEvaluated(i); joinPushable.add(targets.getTarget(i)); joinPushableId.add(i); } } if (joinPushable.size() > 0) { joinNode.setTargetList(targets.targets); } Schema outSchema = shrinkOutSchema(joinNode.getInSchema(), targets.getUpdatedSchema().getColumns()); for (Integer t : joinPushableId) { outSchema.addColumn(targets.getEvaluatedColumn(t)); } outSchema = SchemaUtil.mergeAllWithNoDup(outSchema.getColumns(), SchemaUtil.getProjectedSchema(joinNode.getInSchema(), parentNecessary).getColumns()); joinNode.setOutSchema(outSchema); break; } case UNION: // It does not support the projection UnionNode unionNode = (UnionNode) node; stack.add(unionNode); ParseTree tree = ctx.getParseTree(); if (tree instanceof CreateTableStmt) { tree = ((CreateTableStmt) tree).getSelectStmt(); } QueryBlock block = (QueryBlock) tree; OptimizationContext outerCtx = new OptimizationContext(ctx, block.getTargetList()); OptimizationContext innerCtx = new OptimizationContext(ctx, block.getTargetList()); pushProjectionRecursive(ctx, outerCtx, unionNode.getOuterNode(), stack, necessary); pushProjectionRecursive(ctx, innerCtx, unionNode.getInnerNode(), stack, necessary); stack.pop(); // if this is the final union, we assume that all targets are evalauted // TODO - is it always correct? if (stack.peek().getType() != ExprType.UNION) { optContext.getTargetListManager().setEvaluatedAll(); } break; case SCAN: { ScanNode scanNode = (ScanNode) node; TargetListManager targets = optContext.getTargetListManager(); List<Integer> scanPushableId = Lists.newArrayList(); List<Target> scanPushable = Lists.newArrayList(); EvalNode expr; for (int i = 0; i < targets.size(); i++) { expr = targets.getTarget(i).getEvalTree(); if (!targets.isEvaluated(i) && canBeEvaluated(expr, scanNode)) { if (expr.getType() == EvalNode.Type.FIELD) { targets.setEvaluated(i); } else if (EvalTreeUtil.findDistinctAggFunction(expr).size() == 0) { targets.setEvaluated(i); scanPushable.add(targets.getTarget(i)); scanPushableId.add(i); } } } if (scanPushable.size() > 0) { scanNode.setTargets(scanPushable.toArray(new Target[scanPushable.size()])); } Schema outSchema = shrinkOutSchema(scanNode.getInSchema(), targets.getUpdatedSchema().getColumns()); for (Integer t : scanPushableId) { outSchema.addColumn(targets.getEvaluatedColumn(t)); } outSchema = SchemaUtil.mergeAllWithNoDup(outSchema.getColumns(), SchemaUtil.getProjectedSchema(scanNode.getInSchema(), necessary).getColumns()); scanNode.setOutSchema(outSchema); break; } default: } return node; }
From source file:com.udojava.evalex.Expression.java
/** * Check that the expression has enough numbers and variables to fit the * requirements of the operators and functions, also check * for only 1 result stored at the end of the evaluation. *//*from w ww. j a v a 2s. c o m*/ private void validate(List<String> rpn) { /*- * Thanks to Norman Ramsey: * http://http://stackoverflow.com/questions/789847/postfix-notation-validation */ // each push on to this stack is a new function scope, with the value of each // layer on the stack being the count of the number of parameters in that scope Stack<Integer> stack = new Stack<>(); // push the 'global' scope stack.push(0); for (final String token : rpn) { if (operators.containsKey(token)) { if (stack.peek() < 2) { throw new ExpressionException("Missing parameter(s) for operator " + token); } // pop the operator's 2 parameters and add the result stack.set(stack.size() - 1, stack.peek() - 2 + 1); } else if (mainVars.containsKey(token)) { stack.set(stack.size() - 1, stack.peek() + 1); } else if (functions.containsKey(token.toUpperCase(Locale.ROOT))) { LazyFunction f = functions.get(token.toUpperCase(Locale.ROOT)); int numParams = stack.pop(); if (!f.numParamsVaries() && numParams != f.getNumParams()) { throw new ExpressionException("Function " + token + " expected " + f.getNumParams() + " parameters, got " + numParams); } if (stack.size() <= 0) { throw new ExpressionException("Too many function calls, maximum scope exceeded"); } // push the result of the function stack.set(stack.size() - 1, stack.peek() + 1); } else if ("(".equals(token)) { stack.push(0); } else { stack.set(stack.size() - 1, stack.peek() + 1); } } if (stack.size() > 1) { throw new ExpressionException("Too many unhandled function parameter lists"); } else if (stack.peek() > 1) { throw new ExpressionException("Too many numbers or variables"); } else if (stack.peek() < 1) { throw new ExpressionException("Empty expression"); } }
From source file:org.springframework.statemachine.config.AbstractStateMachineFactory.java
/** * Main constructor that create a {@link StateMachine}. * * @param uuid for internal usage. Can be null, in that case a random one will be generated. * @param machineId represent a user Id, up to you to set what you want. * @return a {@link StateMachine}// w w w. j av a2 s .c om */ @SuppressWarnings("unchecked") public StateMachine<S, E> getStateMachine(UUID uuid, String machineId) { StateMachineModel<S, E> stateMachineModel = resolveStateMachineModel(machineId); if (stateMachineModel.getConfigurationData().isVerifierEnabled()) { StateMachineModelVerifier<S, E> verifier = stateMachineModel.getConfigurationData().getVerifier(); if (verifier == null) { verifier = new CompositeStateMachineModelVerifier<S, E>(); } verifier.verify(stateMachineModel); } // shared DefaultExtendedState defaultExtendedState = new DefaultExtendedState(); StateMachine<S, E> machine = null; // we store mappings from state id's to states which gets // created during the process. This is needed for transitions to // find a correct mappings because they use state id's, not actual // states. final Map<S, State<S, E>> stateMap = new HashMap<S, State<S, E>>(); Stack<MachineStackItem<S, E>> regionStack = new Stack<MachineStackItem<S, E>>(); Stack<StateData<S, E>> stateStack = new Stack<StateData<S, E>>(); Map<Object, StateMachine<S, E>> machineMap = new HashMap<Object, StateMachine<S, E>>(); Map<S, StateHolder<S, E>> holderMap = new HashMap<S, StateHolder<S, E>>(); Iterator<Node<StateData<S, E>>> iterator = buildStateDataIterator(stateMachineModel); while (iterator.hasNext()) { Node<StateData<S, E>> node = iterator.next(); StateData<S, E> stateData = node.getData(); StateData<S, E> peek = stateStack.isEmpty() ? null : stateStack.peek(); // simply push and continue if (stateStack.isEmpty()) { stateStack.push(stateData); continue; } boolean stackContainsSameParent = false; Iterator<StateData<S, E>> ii = stateStack.iterator(); while (ii.hasNext()) { StateData<S, E> sd = ii.next(); if (stateData != null && ObjectUtils.nullSafeEquals(stateData.getState(), sd.getParent())) { stackContainsSameParent = true; break; } } if (stateData != null && !stackContainsSameParent) { stateStack.push(stateData); continue; } Collection<StateData<S, E>> stateDatas = popSameParents(stateStack); int initialCount = getInitialCount(stateDatas); Collection<Collection<StateData<S, E>>> regionsStateDatas = splitIntoRegions(stateDatas); Collection<TransitionData<S, E>> transitionsData = getTransitionData(iterator.hasNext(), stateDatas, stateMachineModel); if (initialCount > 1) { for (Collection<StateData<S, E>> regionStateDatas : regionsStateDatas) { machine = buildMachine(machineMap, stateMap, holderMap, regionStateDatas, transitionsData, resolveBeanFactory(stateMachineModel), contextEvents, defaultExtendedState, stateMachineModel.getTransitionsData(), resolveTaskExecutor(stateMachineModel), resolveTaskScheduler(stateMachineModel), machineId, null, stateMachineModel); regionStack.push(new MachineStackItem<S, E>(machine)); } Collection<Region<S, E>> regions = new ArrayList<Region<S, E>>(); while (!regionStack.isEmpty()) { MachineStackItem<S, E> pop = regionStack.pop(); regions.add(pop.machine); } S parent = (S) peek.getParent(); RegionState<S, E> rstate = buildRegionStateInternal(parent, regions, null, stateData != null ? stateData.getEntryActions() : null, stateData != null ? stateData.getExitActions() : null, new DefaultPseudoState<S, E>(PseudoStateKind.INITIAL)); if (stateData != null) { stateMap.put(stateData.getState(), rstate); } else { // TODO: don't like that we create a last machine here Collection<State<S, E>> states = new ArrayList<State<S, E>>(); states.add(rstate); Transition<S, E> initialTransition = new InitialTransition<S, E>(rstate); StateMachine<S, E> m = buildStateMachineInternal(states, new ArrayList<Transition<S, E>>(), rstate, initialTransition, null, defaultExtendedState, null, contextEvents, resolveBeanFactory(stateMachineModel), resolveTaskExecutor(stateMachineModel), resolveTaskScheduler(stateMachineModel), beanName, machineId != null ? machineId : stateMachineModel.getConfigurationData().getMachineId(), uuid, stateMachineModel); machine = m; } } else { machine = buildMachine(machineMap, stateMap, holderMap, stateDatas, transitionsData, resolveBeanFactory(stateMachineModel), contextEvents, defaultExtendedState, stateMachineModel.getTransitionsData(), resolveTaskExecutor(stateMachineModel), resolveTaskScheduler(stateMachineModel), machineId, uuid, stateMachineModel); if (peek.isInitial() || (!peek.isInitial() && !machineMap.containsKey(peek.getParent()))) { machineMap.put(peek.getParent(), machine); } } stateStack.push(stateData); } // setup autostart for top-level machine if (machine instanceof LifecycleObjectSupport) { ((LifecycleObjectSupport) machine) .setAutoStartup(stateMachineModel.getConfigurationData().isAutoStart()); } // set top-level machine as relay final StateMachine<S, E> fmachine = machine; fmachine.getStateMachineAccessor().doWithAllRegions(new StateMachineFunction<StateMachineAccess<S, E>>() { @Override public void apply(StateMachineAccess<S, E> function) { function.setRelay(fmachine); } }); // add monitoring hooks final StateMachineMonitor<S, E> stateMachineMonitor = stateMachineModel.getConfigurationData() .getStateMachineMonitor(); if (stateMachineMonitor != null || defaultStateMachineMonitor != null) { fmachine.getStateMachineAccessor().doWithRegion(new StateMachineFunction<StateMachineAccess<S, E>>() { @Override public void apply(StateMachineAccess<S, E> function) { if (defaultStateMachineMonitor != null) { function.addStateMachineMonitor(defaultStateMachineMonitor); } if (stateMachineMonitor != null) { function.addStateMachineMonitor(stateMachineMonitor); } } }); } // TODO: should error out if sec is enabled but spring-security is not in cp if (stateMachineModel.getConfigurationData().isSecurityEnabled()) { final StateMachineSecurityInterceptor<S, E> securityInterceptor = new StateMachineSecurityInterceptor<S, E>( stateMachineModel.getConfigurationData().getTransitionSecurityAccessDecisionManager(), stateMachineModel.getConfigurationData().getEventSecurityAccessDecisionManager(), stateMachineModel.getConfigurationData().getEventSecurityRule()); log.info("Adding security interceptor " + securityInterceptor); fmachine.getStateMachineAccessor() .doWithAllRegions(new StateMachineFunction<StateMachineAccess<S, E>>() { @Override public void apply(StateMachineAccess<S, E> function) { function.addStateMachineInterceptor(securityInterceptor); } }); } // setup distributed state machine if needed. // we wrap previously build machine with a distributed // state machine and set it to use given ensemble. if (stateMachineModel.getConfigurationData().getStateMachineEnsemble() != null) { DistributedStateMachine<S, E> distributedStateMachine = new DistributedStateMachine<S, E>( stateMachineModel.getConfigurationData().getStateMachineEnsemble(), machine); distributedStateMachine.setAutoStartup(stateMachineModel.getConfigurationData().isAutoStart()); distributedStateMachine.afterPropertiesSet(); machine = distributedStateMachine; } for (StateMachineListener<S, E> listener : stateMachineModel.getConfigurationData() .getStateMachineListeners()) { machine.addStateListener(listener); } // go through holders and fix state references which // were not known at a time holder was created for (Entry<S, StateHolder<S, E>> holder : holderMap.entrySet()) { holder.getValue().setState(stateMap.get(holder.getKey())); } return delegateAutoStartup(machine); }
From source file:hydrograph.engine.core.xmlparser.parametersubstitution.ParameterSubstitutor.java
private void substituteMutable(StringBuilder mutable, Stack<String> unresolvedParameters) { int startIndex = mutable.indexOf(VARIABLE_PREFIX); int endIndex = mutable.indexOf(VARIABLE_SUFFIX, startIndex); // return if nothing to substitute if (startIndex == -1 || endIndex == -1) { return;// ww w. ja va2 s . c o m } // get parameter name String parameterName = mutable.substring(startIndex + VARIABLE_PREFIX.length(), endIndex); // raise exception if parameter name is blank if (parameterName == null || parameterName.trim().length() == 0) { throw new ParameterSubstitutorException("Parameter name can not be blank. Please correct."); } parameterName = parameterName.trim(); String parameterValue = null; if (resolvedParameterCache.containsKey(parameterName)) { // obtain value from cache if already present parameterValue = resolvedParameterCache.get(parameterName); LOG.info("cache used for " + parameterName); } else { // check if the parameter is already on the stack then raise // exception // that it is circular substitution if (unresolvedParameters.search(parameterName) != -1) { throw new ParameterSubstitutorException("Found a circular depencency between parameter " + parameterName + " and " + unresolvedParameters.peek() + ". Both are referencing each other and cannot be resolved. Please correct."); } // get parameter value parameterValue = parameterBank.getParameter(parameterName); // if value is null then raise exception if (parameterValue == null) { throw new ParameterSubstitutorException( "No value is found for the parameter " + parameterName + " to substitute"); } // if parameter key to be substituted is in quotes("") then escape // special characters from its value if (isParameterPresentInQuotes(mutable, startIndex, endIndex)) { parameterValue = StringEscapeUtils.escapeXml(parameterValue); } // add current parameter to stack to check for circular loop later unresolvedParameters.push(parameterName); // check of substitution if there is a parameter reference in // parameter // value(internal substitution) parameterValue = substitute(parameterValue, unresolvedParameters); // remove parameter from stack as soon as it is resolved unresolvedParameters.pop(); // add resolved value to cache resolvedParameterCache.put(parameterName, parameterValue); } // delete parameter syntax mutable.delete(startIndex, endIndex + VARIABLE_SUFFIX.length()); // insert parameter value mutable.insert(startIndex, parameterValue); // check for next substitution and do it if available substituteMutable(mutable, unresolvedParameters); }
From source file:com.unboundid.scim.sdk.FilterParser.java
/** * Read a filter expression./*from w w w .j a v a2 s . c o m*/ * * @return The SCIM filter. */ private SCIMFilter readFilter() { final Stack<Node> expressionStack = new Stack<Node>(); // Employ the shunting-yard algorithm to parse into reverse polish notation, // where the operands are filter components and the operators are the // logical AND and OR operators. This algorithm ensures that operator // precedence and parentheses are respected. final List<Node> reversePolish = new ArrayList<Node>(); for (String word = readWord(); word != null; word = readWord()) { if (word.equalsIgnoreCase("and") || word.equalsIgnoreCase("or")) { final OperatorNode currentOperator; if (word.equalsIgnoreCase("and")) { currentOperator = new OperatorNode(SCIMFilterType.AND, markPos); } else { currentOperator = new OperatorNode(SCIMFilterType.OR, markPos); } while (!expressionStack.empty() && (expressionStack.peek() instanceof OperatorNode)) { final OperatorNode previousOperator = (OperatorNode) expressionStack.peek(); if (previousOperator.getPrecedence() < currentOperator.getPrecedence()) { break; } reversePolish.add(expressionStack.pop()); } expressionStack.push(currentOperator); } else if (word.equals("(")) { expressionStack.push(new LeftParenthesisNode(markPos)); } else if (word.equals(")")) { while (!expressionStack.empty() && !(expressionStack.peek() instanceof LeftParenthesisNode)) { reversePolish.add(expressionStack.pop()); } if (expressionStack.empty()) { final String msg = String.format( "No opening parenthesis matching closing " + "parenthesis at position %d", markPos); throw new IllegalArgumentException(msg); } expressionStack.pop(); } else { rewind(); final int pos = currentPos; final SCIMFilter filterComponent = readFilterComponent(); reversePolish.add(new FilterNode(filterComponent, pos)); } } while (!expressionStack.empty()) { final Node node = expressionStack.pop(); if (node instanceof LeftParenthesisNode) { final String msg = String.format( "No closing parenthesis matching opening " + "parenthesis at position %d", node.getPos()); throw new IllegalArgumentException(msg); } reversePolish.add(node); } // Evaluate the reverse polish notation to create a single complex filter. final Stack<FilterNode> filterStack = new Stack<FilterNode>(); for (final Node node : reversePolish) { if (node instanceof OperatorNode) { final FilterNode rightOperand = filterStack.pop(); final FilterNode leftOperand = filterStack.pop(); final OperatorNode operatorNode = (OperatorNode) node; if (operatorNode.getFilterType().equals(SCIMFilterType.AND)) { final SCIMFilter filter = SCIMFilter.createAndFilter( Arrays.asList(leftOperand.getFilterComponent(), rightOperand.getFilterComponent())); filterStack.push(new FilterNode(filter, leftOperand.getPos())); } else { final SCIMFilter filter = SCIMFilter.createOrFilter( Arrays.asList(leftOperand.getFilterComponent(), rightOperand.getFilterComponent())); filterStack.push(new FilterNode(filter, leftOperand.getPos())); } } else { filterStack.push((FilterNode) node); } } if (filterStack.size() == 0) { final String msg = String.format("Empty filter expression"); throw new IllegalArgumentException(msg); } else if (filterStack.size() > 1) { final String msg = String.format("Unexpected characters at position %d", expressionStack.get(1).pos); throw new IllegalArgumentException(msg); } return filterStack.get(0).filterComponent; }
From source file:org.xlrnet.tibaija.processor.FullTIBasicVisitor.java
private int internalHandleControlFlowLogic(int commandIndex, List<TIBasicParser.CommandContext> commandList, Stack<ControlFlowElement> flowElementStack, Stack<ControlFlowElement.ControlFlowToken> skipCommandsStack, TIBasicParser.CommandContext nextCommand) { int commandListSize = commandList.size(); ControlFlowElement currentFlowElement = (ControlFlowElement) nextCommand.accept(this); ControlFlowElement topFlowElement;//from w w w. ja v a2 s . co m if (!flowElementStack.empty()) { topFlowElement = flowElementStack.peek(); } else { topFlowElement = null; } // Check if current token depends on a certain pre-token final int line = currentFlowElement.getLine(); final int charIndex = currentFlowElement.getCharIndex(); switch (currentFlowElement.getToken()) { case INCREMENT_SKIP_GREATER: case DECREMENT_SKIP_LESS: if (commandIndex + 1 >= commandList.size()) { throw new IllegalControlFlowException(line, charIndex, "Missing next command"); } if (!currentFlowElement.getLastEvaluation()) { LOGGER.debug("Skipping next command..."); commandIndex++; } break; case GOTO: JumpingControlFlowElement jumpElement = (JumpingControlFlowElement) currentFlowElement; String targetLabel = jumpElement.getTargetLabel(); commandIndex = environment.getProgramStack().peek().getLabelJumpTarget(jumpElement.getTargetLabel()); LOGGER.debug("Jumping to label {} at command {}", targetLabel, commandIndex); break; case LABEL: break; // Do nothing when encountering Label case FOR: boolean isFirstIteration = false; if ((topFlowElement == null || topFlowElement.getCommandIndex() != commandIndex)) { // Set start value (should be executed ALWAYS when this block is executed the *first* time from top-down TIBasicParser.ForStatementContext forStatementContext = commandList.get(commandIndex) .controlFlowStatement().forStatement(); String variableName = forStatementContext.numericalVariable().getText(); Value value = (Value) forStatementContext.expression(0).accept(this); Variables.NumberVariable targetVariable = Variables.resolveNumberVariable(variableName); environment.getWritableMemory().setNumberVariableValue(targetVariable, value); isFirstIteration = true; } if (currentFlowElement.isRepeatable() && (currentFlowElement.getLastEvaluation() || isFirstIteration)) { if (isFirstIteration) { currentFlowElement.setLastEvaluation(true); // Hack for making sure, that the first increment is ALWAYS done at the end LOGGER.debug("Entering FOR loop at command {}", commandIndex); } else { LOGGER.debug("Continuing FOR loop at command {}", commandIndex); flowElementStack.pop(); } currentFlowElement.setCommandIndex(commandIndex); flowElementStack.push(currentFlowElement); } else { if (topFlowElement != null && topFlowElement.getCommandIndex() == commandIndex) { flowElementStack.pop(); } LOGGER.debug("Skipping commands until next END from FOR command {}", commandIndex); skipCommandsStack.push(ControlFlowElement.ControlFlowToken.FOR); } break; case REPEAT: currentFlowElement.setCommandIndex(commandIndex); LOGGER.debug("Entering repeat loop at command {}", commandIndex); flowElementStack.push(currentFlowElement); break; case WHILE: if (!currentFlowElement.getLastEvaluation()) { LOGGER.debug("Skipping commands until next END from WHILE command {}", commandIndex); skipCommandsStack.push(ControlFlowElement.ControlFlowToken.WHILE); } else { currentFlowElement.setCommandIndex(commandIndex); flowElementStack.push(currentFlowElement); } break; case THEN: if (topFlowElement == null) { throw new IllegalControlFlowException(line, charIndex, "Illegal 'Then' Statement"); } if (topFlowElement.getToken() != ControlFlowElement.ControlFlowToken.IF) { throw new IllegalControlFlowException(line, charIndex, "Illegal 'Then' Statement without preceding 'If'"); } if (topFlowElement.getLastEvaluation()) { currentFlowElement.setLastEvaluation(true); } else { currentFlowElement.setLastEvaluation(false); skipCommandsStack.push(ControlFlowElement.ControlFlowToken.ELSE); LOGGER.debug("Skipping commands until next ELSE from THEN command {}", commandIndex); } flowElementStack.push(currentFlowElement); break; case ELSE: if (topFlowElement == null) { throw new IllegalControlFlowException(line, charIndex, "Illegal 'Else' Statement"); } if (topFlowElement.getToken() != ControlFlowElement.ControlFlowToken.THEN) { throw new IllegalControlFlowException(line, charIndex, "Illegal 'Else' Statement without preceding 'Then'"); } if (topFlowElement.getLastEvaluation()) { // Skip until next "END" if previous if was true skipCommandsStack.push(ControlFlowElement.ControlFlowToken.END); LOGGER.debug("Skipping commands until next END from ELSE command {}", commandIndex); } break; case END: if (topFlowElement == null) { throw new IllegalControlFlowException(line, charIndex, "Illegal 'End' Statement without preceding endable element"); } if (topFlowElement.getToken() == ControlFlowElement.ControlFlowToken.REPEAT) { // Repeat will only be check at the END command! final TIBasicParser.CommandContext commandContext = commandList .get(topFlowElement.getCommandIndex()); Value v = (Value) commandContext.controlFlowStatement().repeatStatement().expression().accept(this); if (v.bool()) { topFlowElement.setRepeatable(false); } else { topFlowElement.setRepeatable(true); } } else if (topFlowElement.getToken() == ControlFlowElement.ControlFlowToken.FOR) { if (topFlowElement.getLastEvaluation()) { topFlowElement.setRepeatable(true); TIBasicParser.ForStatementContext forStatementContext = commandList .get(topFlowElement.getCommandIndex()).controlFlowStatement().forStatement(); String variableName = forStatementContext.numericalVariable().getText(); Value increment; if (forStatementContext.expression().size() == 3) increment = (Value) forStatementContext.expression(2).accept(this); else increment = Value.of(1); Variables.NumberVariable targetVariable = Variables.resolveNumberVariable(variableName); Value value = environment .runRegisteredExpressionFunction("+", environment.getMemory().getNumberVariableValue(targetVariable), increment) .get(); environment.getWritableMemory().setNumberVariableValue(targetVariable, value); flowElementStack.push(topFlowElement); // Push the flow element again -> workaround } else { topFlowElement.setRepeatable(false); } } if (topFlowElement.isRepeatable()) { commandIndex = topFlowElement.getCommandIndex() - 1; // Move counter backwards LOGGER.debug("Moving command counter to index {}", commandIndex); } flowElementStack.pop(); break; case IF: // Look ahead if the next command might be a "Then" i.e. if it is a controlflow statement if (commandListSize <= commandIndex + 1) { throw new IllegalControlFlowException(line, charIndex, "Illegal 'If' at the end of the program"); } else if (commandList.get(commandIndex + 1).isControlFlowStatement) { flowElementStack.push(currentFlowElement); LOGGER.debug("Predicted multiline IF at command {}", commandIndex); } else if (!currentFlowElement.getLastEvaluation()) { // If the next command is not a flow statement and the If evaluated to false, skip the next command (i.e. no else allowed!) commandIndex++; LOGGER.debug("Skipped IF statement without ELSE clause at command {}", commandIndex); } break; default: throw new NotImplementedException("Flow not implemented"); } return commandIndex; }
From source file:ro.uaic.info.nlptools.ggs.engine.core.StateMachine.java
private List<State> findInfiniteLoop(State currentState, List<State> currentPath, Stack<GraphNode> callStack, Stack<Integer> pathJumpsBeginIndexes, Map<State, State> jumpProxies) {//functie recursiva pentru gasit bucle infinite if (currentState.index == terminalStateIndex) return null; if (verifiedStates.contains(currentState)) { //this state has been passed before successfully return null; }//from www. j a va2 s. c o m List<State> newPath = new ArrayList<State>(currentPath); State currentProxy = null; //handle correct jump transitions if (currentState.isGraphNodeEntry) { callStack.push(currentState.parentGraphNode); if (currentState.parentGraphNode == currentState.parentGraphNode.getParentGraph().getStartNode()) pathJumpsBeginIndexes.push(newPath.size()); } else if (currentState.isGraphNodeExit) { if (currentState.parentGraphNode != callStack.peek()) { return null; // this is not a valit transition according to jumps stack } callStack.pop(); if (currentState.parentGraphNode == currentState.parentGraphNode.getParentGraph().getEndNode()) {//if exit from a jump, the nodes inside the jump must be treated as one empty or non empty node, to avoid false detection when recursivity is used int pathJumpStart = pathJumpsBeginIndexes.pop(); boolean consumed = false; for (int i = pathJumpStart; i < currentPath.size(); i++) { if (!newPath.get(newPath.size() - 1).condition.isEmpty) consumed = true; newPath.remove(newPath.size() - 1); } if (consumed) { currentProxy = jumpProxies.get(newPath.get(newPath.size() - 1)); if (currentProxy == null) { GraphNode gn = new GraphNode(grammar); // this is a proxy node for the entire sub network - since we know there is no loop inside it, we can treat it as a normal node for the search if (!currentPath.isEmpty()) gn.setTokenMatchingCode( "jump to " + currentPath.get(currentPath.size() - 1).parentGraphNode .getParentGraph().getId()); currentProxy = new State(this, gn); currentProxy.condition.isEmpty = false; jumpProxies.put(newPath.get(newPath.size() - 1), currentProxy); } newPath.add(currentProxy); } } } //avoid exploring non empty loops - such loops are ok if ((currentProxy == null || !currentPath.contains(currentProxy)) && (currentState.condition.isEmpty || !currentPath.contains(currentState))) { if (currentState.parentGraphNode != currentState.parentGraphNode.getParentGraph().getEndNode()) //if exited from a jump do not retain this node in the loop, to avoid false detection when recursivity is used newPath.add(currentState); if (currentState.condition.isEmpty) {// search for this empty state in the tail of the current traveled path from root boolean found = false; for (int i = currentPath.size() - 1; i >= 0; i--) { if (!currentPath.get(i).condition.isEmpty) { break; } if (currentPath.get(i) == currentState) { found = true; break; } } if (found) { return newPath; } } for (int childStateIndex : currentState.childStatesIndexes) { List<State> foundPath = findInfiniteLoop(states.get(childStateIndex), newPath, callStack, pathJumpsBeginIndexes, jumpProxies); if (foundPath != null) return foundPath; } //this node doesn't lead to an infinite loop if (currentState.isGraphNodeEntry) { verifiedStates.add(currentState); } } if (currentState.isGraphNodeEntry && currentState.parentGraphNode == currentState.parentGraphNode.getParentGraph().getStartNode()) pathJumpsBeginIndexes.pop(); else if (currentState.isGraphNodeExit && currentState.parentGraphNode == currentState.parentGraphNode.getParentGraph().getEndNode()) //if exited from a jump, the nodes inside the jump must be ignored, to avoit false detection when recursivity is used pathJumpsBeginIndexes.push(currentPath .lastIndexOf(states.get(compNodes.get(currentPath.get(currentPath.size() - 1).parentGraphNode .getParentGraph().getStartNode()).startStateIndex))); return null; }