Example usage for org.apache.commons.scxml.model TransitionTarget getTransitionsList

List of usage examples for org.apache.commons.scxml.model TransitionTarget getTransitionsList

Introduction

In this page you can find the example usage for org.apache.commons.scxml.model TransitionTarget getTransitionsList.

Prototype

public final List<Transition> getTransitionsList() 

Source Link

Document

Get the outgoing transitions for this state as a java.util.List.

Usage

From source file:alma.acs.nc.sm.generic.AcsScxmlEngine.java

/**
 * Gets the signals that would trigger transitions for the current state.
 * <p>/*w ww.jav  a2 s . co m*/
 * When actually sending such signals later on, the SM may have moved to a different state.
 * To prevent this, you can synchronize on this AcsScxmlEngine, which will block concurrent calls to {@link #fireSignal(Enum)}.
 * <p>
 * This method can be useful for displaying applicable signals in a GUI,
 * or to reject signals (with exception etc) that do not "fit" the current state
 * (while normally such signals would be silently ignored). 
 * The latter gets used in {@link #fireSignalWithErrorFeedback(Enum)}.
 * 
 * @see org.apache.commons.scxml.semantics.SCXMLSemanticsImpl#enumerateReachableTransitions(SCXML, Step, ErrorReporter)
 */
public synchronized Set<S> getApplicableSignals() {
    Set<String> events = new HashSet<String>();

    @SuppressWarnings("unchecked")
    Set<TransitionTarget> stateSet = new HashSet<TransitionTarget>(exec.getCurrentStatus().getStates());
    LinkedList<TransitionTarget> todoList = new LinkedList<TransitionTarget>(stateSet);

    while (!todoList.isEmpty()) {
        TransitionTarget tt = todoList.removeFirst();
        @SuppressWarnings("unchecked")
        List<Transition> transitions = tt.getTransitionsList();
        for (Transition t : transitions) {
            String event = t.getEvent();
            events.add(event);
        }
        TransitionTarget parentTT = tt.getParent();
        if (parentTT != null && !stateSet.contains(parentTT)) {
            stateSet.add(parentTT);
            todoList.addLast(parentTT);
        }
    }

    // convert signal names to enum constants
    Set<S> ret = new HashSet<S>();
    for (String signalName : events) {
        S signal = Enum.valueOf(signalType, signalName);
        ret.add(signal);
    }
    return ret;
}

From source file:de.dfki.iui.mmds.scxml.engine.impl.SCXMLEngineImpl.java

@Override
public List<String> getAvailableEvents() {

    Set<TransitionTarget> states = engine.getCurrentStatus().getAllStates();
    // logInfo("found states: " + states.size());
    Set<Transition> transitions = new HashSet<Transition>();

    for (TransitionTarget state : states) {
        // logInfo("found state: " + state.getId());
        transitions.addAll(state.getTransitionsList());
    }/*from   w w w .j  a v a 2  s  . c o m*/

    List<String> events = new LinkedList<String>();
    for (Transition t : transitions) {
        // System.out.println("Available event: " + t.getEvent());
        if (t.getEvent() != null) {
            events.add(t.getEvent());
        }
    }

    return events;
}

From source file:de.dfki.iui.mmds.scxml.engine.impl.SCXMLEngineImpl.java

@Override
public Map<String, Map<String, List<Object[]>>> getAvailableEventsStates() {
    Map<String, Map<String, List<Object[]>>> eventsStates = new HashMap<String, Map<String, List<Object[]>>>();
    if (engine.getCurrentStatus().isFinal())
        // stop the interpretation by sending an empty config/available
        // event states
        return eventsStates;

    String event, id;//from  w  w  w  . j  av  a  2s .  c  o  m
    Map<String, List<Object[]>> states;
    Map<String, Object> vars, rootVars;
    List<Object[]> state;
    int pos;
    SCInstance sci = engine.getSCInstance();
    Set<String> datas;

    for (TransitionTarget tt : engine.getCurrentStatus().getAllStates()) {
        id = tt.getId();
        pos = 0;
        for (Transition t : tt.getTransitionsList()) {
            event = t.getEvent();
            event = (event != null || engine.isSuperStep()) ? event : TriggerEvent.EMPTY_EVENT;
            if (event != null) {
                // 1. add all events to the configuration
                if (!eventsStates.containsKey(event)) {
                    eventsStates.put(event, new HashMap<String, List<Object[]>>());
                }

                // 2. add all active source states to the config
                states = eventsStates.get(event);
                if (!states.containsKey(id)) {
                    states.put(id, new LinkedList<Object[]>());
                }

                // 3. add the transition condition to the config
                state = states.get(id);

                /*
                 * the following 4 values in the Object array indicate: i)
                 * the position of the transition ii) the condition of the
                 * transition iii) that the evaluation of the transition's
                 * condition is not performed in the last step, i.e. it is
                 * 'UNKNOWN' // * iii) that the transition condition was not
                 * changed in the last step, i.e. no dynamical change and
                 * this is not a 'refresh' event
                 */
                state.add(new Object[] { pos, t.getCond() == null ? "" : t.getCond(), -1 });

                // 4. add all contexts to the config
                vars = new HashMap<String, Object>();
                while (tt != null) {
                    vars.putAll(sci.getContext(tt).getVars());
                    tt = tt.getParent();
                }
                rootVars = sci.getRootContext().getVars();
                if (rootVars != null) {
                    vars.putAll(rootVars);
                }

                // to skip double entries the names of all datas in the
                // state config are needed
                // the following set/for-loop could be removed if the used
                // list would check double occurrences itself -> exchange
                // LinkedList by something else
                datas = new HashSet<String>();
                for (Object[] data : state) {
                    if (data[0] instanceof String) {
                        datas.add((String) data[0]);
                    }
                }
                for (Entry<String, Object> e : vars.entrySet()) {
                    /*
                     * the following 3 values in the Object array indicate:
                     * i) the name of the data ii) the current value of the
                     * data iii) that the data value was not changed in the
                     * last step, i.e. no dynamical change and this is not a
                     * 'refresh' event
                     */
                    if (!datas.contains(e.getKey())) {
                        state.add(new Object[] { e.getKey(), e.getValue(), false });
                        datas.add(e.getKey());
                    }
                }
            }
            pos++;
        }
    }
    return eventsStates;
}

From source file:de.dfki.iui.mmds.scxml.engine.impl.SCXMLEngineImpl.java

/**
 * Instantiate and initialize the underlying executor instance.
 * /*w  ww . j  av  a  2  s .  c o m*/
 * @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:org.finra.datagenerator.engine.negscxml.NegSCXMLCommons.java

/**
 * For a given state in the state chart, every transition out from that state is checked against every possible
 * variable assignment; those combinations satisfying the transition condition are added to the bootstrap list
 *
 * @param nextState         the state whose transitions are checked and which was
 *                          expanded to get the variable assignments
 * @param product           a list of variable assignment maps
 * @param negativeVariables the variables with a negative value, or an empty set
 * @param bootStrap         the bootstrap list
 *//*from  w ww .ja  v a 2s  .  c  o m*/
public void checkTransitions(TransitionTarget nextState, List<Map<String, String>> product,
        Set<String> negativeVariables, List<NegPossibleState> bootStrap) {
    //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) {
            //transition condition satisfied, add to bootstrap list
            if (checkTransition(p, condition, negativeVariables)) {
                NegPossibleState result = new NegPossibleState(target, p, negativeVariables);
                bootStrap.add(result);
            }
        }
    }
}

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
 *///  w w w.j a v a 2 s. c  om
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   www  .j  a va  2s. com*/
    }

    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);
            }
        }
    }
}