List of usage examples for org.apache.commons.scxml Context set
void set(String name, Object value);
From source file:com.korwe.thecore.scxml.ScxmlMessageProcessor.java
@Override public void initialize(String sessionId) { super.initialize(sessionId); try {/*from www . j a v a 2s . c o m*/ String scxmlPath = CoreConfig.getInstance().getProperty("scxml_path"); if (LOG.isDebugEnabled()) { LOG.debug("SCXML path = " + scxmlPath); } File scfile = new File(scxmlPath); if (LOG.isDebugEnabled()) { LOG.debug("Absolute path: [" + scfile.getAbsolutePath() + "]"); } InputSource source = new InputSource(new BufferedReader(new FileReader(scxmlPath))); scxml = SCXMLParser.parse(source, new SimpleErrorHandler()); exec = new SCXMLExecutor(new JexlEvaluator(), new SimpleDispatcher(), new SimpleErrorReporter()); exec.setStateMachine(scxml); exec.addListener(scxml, new SimpleSCXMLListener()); exec.registerInvokerClass("x-coremessage", SendCoreMessageInvoker.class); Context context = new JexlContext(); context.set("sessionId", sessionId); context.set("lastMsg", null); exec.setRootContext(context); exec.go(); } catch (Exception e) { LOG.error("Failed to parse SCXML", e); } }
From source file:de.dfki.iui.mmds.dialogue.SiamEvaluator.java
@Override public void onTransition(TransitionTarget from, TransitionTarget to, Transition transition) { // save variables of firing transition to context that were filled // during transition pattern matching process Context currentContext = siamStateMachine.getCurrentContext(); Log log = (Log) transition.getActions().get(0); String transitionId = log.getLabel(); if (variableCache.containsKey(transitionId)) { Map<String, Object> variables = variableCache.get(transitionId); // set context variables for (String key : variables.keySet()) { Variable variable = (Variable) currentContext.get("_variable$" + key); if (variable == null) { Logger.getLogger(this.getClass()) .warn(String.format( "In transition \'%s': Variable \"%s\" is not defined for scope of state \"%s\"", transitionId, key, currentContext.get("stateID"))); } else { try { currentContext.set(key, variables.get(key)); } catch (IllegalArgumentException ex) { Logger.getLogger(getClass()).warn( String.format("In transition \'%s': %s", transitionId, ex.getLocalizedMessage())); }//w w w. jav a 2s . c om } } } variableCache.remove(transitionId); }
From source file:de.dfki.iui.mmds.scxml.engine.impl.SCXMLEngineImpl.java
/** * Instantiate and initialize the underlying executor instance. * //www . j a v a 2 s . c om * @param stateMachine * The state machine * @param topicInfix * @param rootCtx * The root context * @param evaluator * The expression evaluator * @param dispatcher */ private void initialize(final SCXML stateMachine, String idSuffix, final Context rootCtx, final Evaluator evaluator, EventDispatcher dispatcher, final ErrorReporter errorReporter) { engine = new SCXMLExecutor(evaluator, dispatcher, new SimpleErrorReporter()); engine.setStateMachine(stateMachine); engine.setSuperStep(true); engine.setRootContext(rootCtx); engine.addListener(stateMachine, new EntryListener()); engine.registerInvokerClass("scxml", SimpleSCXMLInvoker.class); // engine.registerInvokerClass("grounding", GroundingInvoker.class); // setId(stateMachine.getId()); String topicId = stateMachine.getId() + idSuffix; setId(topicId); EventHandler handler = new EventHandler() { @Override public void handleEvent(Event event) { if (event instanceof SCXMLEventFiredEvent) { // logInfo( "Scxml event 'SCXMLEventFiredEvent' received!" // ); fireEvent(((SCXMLEventFiredEvent) event).getEvent(), null); } } }; serviceRegs.add(SCXMLEngineActivator.registerEventHandler(handler, SCXMLEventFiredEvent.getTopic(topicId))); handlers.add(handler); // One event handler to listen for macro/micro step instructions handler = new EventHandler() { @Override public void handleEvent(Event event) { // logInfo( "Scxml event 'SCXMLMacroMicroStepEvent' received!" // ); engine.setSuperStep(SCXMLMacroMicroStepEvent.isMacroStepEvent(event)); String ev = ((SCXMLMacroMicroStepEvent) event).getEvent(); if (ev == null) { resume(); } else { fireEvent(ev, null); } } }; serviceRegs.add(SCXMLEngineActivator.registerEventHandler(handler, SCXMLMacroMicroStepEvent.getTopic(topicId, SCXMLMacroMicroStepEvent.TOPIC_SUFFIX_MACRO))); serviceRegs.add(SCXMLEngineActivator.registerEventHandler(handler, SCXMLMacroMicroStepEvent.getTopic(topicId, SCXMLMacroMicroStepEvent.TOPIC_SUFFIX_MICRO))); handlers.add(handler); // a handler for the transition cond evaluation/change events handler = new EventHandler() { public Transition findTransition(SCXMLTransitionEvent ev) { String stateId = ev.getStateId(); for (TransitionTarget tt : engine.getCurrentStatus().getAllStates()) { if (tt.getId().equals(stateId)) { try { // the state is found, now take a look at the // transitions return tt.getTransitionsList().get(ev.getTransPos()); } catch (IndexOutOfBoundsException e) { logError(e); } } } return null; } @Override public void handleEvent(Event event) { if (SCXMLTransitionEvent.isEvalTransitionCondEvent(event)) { // logInfo( "Scxml event 'SCXMLTransitionEvent' received!" // ); SCXMLTransitionEvent ev = (SCXMLTransitionEvent) event; Transition t = findTransition(ev); if (t != null) { try { String cond = t.getCond(); boolean evalResult = engine.getEvaluator() .evalCond(engine.getSCInstance().getContext(t.getParent()), cond); // now send the complete current state Map<String, Map<String, List<Object[]>>> currentState = getAvailableEventsStates(); for (Map<String, List<Object[]>> evVal : currentState.values()) { for (List<Object[]> stateVal : evVal.values()) { for (Object[] values : stateVal) { if (values[0] instanceof Integer && values[1].equals(cond)) { // set the evaluation result values[2] = evalResult ? 1 : 0; } } } } // logInfo( "Send 'Active states'" ); SCXMLEngineActivator.sendActiveStates(id, getActiveStates(), getAllActiveStates()); // logInfo( "Send 'Scxml state'" ); SCXMLEngineActivator.sendScxmlState(id, State.IDLE, currentState); } catch (SCXMLExpressionException e) { logError(e); } } } else if (SCXMLChangeTransitionCondEvent.isChangeTransitionCondEvent(event)) { // logInfo( // "Scxml event 'SCXMLChangeTransitionCondEvent' received!" // ); SCXMLChangeTransitionCondEvent ev = (SCXMLChangeTransitionCondEvent) event; Transition t = findTransition(ev); if (t != null) { t.setCond(ev.getNewCond()); } } } }; serviceRegs.add(SCXMLEngineActivator.registerEventHandler(handler, SCXMLTransitionEvent.getTopic(topicId, SCXMLTransitionEvent.Sort.COND))); handlers.add(handler); // a handler for the change of data values handler = new EventHandler() { @Override public void handleEvent(Event event) { if (event instanceof SCXMLChangeDataValueEvent) { // logInfo( // "Scxml event 'SCXMLChangeDataValueEvent' received!" ); SCXMLChangeDataValueEvent ev = (SCXMLChangeDataValueEvent) event; String stateId = ev.getStateId(); for (TransitionTarget tt : engine.getCurrentStatus().getAllStates()) { if (tt.getId().equals(stateId)) { try { // here comes a 'silent' change of the content, // i.e. there is no event 'dataId.change' sent Context ctxt = engine.getSCInstance().getContext(tt); Object result = engine.getEvaluator().eval(ctxt, ev.getValueScript()); String dataId = ev.getDataId(); ctxt.set(dataId, result); // now send the complete current state Map<String, Map<String, List<Object[]>>> currentState = getAvailableEventsStates(); for (Map<String, List<Object[]>> val : currentState.values()) { for (List<Object[]> state : val.values()) { for (Object[] values : state) { if (values[0].equals(dataId)) { // indicate that the value // changed values[2] = true; } } } } // logInfo( "Send 'Active states'" ); SCXMLEngineActivator.sendActiveStates(id, getActiveStates(), getAllActiveStates()); // logInfo( "Send 'Scxml state'" ); SCXMLEngineActivator.sendScxmlState(id, State.IDLE, currentState); return; } catch (SCXMLExpressionException e) { e.printStackTrace(); } } } } } }; serviceRegs.add( SCXMLEngineActivator.registerEventHandler(handler, SCXMLChangeDataValueEvent.getTopic(topicId))); handlers.add(handler); }
From source file:de.dfki.iui.mmds.dialogue.DialogueComponent.java
@Override public void resetCurrentScxmlContext() { Context currentContext = stateMachine.getCurrentContext(); List<String> activeStates = stateMachine.getAllActiveStates(); for (String stateId : activeStates) { AbstractState node = idToDialogueNode.get(stateId); for (Variable variable : node.getVariables()) { Object defaultValue = null; if (variable.getDefault() != null && !variable.getDefault().isEmpty()) { if (variable.getEmfType() != null && variable.getEmfType() instanceof EDataType) { defaultValue = variable.getEmfType().getEPackage().getEFactoryInstance() .createFromString((EDataType) variable.getEmfType(), variable.getDefault()); } else if (variable.getType() != null && !variable.getType().isEmpty()) { try { defaultValue = stateMachine.siamEvaluator.eval(currentContext, variable.getDefault()); } catch (IllegalArgumentException | SecurityException | SCXMLExpressionException e) { final Writer result = new StringWriter(); final PrintWriter printWriter = new PrintWriter(result); e.printStackTrace(printWriter); Logger.getLogger(this.getClass()).warn(String.format( "Cannot create default variable value \"%s\" for variable \"%s\" of type %s!\n%s", variable.getDefault(), variable.getName(), variable.getType(), result.toString())); }/*from w ww .j a v a2 s .co m*/ if (defaultValue == null) { Logger.getLogger(this.getClass()).warn(String.format( "Cannot create default variable value \"%s\" for variable \"%s\" of type %s!", variable.getDefault(), variable.getName(), variable.getType())); } } else { Logger.getLogger(this.getClass()).warn(String.format( "Cannot create default value for variable \"%s\". The type %s is not serializable.", variable.getName(), variable.getEmfType())); } } // currentContext.set(name, value); currentContext.set(variable.getName(), defaultValue); } } }
From source file:org.finra.datagenerator.engine.negscxml.NegSCXMLCommons.java
/** * Checks if a variable assignment satisfies a condition for a transition * Conditions involving the negative variables are auto satisfied/ignored * * @param variables the assignments * @param condition the condition * @param negativeVariables the negative variables * @return Boolean true if condition passes, false otherwise *//* w ww. j a va2 s .com*/ public Boolean checkTransition(Map<String, String> variables, String condition, Set<String> negativeVariables) { Boolean pass; //condition must exist if (condition == null) { pass = true; } else { //condition must not concern one of the negative variables for (String negativeVariable : negativeVariables) { if (condition.contains(negativeVariable)) { pass = true; return pass; } } //scrub the context clean so we may use it to evaluate transition conditional Context context = this.getRootContext(); context.reset(); //set up new context for (Map.Entry<String, String> e : variables.entrySet()) { context.set(e.getKey(), e.getValue()); } //evaluate condition try { pass = (Boolean) this.getEvaluator().eval(context, condition); } catch (SCXMLExpressionException ex) { pass = false; } } return pass; }
From source file:org.finra.datagenerator.engine.scxml.SCXMLEngine.java
/** * Performs a partial BFS on model until the search frontier reaches the desired bootstrap size * * @param min the desired bootstrap size * @return a list of found PossibleState * @throws ModelException if the desired bootstrap can not be reached *//*from w w w.j a v a 2s . c o m*/ public List<PossibleState> bfs(int min) throws ModelException { List<PossibleState> bootStrap = new LinkedList<>(); TransitionTarget initial = model.getInitialTarget(); PossibleState initialState = new PossibleState(initial, fillInitialVariables()); bootStrap.add(initialState); while (bootStrap.size() < min) { PossibleState state = bootStrap.remove(0); TransitionTarget nextState = state.nextState; if (nextState.getId().equalsIgnoreCase("end")) { throw new ModelException("Could not achieve required bootstrap without reaching end state"); } //run every action in series List<Map<String, String>> product = new LinkedList<>(); product.add(new HashMap<>(state.variables)); OnEntry entry = nextState.getOnEntry(); List<Action> actions = entry.getActions(); for (Action action : actions) { for (CustomTagExtension tagExtension : tagExtensionList) { if (tagExtension.getTagActionClass().isInstance(action)) { product = tagExtension.pipelinePossibleStates(action, product); } } } //go through every transition and see which of the products are valid, adding them to the list List<Transition> transitions = nextState.getTransitionsList(); for (Transition transition : transitions) { String condition = transition.getCond(); TransitionTarget target = ((List<TransitionTarget>) transition.getTargets()).get(0); for (Map<String, String> p : product) { Boolean pass; if (condition == null) { pass = true; } else { //scrub the context clean so we may use it to evaluate transition conditional Context context = this.getRootContext(); context.reset(); //set up new context for (Map.Entry<String, String> e : p.entrySet()) { context.set(e.getKey(), e.getValue()); } //evaluate condition try { pass = (Boolean) this.getEvaluator().eval(context, condition); } catch (SCXMLExpressionException ex) { pass = false; } } //transition condition satisfied, add to bootstrap list if (pass) { PossibleState result = new PossibleState(target, p); bootStrap.add(result); } } } } return bootStrap; }
From source file:org.finra.datagenerator.engine.scxml.SCXMLFrontier.java
private void dfs(ProcessingStrategy processingStrategy, AtomicBoolean flag, PossibleState state) { if (flag.get()) { return;/*from w ww . j a v a 2 s. c om*/ } TransitionTarget nextState = state.nextState; //reached end of chart, valid assignment found if (nextState.getId().equalsIgnoreCase("end")) { processingStrategy.processOutput(state.variables); return; } //run every action in series List<Map<String, String>> product = new LinkedList<>(); product.add(new HashMap<>(state.variables)); OnEntry entry = nextState.getOnEntry(); List<Action> actions = entry.getActions(); for (Action action : actions) { for (CustomTagExtension tagExtension : tagExtensionList) { if (tagExtension.getTagActionClass().isInstance(action)) { product = tagExtension.pipelinePossibleStates(action, product); } } } //go through every transition and see which of the products are valid, recursive searching on them List<Transition> transitions = nextState.getTransitionsList(); for (Transition transition : transitions) { String condition = transition.getCond(); TransitionTarget target = ((List<TransitionTarget>) transition.getTargets()).get(0); for (Map<String, String> p : product) { Boolean pass; if (condition == null) { pass = true; } else { //scrub the context clean so we may use it to evaluate transition conditional Context context = this.getRootContext(); context.reset(); //set up new context for (Map.Entry<String, String> e : p.entrySet()) { context.set(e.getKey(), e.getValue()); } //evaluate condition try { pass = (Boolean) this.getEvaluator().eval(context, condition); } catch (SCXMLExpressionException ex) { pass = false; } } //transition condition satisfied, continue search recursively if (pass) { PossibleState result = new PossibleState(target, p); dfs(processingStrategy, flag, result); } } } }