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

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

Introduction

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

Prototype

public final String getId() 

Source Link

Document

Get the identifier for this transition target (may be null).

Usage

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

@Override
public List<String> getActiveStates() {
    Set<TransitionTarget> states = engine.getCurrentStatus().getStates();
    List<String> ids = new LinkedList<String>();
    for (TransitionTarget t : states) {
        ids.add(t.getId());
    }//from  w  w  w. j a va2  s  .  com
    return ids;
}

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

@Override
public List<String> getAllActiveStates() {
    Set<TransitionTarget> states = engine.getCurrentStatus().getAllStates();
    List<String> ids = new LinkedList<String>();
    for (TransitionTarget t : states) {
        ids.add(t.getId());
    }/*from   w ww  .  j a v a 2 s . c o m*/
    return ids;
}

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

/**
 * @param lastLeafs/*from  w w  w.ja  va  2  s . c o m*/
 * @return
 */
private void updateConfigHistory(Set<TransitionTarget> lastLeafs) {
    if (lastLeafs.equals(engine.getCurrentStatus().getStates()))
        // only update the history if there was a change in the
        // configuration
        return;
    int histSize = configHistory.size();
    if (0 < histSize && histSize == CONFIG_HISTORY_SIZE) {
        configHistory.pollLast();
    }
    if (configHistory.size() < CONFIG_HISTORY_SIZE) {
        Set<TransitionTarget> leafs = engine.getCurrentStatus().getStates();
        Set<String> leafStateIds = new HashSet<String>(leafs.size());
        for (TransitionTarget tt : leafs) {
            leafStateIds.add(tt.getId());
        }
        configHistory.push(leafStateIds);
    }
}

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;/*  w w w.  j ava 2s. c  om*/
    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.
 * /*from ww w .  j a va 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:org.dishevelled.piccolo.identify.StateMachineSupport.java

/**
 * Create a new state machine support class to be delegated to
 * by the specified delegator with the specified state machine.
 *
 * @param delegator object delegating to this state machine support
 *    class, must not be null//from w  w  w.  ja va 2s.  c  o m
 * @param stateMachine state machine for this support class, must
 *    not be null
 */
StateMachineSupport(final Object delegator, final SCXML stateMachine) {
    if (delegator == null) {
        throw new IllegalArgumentException("delegator must not be null");
    }
    if (stateMachine == null) {
        throw new IllegalArgumentException("stateMachine must not be null");
    }
    this.delegator = delegator;

    Evaluator evaluator = new JexlEvaluator();
    EventDispatcher dispatcher = new SimpleDispatcher();
    ErrorReporter errorReporter = new NoopErrorReporter();
    Context rootContext = new JexlContext();
    SCXMLListener listener = new SCXMLListener() {
        @Override
        public void onEntry(final TransitionTarget entered) {
            invoke(entered.getId());
        }

        @Override
        public void onExit(final TransitionTarget exited) {
            // empty
        }

        @Override
        public void onTransition(final TransitionTarget to, final TransitionTarget from,
                final Transition transition) {
            // empty
        }
    };

    executor = new SCXMLExecutor(evaluator, dispatcher, errorReporter);
    executor.setStateMachine(stateMachine);
    executor.setSuperStep(false);
    executor.setRootContext(rootContext);
    executor.addListener(stateMachine, listener);

    try {
        executor.go();
    } catch (ModelException e) {
        // ignore
    }
}

From source file:org.dishevelled.piccolo.sprite.statemachine.AbstractStateMachineSprite.java

/**
 * Initialize the specified state machine.  Animations are loaded for all
 * the state ids and the current animation is set to the initial target, if any.
 *
 * <p>/*from  ww w  .j  a  v a 2  s.c  om*/
 * <b>Note:</b> this method should be called from the constructor
 * of a subclass after its state machine has been instantiated.
 * </p>
 *
 * @param stateMachine state machine to initialize, must not be null
 */
protected final void initializeStateMachine(final SCXML stateMachine) {
    if (stateMachine == null) {
        throw new IllegalArgumentException("stateMachine must not be null");
    }
    // load animations for state ids
    for (Iterator<?> entries = stateMachine.getTargets().entrySet().iterator(); entries.hasNext();) {
        Map.Entry<?, ?> entry = (Map.Entry<?, ?>) entries.next();
        String id = (String) entry.getKey();
        Object target = entry.getValue();
        if (target instanceof State) {
            Animation animation = createAnimation(id);
            if (animation != null) {
                animations.put(id, animation);
            }
        }
    }
    // set the current animation to the initial target, if any
    String initialTargetId = (stateMachine.getInitialTarget() == null) ? null
            : stateMachine.getInitialTarget().getId();
    if (animations.containsKey(initialTargetId)) {
        currentAnimation = animations.get(initialTargetId);
    }
    // create a state machine support class that delegates to this
    stateMachineSupport = new StateMachineSupport(this, stateMachine);
    // update current animation on entry to a new state
    stateMachineSupport.getExecutor().addListener(stateMachine, new AbstractSCXMLListener() {
        @Override
        public void onEntry(final TransitionTarget state) {
            Animation animation = animations.get(state.getId());
            if (animation != null) {
                currentAnimation = animation;
            }
        }
    });
}

From source file:org.finra.datagenerator.engine.negscxml.NegSCXMLGapper.java

/**
 * Takes a model and a NegSCXMLFrontier and decomposes the Frontier into a Map of Strings to Strings
 * These strings can be sent over a network to get a Frontier past a 'gap'
 *
 * @param frontier  the Frontier//from   w w  w.  j ava2 s .com
 * @param modelText the model
 * @return the map of strings representing a decomposition
 */
public Map<String, String> decompose(Frontier frontier, String modelText) {
    if (!(frontier instanceof NegSCXMLFrontier)) {
        return null;
    }

    setModel(modelText);

    TransitionTarget target = ((NegSCXMLFrontier) frontier).getRoot().nextState;
    Map<String, String> variables = ((NegSCXMLFrontier) frontier).getRoot().variables;
    Set<String> negVariables = ((NegSCXMLFrontier) frontier).getRoot().negVariable;
    int negative = ((NegSCXMLFrontier) frontier).getNegative();

    Map<String, String> decomposition = new HashMap<String, String>();
    decomposition.put("negative", String.valueOf(negative));
    decomposition.put("target", target.getId());

    StringBuilder packedVariables = new StringBuilder();
    for (Map.Entry<String, String> variable : variables.entrySet()) {
        packedVariables.append(variable.getKey());
        packedVariables.append("::");
        packedVariables.append(variable.getValue());
        packedVariables.append(";");
    }
    decomposition.put("variables", packedVariables.toString());

    packedVariables = new StringBuilder();
    for (String variable : negVariables) {
        packedVariables.append(variable);
        packedVariables.append(";");
    }
    decomposition.put("negVariables", packedVariables.toString());

    decomposition.put("model", modelText);

    return decomposition;
}

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 ww w  .  j  a  va  2 s  .com
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 w w.j  av a 2 s  .c  o  m
    }

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