Package org.modeshape.jcr.api.sequencer

Examples of org.modeshape.jcr.api.sequencer.Sequencer$Context


     * </ul>
     */
    public static void execute(final String uri, final Evaluator evaluator) {
        try {
            String documentURI = getCanonicalURI(uri);
            Context rootCtx = evaluator.newContext(null);
            Tracer trc = new Tracer();
            SCXML doc = SCXMLReader.read(new URL(documentURI));
            if (doc == null) {
                System.err.println("The SCXML document " + uri
                        + " can not be parsed!");
                System.exit(-1);
            }
            System.out.println(SCXMLWriter.write(doc));
            SCXMLExecutor exec = new SCXMLExecutor(evaluator, null, trc);
            EventDispatcher ed = new SimpleScheduler(exec);
            exec.setEventdispatcher(ed);
            exec.setStateMachine(doc);
            exec.addListener(doc, trc);
            exec.registerInvokerClass("scxml", SimpleSCXMLInvoker.class);
            exec.setRootContext(rootCtx);
            exec.go();
            BufferedReader br = new BufferedReader(new
                InputStreamReader(System.in));
            String event;
            while ((event = br.readLine()) != null) {
                event = event.trim();
                if (event.equalsIgnoreCase("help") || event.equals("?")) {
                    System.out.println("Enter a space-separated list of "
                        + "events");
                    System.out.println("To populate a variable in the "
                        + "current context, type \"name=value\"");
                    System.out.println("To quit, enter \"quit\"");
                    System.out.println("To reset state machine, enter "
                        + "\"reset\"");
                } else if (event.equalsIgnoreCase("quit")) {
                    break;
                } else if (event.equalsIgnoreCase("reset")) {
                    exec.reset();
                } else if (event.indexOf('=') != -1) {
                    int marker = event.indexOf('=');
                    String name = event.substring(0, marker);
                    String value = event.substring(marker + 1);
                    rootCtx.setLocal(name, value);
                    System.out.println("Set variable " + name + " to "
                        + value);
                } else if (event == null || event.trim().length() == 0
                           || event.equalsIgnoreCase("null")) {
                    TriggerEvent[] evts = {new TriggerEvent(null,
View Full Code Here


        else if (!transition.isNoEventsTransition()) {
            return false;
        }
        if (transition.getCond() != null) {
            Boolean result = Boolean.FALSE;
            Context context = exctx.getScInstance().getContext(transition.getParent());
            context.setLocal(Context.NAMESPACES_KEY, transition.getNamespaces());
            try {
                if ((result = exctx.getEvaluator().evalCond(context, transition.getCond())) == null) {
                    result = Boolean.FALSE;
                    if (exctx.getAppLog().isDebugEnabled()) {
                        exctx.getAppLog().debug("Treating as false because the cond expression was evaluated as null: '"
                                + transition.getCond() + "'");
                    }
                }
            }
            catch (SCXMLExpressionException e) {
                exctx.getInternalIOProcessor().addEvent(new TriggerEvent(TriggerEvent.ERROR_EXECUTION, TriggerEvent.ERROR_EVENT));
                exctx.getErrorReporter().onError(ErrorConstants.EXPRESSION_ERROR, "Treating as false due to error: "
                        + e.getMessage(), transition);
            }
            finally {
                context.setLocal(Context.NAMESPACES_KEY, null);
            }
            return result;
        }
        return true;
    }
View Full Code Here

     * @param scInstance the state machine instance holding the system context
     * @param event The event being stored
     * @param internal Flag indicating the event was received internally or externally
     */
    public void setSystemEventVariable(final SCInstance scInstance, final TriggerEvent event, boolean internal) {
        Context systemContext = scInstance.getSystemContext();
        EventVariable eventVar = null;
        if (event != null) {
            String eventType = internal ? EventVariable.TYPE_INTERNAL : EventVariable.TYPE_EXTERNAL;

            final int triggerEventType = event.getType();
            if (triggerEventType == TriggerEvent.ERROR_EVENT || triggerEventType == TriggerEvent.CHANGE_EVENT) {
                eventType = EventVariable.TYPE_PLATFORM;
            }

            // TODO: determine sendid, origin, originType and invokeid based on context later.
            eventVar = new EventVariable(event.getName(), eventType, null, null, null, null, event.getPayload());
        }
        systemContext.setLocal(SCXMLSystemContext.EVENT_KEY, eventVar);
    }
View Full Code Here

        Evaluator eval = exctx.getEvaluator();
        for (TransitionalState ts : statesToInvoke) {
            if (ts.getInvokes().isEmpty()) {
                continue;
            }
            Context context = scInstance.getContext(ts);
            for (Invoke i : ts.getInvokes()) {
                String src = i.getSrc();
                if (src == null) {
                    String srcexpr = i.getSrcexpr();
                    Object srcObj;
                    try {
                        context.setLocal(Context.NAMESPACES_KEY, i.getNamespaces());
                        srcObj = eval.eval(context, srcexpr);
                        context.setLocal(Context.NAMESPACES_KEY, null);
                        src = String.valueOf(srcObj);
                    } catch (SCXMLExpressionException see) {
                        exctx.getInternalIOProcessor().addEvent(new TriggerEvent(TriggerEvent.ERROR_EXECUTION, TriggerEvent.ERROR_EVENT));
                        exctx.getErrorReporter().onError(ErrorConstants.EXPRESSION_ERROR, see.getMessage(), i);
                    }
                }
                String source = src;
                PathResolver pr = i.getPathResolver();
                if (pr != null) {
                    source = i.getPathResolver().resolvePath(src);
                }
                Invoker inv;
                try {
                    inv = exctx.newInvoker(i.getType());
                } catch (InvokerException ie) {
                    exctx.getInternalIOProcessor().addEvent(new TriggerEvent("failed.invoke."+ts.getId(), TriggerEvent.ERROR_EVENT));
                    continue;
                }
                List<Param> params = i.params();
                Map<String, Object> args = new HashMap<String, Object>();
                for (Param p : params) {
                    String argExpr = p.getExpr();
                    Object argValue = null;
                    context.setLocal(Context.NAMESPACES_KEY, p.getNamespaces());
                    // Do we have an "expr" attribute?
                    if (argExpr != null && argExpr.trim().length() > 0) {
                        try {
                            argValue = eval.eval(context, argExpr);
                        } catch (SCXMLExpressionException see) {
                            exctx.getInternalIOProcessor().addEvent(new TriggerEvent(TriggerEvent.ERROR_EXECUTION, TriggerEvent.ERROR_EVENT));
                            exctx.getErrorReporter().onError(ErrorConstants.EXPRESSION_ERROR, see.getMessage(), i);
                        }
                    } else {
                        // No. Does value of "name" attribute refer to a valid
                        // location in the data model?
                        try {
                            argValue = eval.evalLocation(context, p.getName());
                            if (argValue == null) {
                                // Generate error, 4.3.1 in WD-scxml-20080516
                                exctx.getInternalIOProcessor().addEvent(new TriggerEvent(ts.getId() + ERR_ILLEGAL_ALLOC, TriggerEvent.ERROR_EVENT));
                            }
                        } catch (SCXMLExpressionException see) {
                            exctx.getInternalIOProcessor().addEvent(new TriggerEvent(TriggerEvent.ERROR_EXECUTION, TriggerEvent.ERROR_EVENT));
                            exctx.getErrorReporter().onError(ErrorConstants.EXPRESSION_ERROR, see.getMessage(), i);
                        }
                    }
                    context.setLocal(Context.NAMESPACES_KEY, null);
                    args.put(p.getName(), argValue);
                }
                String invokeId = exctx.setInvoker(i, inv);
                inv.setInvokeId(invokeId);
                inv.setParentIOProcessor(exctx.getExternalIOProcessor());
View Full Code Here

    public boolean sequence( String sequencerName,
                             Property inputProperty,
                             Node outputNode ) throws RepositoryException {
        CheckArg.isSame(inputProperty.getSession(), "inputProperty", this, "this session");
        CheckArg.isSame(outputNode.getSession(), "outputNode", this, "this session");
        Sequencer sequencer = repository().runningState().sequencers().getSequencer(sequencerName);
        if (sequencer == null) return false;

        final ValueFactory values = getValueFactory();
        final DateTime now = dateFactory().create();
        final Sequencer.Context context = new Sequencer.Context() {

            @Override
            public ValueFactory valueFactory() {
                return values;
            }

            @Override
            public Calendar getTimestamp() {
                return now.toCalendar();
            }
        };
        try {
            if (sequencer.hasAcceptedMimeTypes()) {
                // Get the MIME type, first by looking at the changed property's parent node
                // (or grand-parent node if parent is 'jcr:content') ...
                String mimeType = SequencingRunner.getInputMimeType(inputProperty);

                // See if the sequencer accepts the MIME type ...
                if (mimeType != null && !sequencer.isAccepted(mimeType)) {
                    Logger.getLogger(getClass())
                          .debug("Skipping sequencing because input's MIME type '{0}' is not accepted by the '{1}' sequencer",
                                 mimeType, sequencerName);
                    return false;
                }
            }
            return sequencer.execute(inputProperty, outputNode, context);
        } catch (RepositoryException e) {
            throw e;
        } catch (Exception e) {
            throw new RepositoryException(e);
        }
View Full Code Here

    @Override
    public void run() {
        JcrSession inputSession = null;
        JcrSession outputSession = null;
        final RepositoryStatistics stats = repository.statistics();
        Sequencer sequencer = null;
        String sequencerName = null;
        try {
            // Create the required session(s) ...
            inputSession = repository.loginInternalSession(work.getInputWorkspaceName());
            if (work.getOutputWorkspaceName() != null && !work.getOutputWorkspaceName().equals(work.getInputWorkspaceName())) {
                outputSession = repository.loginInternalSession(work.getOutputWorkspaceName());
            } else {
                outputSession = inputSession;
            }

            // Get the sequencer ...
            sequencer = repository.sequencers().getSequencer(work.getSequencerId());
            if (sequencer == null) {
                if (DEBUG) {
                    LOGGER.debug("Unable to find sequencer with ID '{0}' in repository '{1}'; skipping input '{3}:{2}' and output '{5}:{4}'",
                                 work.getSequencerId(), repository.name(), work.getInputPath(), work.getInputWorkspaceName(),
                                 work.getOutputPath(), work.getOutputWorkspaceName());
                }
                return;
            }
            sequencerName = sequencer.getName();

            String logMsg = null;
            if (TRACE || DEBUG) {
                logMsg = StringUtil.createString("sequencer '{0}' in repository '{1}' with input '{3}:{2}' to produce '{5}:{4}'",
                                                 sequencerName,
                                                 repository.name(),
                                                 work.getInputPath(),
                                                 work.getInputWorkspaceName(),
                                                 work.getOutputPath(),
                                                 work.getOutputWorkspaceName() != null ? work.getOutputWorkspaceName() : work.getInputWorkspaceName());
                LOGGER.debug("Running {0}", logMsg);
            }

            // Find the selected node ...
            AbstractJcrNode selectedNode = inputSession.getNode(work.getSelectedPath());

            // Find the input that has changed and is to be sequenced ...
            Item inputItem = inputSession.getItem(work.getInputPath());
            Property changedProperty = null;
            if (inputItem instanceof Property) {
                changedProperty = (Property)inputItem;
            } else {
                Node changedNode = (Node)inputItem;
                // now look for a property that was changed or added ...
                changedProperty = changedNode.getProperty(work.getChangedPropertyName());
            }
            assert changedProperty != null;

            if (sequencer.hasAcceptedMimeTypes()) {
                // Get the MIME type, first by looking at the changed property's parent node
                // (or grand-parent node if parent is 'jcr:content') ...
                String mimeType = getInputMimeType(changedProperty);

                // See if the sequencer accepts the MIME type ...
                if (mimeType != null && !sequencer.isAccepted(mimeType)) {
                    LOGGER.debug("Skipping sequencing because MIME type of input doesn't match expectations for {0}", logMsg);
                    return; // nope
                }
            }

            AbstractJcrNode outputNode = null;
            String primaryType = null;
            if (work.getSelectedPath().equals(work.getOutputPath())) {
                // The output is to go directly under the sequenced node ...
                outputNode = selectedNode.getName().equals(JcrConstants.JCR_CONTENT) ? selectedNode.getParent() : selectedNode;
                primaryType = selectedNode.getPrimaryNodeType().getName();
            } else {
                // Find the parent of the output if it exists, or create the node(s) along the path if not ...
                AbstractJcrNode parentOfOutput = null;
                try {
                    parentOfOutput = outputSession.getNode(work.getOutputPath());
                } catch (PathNotFoundException e) {
                    LOGGER.trace("Creating missing output path for {0}", logMsg);
                    JcrTools tools = new JcrTools();
                    parentOfOutput = (AbstractJcrNode)tools.findOrCreateNode(outputSession, work.getOutputPath());
                }

                // Now determine the name of top node in the output, using the last segment of the selected path ...
                String outputNodeName = computeOutputNodeName(selectedNode);

                // Remove any existing output (from a prior sequencing run on this same input) ...
                removeExistingOutputNodes(parentOfOutput, outputNodeName, work.getSelectedPath(), logMsg);

                // Create the output node
                if (parentOfOutput.isNew() && parentOfOutput.getName().equals(outputNodeName)) {
                    // avoid creating a duplicate path with the same name
                    outputNode = parentOfOutput;
                } else {
                    if (TRACE) {
                        LOGGER.trace("Creating output node '{0}' under parent '{1}' for {2}", outputNodeName,
                                     parentOfOutput.getPath(), logMsg);
                    }
                    outputNode = parentOfOutput.addNode(outputNodeName, JcrConstants.NT_UNSTRUCTURED);
                }

                // and make sure the output node has the 'mode:derived' mixin ...
                outputNode.addMixin(DERIVED_NODE_TYPE_NAME);
                outputNode.setProperty(DERIVED_FROM_PROPERTY_NAME, work.getSelectedPath());
            }

            // Execute the sequencer ...
            DateTime now = outputSession.dateFactory().create();
            Sequencer.Context context = new SequencingContext(now, outputSession.getValueFactory());
            if (inputSession.isLive() && (inputSession == outputSession || outputSession.isLive())) {
                final long start = System.nanoTime();

                try {
                    LOGGER.trace("Executing {0}", logMsg);
                    if (sequencer.execute(changedProperty, outputNode, context)) {
                        LOGGER.trace("Completed executing {0}", logMsg);

                        // Make sure that the sequencer did not change the primary type of the selected node ..
                        if (selectedNode == outputNode && !selectedNode.getPrimaryNodeType().getName().equals(primaryType)) {
                            String msg = RepositoryI18n.sequencersMayNotChangeThePrimaryTypeOfTheSelectedNode.text();
                            throw new RepositoryException(msg);
                        }

                        // find the new nodes created by the sequencing before saving, so we can properly fire the events
                        List<AbstractJcrNode> outputNodes = findOutputNodes(outputNode);

                        // set the createdBy property (if it applies) to the user which triggered the sequencing, not the context
                        // of the saving session
                        setCreatedByIfNecessary(outputSession, outputNodes);

                        // outputSession
                        LOGGER.trace("Saving session used by {0}", logMsg);
                        outputSession.save();

                        // fire the sequencing event after save (hopefully by this time the transaction has been committed)
                        LOGGER.trace("Firing events resulting from {0}", logMsg);
                        fireSequencingEvent(selectedNode, outputNodes, outputSession, sequencerName);

                        long durationInNanos = Math.abs(System.nanoTime() - start);
                        Map<String, String> payload = new HashMap<String, String>();
                        payload.put("sequencerName", sequencer.getClass().getName());
                        payload.put("sequencedPath", changedProperty.getPath());
                        payload.put("outputPath", outputNode.getPath());
                        stats.recordDuration(DurationMetric.SEQUENCER_EXECUTION_TIME, durationInNanos, TimeUnit.NANOSECONDS,
                                             payload);
                    }
View Full Code Here

            this.pathExpressionsBySequencerId = new HashMap<UUID, Collection<SequencerPathExpression>>();

            String repoName = repository.name();
            for (Component component : components) {
                try {
                    Sequencer sequencer = component.createInstance(getClass().getClassLoader());
                    // Set the repository name field ...
                    ReflectionUtil.setValue(sequencer, "repositoryName", repoName);

                    // Set the logger instance
                    ReflectionUtil.setValue(sequencer, "logger", ExtensionLogger.getLogger(sequencer.getClass()));
                    // We'll initialize it later in #intialize() ...

                    sequencersByName.put(sequencer.getName(), sequencer);
                    if (sequencer.getPathExpressions().length == 0) {
                        // There are no path expressions, so this sequencer is only for explicit invocation ...
                        if (DEBUG) {
                            LOGGER.debug("Created sequencer '{0}' in repository '{1}' with no path expression; availabe only for explicit invocation",
                                         sequencer.getName(), repository.name());
                        }

                    } else {
                        // For each sequencer, figure out which workspaces apply ...
                        UUID uuid = sequencer.getUniqueId();
                        sequencersById.put(sequencer.getUniqueId(), sequencer);
                        // For each sequencer, create the path expressions ...

                        Set<SequencerPathExpression> pathExpressions = buildPathExpressionSet(sequencer);
                        pathExpressionsBySequencerId.put(uuid, pathExpressions);
                        if (DEBUG) {
                            LOGGER.debug("Created sequencer '{0}' in repository '{1}' with valid path expressions: {2}",
                                         sequencer.getName(), repository.name(), pathExpressions);
                        }
                    }
                } catch (Throwable t) {
                    if (t.getCause() != null) {
                        t = t.getCause();
View Full Code Here

                                                + nodeTypeManager.getClass().getName());
            }

            // Initialize each sequencer using the supplied session ...
            for (Iterator<Map.Entry<String, Sequencer>> sequencersIterator = sequencersByName.entrySet().iterator(); sequencersIterator.hasNext();) {
                Sequencer sequencer = sequencersIterator.next().getValue();
                try {
                    sequencer.initialize(registry, (org.modeshape.jcr.api.nodetype.NodeTypeManager)nodeTypeManager);

                    // If successful, call the 'postInitialize' method reflectively (due to inability to call directly) ...
                    Method postInitialize = ReflectionUtil.findMethod(Sequencer.class, "postInitialize");
                    ReflectionUtil.invokeAccessibly(sequencer, postInitialize, new Object[] {});
                    if (DEBUG) {
                        LOGGER.debug("Successfully initialized sequencer '{0}' in repository '{1}'", sequencer.getName(),
                                     repository.name());
                    }
                    initialized.add(sequencer);
                } catch (Throwable t) {
                    if (t.getCause() != null) {
                        t = t.getCause();
                    }
                    repository.error(t, JcrI18n.unableToInitializeSequencer, sequencer, repository.name(), t.getMessage());
                    try {
                        sequencersIterator.remove();
                    } finally {
                        sequencersById.remove(sequencer.getUniqueId());
                    }
                }
            }
            this.initialized = true;
        } catch (RepositoryException e) {
View Full Code Here

TOP

Related Classes of org.modeshape.jcr.api.sequencer.Sequencer$Context

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.