Example usage for org.dom4j Element getData

List of usage examples for org.dom4j Element getData

Introduction

In this page you can find the example usage for org.dom4j Element getData.

Prototype

Object getData();

Source Link

Document

Accesses the data of this element which may implement data typing bindings such as XML Schema or Java Bean bindings or will return the same value as #getText

Usage

From source file:org.orbeon.oxf.controller.PageFlowControllerBuilder.java

License:Open Source License

public static void handleEpilogue(final String controllerContext, List<ASTStatement> statements,
        final String epilogueURL, final Element epilogueElement, final ASTOutput epilogueData,
        final ASTOutput epilogueModelData, final ASTOutput epilogueInstance) {
    if (epilogueURL == null) {
        // Run HTML serializer if no epilogue is specified
        statements.add(new ASTChoose(new ASTHrefId(epilogueData)) {
            {/*  w w  w .j av  a2s  .c  o  m*/
                addWhen(new ASTWhen("not(/*/@xsi:nil = 'true')") {
                    {
                        setNamespaces(NAMESPACES_WITH_XSI_AND_XSLT);
                        // The epilogue did not do the serialization
                        addStatement(new ASTProcessorCall(XMLConstants.HTML_SERIALIZER_PROCESSOR_QNAME) {
                            {
                                Document config = new NonLazyUserDataDocument(
                                        new NonLazyUserDataElement("config"));
                                Element rootElement = config.getRootElement();
                                rootElement.addElement("version").addText("5.0");
                                rootElement.addElement("encoding").addText("utf-8");
                                addInput(new ASTInput("config", config));
                                addInput(new ASTInput("data", new ASTHrefId(epilogueData)));
                                //setLocationData(TODO);
                            }
                        });
                    }
                });
                addWhen(new ASTWhen());
            }
        });
    } else {
        // Send result through epilogue
        statements.add(new ASTProcessorCall(XMLConstants.PIPELINE_PROCESSOR_QNAME) {
            {
                final String url = URLFactory.createURL(controllerContext, epilogueURL).toExternalForm();

                addInput(new ASTInput("config", new ASTHrefURL(url)));
                addInput(new ASTInput("data", new ASTHrefId(epilogueData)));
                addInput(new ASTInput("model-data", new ASTHrefId(epilogueModelData)));
                addInput(new ASTInput("instance", new ASTHrefId(epilogueInstance)));
                final String[] locationParams = new String[] { "pipeline", epilogueURL };
                setLocationData(new ExtendedLocationData((LocationData) epilogueElement.getData(),
                        "executing epilogue", epilogueElement, locationParams));
            }
        });
    }
}

From source file:org.orbeon.oxf.controller.PageFlowControllerBuilder.java

License:Open Source License

/**
 * Handle <page>//from www .  ja v  a  2s . c om
 */
public static void handlePage(final StepProcessorContext stepProcessorContext, final String urlBase,
        List<ASTStatement> statementsList, final Element pageElement, final String matcherOutputOrParamId,
        final ASTOutput viewData, final ASTOutput epilogueModelData, final ASTOutput viewInstance,
        final Map<String, String> pageIdToPathInfo, final Map<String, Document> pageIdToSetvaluesDocument,
        final String instancePassing) {

    // Get page attributes
    final String modelAttribute = pageElement.attributeValue("model");
    final String viewAttribute = pageElement.attributeValue("view");
    final String defaultSubmissionAttribute = pageElement.attributeValue("default-submission");

    // Get setvalues document
    final Document setvaluesDocument = getSetValuesDocument(pageElement);

    // Get actions
    final List actionElements = pageElement.elements("action");

    // Handle initial instance
    final ASTOutput defaultSubmission = new ASTOutput("data", "default-submission");
    if (defaultSubmissionAttribute != null) {
        statementsList.add(new ASTProcessorCall(XMLConstants.URL_GENERATOR_PROCESSOR_QNAME) {
            {
                final String url = URLFactory.createURL(urlBase, defaultSubmissionAttribute).toExternalForm();

                final Document configDocument = new NonLazyUserDataDocument(
                        new NonLazyUserDataElement("config"));
                configDocument.getRootElement().addText(url);

                addInput(new ASTInput("config", configDocument));
                addOutput(defaultSubmission);
            }
        });
    }

    // XForms Input
    final ASTOutput isRedirect = new ASTOutput(null, "is-redirect");

    // Always hook up XML submission
    final ASTOutput xformedInstance = new ASTOutput("instance", "xformed-instance");
    {
        final LocationData locDat = Dom4jUtils.getLocationData();
        xformedInstance.setLocationData(locDat);
    }

    // Use XML Submission pipeline
    statementsList.add(new ASTProcessorCall(XMLConstants.PIPELINE_PROCESSOR_QNAME) {
        {
            addInput(new ASTInput("config", new ASTHrefURL(XFORMS_XML_SUBMISSION_XPL)));
            if (setvaluesDocument != null) {
                addInput(new ASTInput("setvalues", setvaluesDocument));
                addInput(new ASTInput("matcher-result", new ASTHrefId(matcherOutputOrParamId)));
            } else {
                addInput(new ASTInput("setvalues", Dom4jUtils.NULL_DOCUMENT));
                addInput(new ASTInput("matcher-result", Dom4jUtils.NULL_DOCUMENT));
            }
            if (defaultSubmissionAttribute != null) {
                addInput(new ASTInput("default-submission", new ASTHrefId(defaultSubmission)));
            } else {
                addInput(new ASTInput("default-submission", Dom4jUtils.NULL_DOCUMENT));
            }
            addOutput(xformedInstance);
        }
    });

    // Make sure the xformed-instance id is used for p:choose
    statementsList.add(new ASTProcessorCall(XMLConstants.NULL_PROCESSOR_QNAME) {
        {
            addInput(new ASTInput("data", new ASTHrefId(xformedInstance)));
        }
    });

    // Execute actions
    final ASTOutput xupdatedInstance = new ASTOutput(null, "xupdated-instance");
    final ASTOutput actionData = new ASTOutput(null, "action-data");
    final int[] actionNumber = new int[] { 0 };
    final boolean[] foundActionWithoutWhen = new boolean[] { false };
    final ASTChoose actionsChoose = new ASTChoose(new ASTHrefId(xformedInstance)) {
        {

            // Always add a branch to test on whether the XML submission asked to bypass actions, model, view, and epilogue
            // Use of this <bypass> document is arguably a HACK 
            addWhen(new ASTWhen() {
                {

                    setTest("/bypass[@xsi:nil = 'true']");
                    setNamespaces(NAMESPACES_WITH_XSI_AND_XSLT);

                    addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                        {
                            addInput(new ASTInput("data", Dom4jUtils.NULL_DOCUMENT));
                            addOutput(new ASTOutput("data", xupdatedInstance));
                        }
                    });
                    addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                        {
                            final Document config = new NonLazyUserDataDocument(
                                    new NonLazyUserDataElement("is-redirect"));
                            config.getRootElement().addText("true");
                            addInput(new ASTInput("data", config));
                            addOutput(new ASTOutput("data", isRedirect));
                        }
                    });
                    addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                        {
                            addInput(new ASTInput("data", Dom4jUtils.NULL_DOCUMENT));
                            addOutput(new ASTOutput("data", actionData));
                        }
                    });
                }
            });

            for (Object actionElement1 : actionElements) {

                // Get info about action
                actionNumber[0]++;
                final Element actionElement = (Element) actionElement1;
                final String whenAttribute;
                {
                    // NOTE: Prior to 2012-06-27, the XSD schema would put a default value of true()
                    final String tempWhen = actionElement.attributeValue("when");
                    if (tempWhen == null)
                        whenAttribute = "true()";
                    else
                        whenAttribute = tempWhen;
                }
                ;
                final String actionAttribute = actionElement.attributeValue("action");

                // Execute action
                addWhen(new ASTWhen() {
                    {

                        // Add condition, remember that we found an <action> without a when
                        if (whenAttribute != null) {
                            if (foundActionWithoutWhen[0])
                                throw new ValidationException("Unreachable <action>",
                                        (LocationData) actionElement.getData());
                            setTest(whenAttribute);
                            setNamespaces(new NamespaceMapping(
                                    Dom4jUtils.getNamespaceContextNoDefault(actionElement)));
                            setLocationData((LocationData) actionElement.getData());
                        } else {
                            foundActionWithoutWhen[0] = true;
                        }

                        final boolean resultTestsOnActionData =
                                // Must have an action, in the first place
                                actionAttribute != null &&
                        // More than one <result>: so at least the first one must have a "when"
                        actionElement.elements("result").size() > 1;

                        final ASTOutput internalActionData = actionAttribute == null ? null
                                : new ASTOutput(null, "internal-action-data-" + actionNumber[0]);
                        if (actionAttribute != null) {
                            // TODO: handle passing and modifications of action data in model, and view, and pass to instance
                            addStatement(new StepProcessorCall(stepProcessorContext, urlBase, actionAttribute,
                                    "action") {
                                {
                                    addInput(new ASTInput("data", Dom4jUtils.NULL_DOCUMENT));
                                    addInput(new ASTInput("instance", new ASTHrefId(xformedInstance)));
                                    addInput(new ASTInput("xforms-model", Dom4jUtils.NULL_DOCUMENT));
                                    addInput(new ASTInput("matcher", new ASTHrefId(matcherOutputOrParamId)));
                                    final ASTOutput dataOutput = new ASTOutput("data", internalActionData);
                                    final String[] locationParams = new String[] { "pipeline", actionAttribute,
                                            "page id", pageElement.attributeValue("id"), "when",
                                            whenAttribute };
                                    dataOutput.setLocationData(
                                            new ExtendedLocationData((LocationData) actionElement.getData(),
                                                    "reading action data output", pageElement, locationParams));
                                    addOutput(dataOutput);
                                    setLocationData(
                                            new ExtendedLocationData((LocationData) actionElement.getData(),
                                                    "executing action", pageElement, locationParams));
                                }
                            });

                            // Force execution of action if no <result> is reading it
                            if (!resultTestsOnActionData) {
                                addStatement(
                                        new ASTProcessorCall(XMLConstants.NULL_SERIALIZER_PROCESSOR_QNAME) {
                                            {
                                                addInput(new ASTInput("data",
                                                        new ASTHrefId(internalActionData)));
                                            }
                                        });
                            }

                            // Export internal-action-data as action-data
                            addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                                {
                                    addInput(new ASTInput("data", new ASTHrefId(internalActionData)));
                                    addOutput(new ASTOutput("data", actionData));
                                }
                            });
                        } else {
                            addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                                {
                                    addInput(new ASTInput("data", Dom4jUtils.NULL_DOCUMENT));
                                    addOutput(new ASTOutput("data", actionData));
                                }
                            });
                        }

                        if (actionElement.elements("result").size() > 0 && internalActionData != null) {
                            // At least one result testing on action

                            // Test based on action
                            addStatement(new ASTChoose(new ASTHrefId(internalActionData)) {
                                {
                                    for (Object o : actionElement.elements("result")) {
                                        final Element resultElement = (Element) o;
                                        final String resultWhenAttribute;
                                        {
                                            // NOTE: Prior to 2012-06-27, the XSD schema would put a default value of true()
                                            final String tempWhen = resultElement.attributeValue("when");
                                            if (tempWhen == null)
                                                resultWhenAttribute = "true()";
                                            else
                                                resultWhenAttribute = tempWhen;
                                        }
                                        ;

                                        // Execute result
                                        addWhen(new ASTWhen() {
                                            {
                                                if (resultWhenAttribute != null) {
                                                    setTest(resultWhenAttribute);
                                                    setNamespaces(new NamespaceMapping(Dom4jUtils
                                                            .getNamespaceContextNoDefault(resultElement)));
                                                    final String[] locationParams = new String[] { "page id",
                                                            pageElement.attributeValue("id"), "when",
                                                            resultWhenAttribute };
                                                    setLocationData(new ExtendedLocationData(
                                                            (LocationData) resultElement.getData(),
                                                            "executing result", resultElement, locationParams));
                                                }
                                                executeResult(this, pageIdToPathInfo, pageIdToSetvaluesDocument,
                                                        xformedInstance, resultElement, internalActionData,
                                                        isRedirect, xupdatedInstance, instancePassing);
                                            }
                                        });
                                    }

                                    // Continue when all results fail
                                    addWhen(new ASTWhen() {
                                        {
                                            addStatement(new ASTProcessorCall(
                                                    XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                                                {
                                                    addInput(new ASTInput("data", new NonLazyUserDataDocument(
                                                            new NonLazyUserDataElement("is-redirect") {
                                                                {
                                                                    setText("false");
                                                                }
                                                            })));
                                                    addOutput(new ASTOutput("data", isRedirect));
                                                }
                                            });
                                            addStatement(new ASTProcessorCall(
                                                    XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                                                {
                                                    addInput(new ASTInput("data",
                                                            new ASTHrefId(xformedInstance)));
                                                    addOutput(new ASTOutput("data", xupdatedInstance));
                                                }
                                            });
                                        }
                                    });
                                }
                            });

                        } else {
                            // No result or result not depending on action
                            final Element resultElement = actionElement.element("result");
                            executeResult(this, pageIdToPathInfo, pageIdToSetvaluesDocument, xformedInstance,
                                    resultElement, internalActionData, isRedirect, xupdatedInstance,
                                    instancePassing);
                        }
                    }
                });
            }

            if (!foundActionWithoutWhen[0]) {
                // Default branch for when all actions fail
                addWhen(new ASTWhen() {
                    {
                        addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                            {
                                addInput(new ASTInput("data", new ASTHrefId(xformedInstance)));
                                addOutput(new ASTOutput("data", xupdatedInstance));
                            }
                        });
                        addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                            {
                                final Document config = new NonLazyUserDataDocument(
                                        new NonLazyUserDataElement("is-redirect"));
                                config.getRootElement().addText("false");
                                addInput(new ASTInput("data", config));
                                addOutput(new ASTOutput("data", isRedirect));
                            }
                        });
                        addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                            {
                                addInput(new ASTInput("data", Dom4jUtils.NULL_DOCUMENT));
                                addOutput(new ASTOutput("data", actionData));
                            }
                        });
                    }
                });
            }
        }
    };

    // Add choose statement
    statementsList.add(actionsChoose);

    // Only continue if there was no redirect
    statementsList.add(new ASTChoose(new ASTHrefId(isRedirect)) {
        {
            addWhen(new ASTWhen("/is-redirect = 'false'") {
                {

                    // Handle page model
                    final ASTOutput modelData = new ASTOutput(null, "model-data");
                    final ASTOutput modelInstance = new ASTOutput(null, "model-instance");
                    if (modelAttribute != null) {
                        // There is a model
                        addStatement(
                                new StepProcessorCall(stepProcessorContext, urlBase, modelAttribute, "model") {
                                    {
                                        addInput(new ASTInput("data", new ASTHrefId(actionData)));
                                        addInput(new ASTInput("instance", new ASTHrefId(xupdatedInstance)));
                                        addInput(new ASTInput("xforms-model", Dom4jUtils.NULL_DOCUMENT));
                                        addInput(
                                                new ASTInput("matcher", new ASTHrefId(matcherOutputOrParamId)));
                                        final String[] locationParams = new String[] { "page id",
                                                pageElement.attributeValue("id"), "model", modelAttribute };
                                        {
                                            final ASTOutput dataOutput = new ASTOutput("data", modelData);
                                            dataOutput.setLocationData(new ExtendedLocationData(
                                                    (LocationData) pageElement.getData(),
                                                    "reading page model data output", pageElement,
                                                    locationParams));
                                            addOutput(dataOutput);
                                        }
                                        {
                                            final ASTOutput instanceOutput = new ASTOutput("instance",
                                                    modelInstance);
                                            addOutput(instanceOutput);
                                            instanceOutput.setLocationData(new ExtendedLocationData(
                                                    (LocationData) pageElement.getData(),
                                                    "reading page model instance output", pageElement,
                                                    locationParams));
                                        }
                                        setLocationData(
                                                new ExtendedLocationData((LocationData) pageElement.getData(),
                                                        "executing page model", pageElement, locationParams));
                                    }
                                });
                    } else if (viewAttribute != null) {
                        // There is no model but there is a view
                        addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                            {
                                addInput(new ASTInput("data", new ASTHrefId(actionData)));
                                addOutput(new ASTOutput("data", modelData));
                            }
                        });
                        addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                            {
                                addInput(new ASTInput("data", new ASTHrefId(xupdatedInstance)));
                                addOutput(new ASTOutput("data", modelInstance));
                            }
                        });
                    }

                    // Handle page view
                    if (viewAttribute != null) {
                        // There is a view
                        addStatement(
                                new StepProcessorCall(stepProcessorContext, urlBase, viewAttribute, "view") {
                                    {
                                        addInput(new ASTInput("data", new ASTHrefId(modelData)));
                                        addInput(new ASTInput("instance", new ASTHrefId(modelInstance)));
                                        addInput(new ASTInput("xforms-model", Dom4jUtils.NULL_DOCUMENT));
                                        addInput(
                                                new ASTInput("matcher", new ASTHrefId(matcherOutputOrParamId)));
                                        final String[] locationParams = new String[] { "page id",
                                                pageElement.attributeValue("id"), "view", viewAttribute };
                                        {
                                            final ASTOutput dataOutput = new ASTOutput("data", viewData);
                                            dataOutput.setLocationData(new ExtendedLocationData(
                                                    (LocationData) pageElement.getData(),
                                                    "reading page view data output", pageElement,
                                                    locationParams));
                                            addOutput(dataOutput);
                                        }
                                        {
                                            final ASTOutput instanceOutput = new ASTOutput("instance",
                                                    viewInstance);
                                            instanceOutput.setLocationData(new ExtendedLocationData(
                                                    (LocationData) pageElement.getData(),
                                                    "reading page view instance output", pageElement,
                                                    locationParams));
                                            addOutput(instanceOutput);
                                        }
                                        setLocationData(
                                                new ExtendedLocationData((LocationData) pageElement.getData(),
                                                        "executing page view", pageElement, locationParams));
                                    }
                                });
                    } else {
                        // There is no view, send nothing to epilogue
                        addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                            {
                                addInput(new ASTInput("data", Dom4jUtils.NULL_DOCUMENT));
                                addOutput(new ASTOutput("data", viewData));
                            }
                        });
                        addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                            {
                                addInput(new ASTInput("data", Dom4jUtils.NULL_DOCUMENT));
                                addOutput(new ASTOutput("data", viewInstance));
                            }
                        });
                    }

                    if (modelAttribute != null && viewAttribute == null) {
                        // With XForms NG we want lazy evaluation of the instance, so we should not force a
                        // read on the instance. We just connect the output.
                        addStatement(new ASTProcessorCall(XMLConstants.NULL_PROCESSOR_QNAME) {
                            {
                                addInput(new ASTInput("data", new ASTHrefId(modelInstance)));
                            }
                        });
                    }

                    if (modelAttribute == null && viewAttribute == null) {
                        // Send out epilogue model data as a null document
                        addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                            {
                                addInput(new ASTInput("data", Dom4jUtils.NULL_DOCUMENT));
                                addOutput(new ASTOutput("data", epilogueModelData));
                            }
                        });
                    } else {
                        // Send out epilogue model data as produced by the model or used by the view
                        addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                            {
                                addInput(new ASTInput("data", new ASTHrefId(modelData)));
                                addOutput(new ASTOutput("data", epilogueModelData));
                            }
                        });
                    }

                }
            });
            addWhen(new ASTWhen() {
                {
                    // There is a redirection due to the action

                    // With XForms NG we want lazy evaluation of the instance, so we should not force a
                    // read on the instance. We just connect the output.
                    addStatement(new ASTProcessorCall(XMLConstants.NULL_PROCESSOR_QNAME) {
                        {
                            addInput(new ASTInput("data", new ASTHrefId(xupdatedInstance)));
                        }
                    });
                    // Just connect the output
                    addStatement(new ASTProcessorCall(XMLConstants.NULL_PROCESSOR_QNAME) {
                        {
                            addInput(new ASTInput("data", new ASTHrefId(actionData)));
                        }
                    });
                    addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                        {
                            addInput(new ASTInput("data", Dom4jUtils.NULL_DOCUMENT));
                            addOutput(new ASTOutput("data", viewData));
                        }
                    });
                    addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                        {
                            addInput(new ASTInput("data", Dom4jUtils.NULL_DOCUMENT));
                            addOutput(new ASTOutput("data", epilogueModelData));
                        }
                    });
                    addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                        {
                            addInput(new ASTInput("data", Dom4jUtils.NULL_DOCUMENT));
                            addOutput(new ASTOutput("data", viewInstance));
                        }
                    });
                }
            });
        }
    });
}

From source file:org.orbeon.oxf.controller.PageFlowControllerBuilder.java

License:Open Source License

private static void executeResult(ASTWhen when, final Map<String, String> pageIdToPathInfo,
        final Map<String, Document> pageIdToSetvaluesDocument, final ASTOutput instanceToUpdate,
        final Element resultElement, final ASTOutput actionData, final ASTOutput redirect,
        final ASTOutput xupdatedInstance, String instancePassing) {

    // Instance to update: either current, or instance from other page
    final String resultPageId = resultElement == null ? null : resultElement.attributeValue("page");
    Attribute instancePassingAttribute = resultElement == null ? null
            : resultElement.attribute("instance-passing");
    final String _instancePassing = instancePassingAttribute == null ? instancePassing
            : instancePassingAttribute.getValue();

    // Create resulting instance
    final ASTOutput internalXUpdatedInstance;
    final boolean isTransformedInstance;
    if (resultElement != null && resultElement.attribute("transform") != null
            && !resultElement.elements().isEmpty()) {
        // Generic transform mechanism
        internalXUpdatedInstance = new ASTOutput("data", "internal-xupdated-instance");
        isTransformedInstance = true;//ww w . j  a  v a 2 s  .co m

        final Document transformConfig = Dom4jUtils
                .createDocumentCopyParentNamespaces((Element) resultElement.elements().get(0));
        final QName transformQName = Dom4jUtils.extractAttributeValueQName(resultElement, "transform");

        // Run transform
        final String resultTraceAttribute = resultElement.attributeValue("trace");
        when.addStatement(new ASTProcessorCall(transformQName) {
            {
                addInput(new ASTInput("config", transformConfig));// transform
                addInput(new ASTInput("instance", new ASTHrefId(instanceToUpdate)));// source-instance
                addInput(new ASTInput("data", new ASTHrefId(instanceToUpdate)));// destination-instance
                //addInput(new ASTInput("request-instance", new ASTHrefId(requestInstance)));// params-instance TODO
                if (actionData != null)
                    addInput(new ASTInput("action", new ASTHrefId(actionData)));// action
                else
                    addInput(new ASTInput("action", Dom4jUtils.NULL_DOCUMENT));// action
                addOutput(new ASTOutput("data", internalXUpdatedInstance) {
                    {
                        setDebug(resultTraceAttribute);
                    }
                });// updated-instance
            }
        });
    } else {
        internalXUpdatedInstance = instanceToUpdate;
        isTransformedInstance = false;
    }

    // Do redirect if we are going to a new page (NOTE: even if the new page has the same id as the current page)
    if (resultPageId != null) {
        final String forwardPathInfo = pageIdToPathInfo.get(resultPageId);
        if (forwardPathInfo == null)
            throw new OXFException("Cannot find page with id '" + resultPageId + "'");

        final Document setvaluesDocument = pageIdToSetvaluesDocument.get(resultPageId);
        final boolean doServerSideRedirect = _instancePassing != null
                && _instancePassing.equals(INSTANCE_PASSING_FORWARD);
        final boolean doRedirectExitPortal = _instancePassing != null
                && _instancePassing.equals(INSTANCE_PASSING_REDIRECT_PORTAL);

        // TODO: we should probably optimize all the redirect handling below with a dedicated processor
        {
            // Do redirect passing parameters from internalXUpdatedInstance without modifying URL
            final ASTOutput parametersOutput;
            if (isTransformedInstance) {
                parametersOutput = new ASTOutput(null, "parameters");
                // Pass parameters only if needed
                final QName instanceToParametersProcessor = XMLConstants.INSTANCE_TO_PARAMETERS_PROCESSOR_QNAME;
                when.addStatement(new ASTProcessorCall(instanceToParametersProcessor) {
                    {
                        addInput(new ASTInput("instance", new ASTHrefId(internalXUpdatedInstance)));
                        addInput(new ASTInput("filter",
                                (setvaluesDocument != null) ? setvaluesDocument : Dom4jUtils.NULL_DOCUMENT));
                        addOutput(new ASTOutput("data", parametersOutput));
                    }
                });
            } else {
                parametersOutput = null;
            }
            // Handle path info
            final ASTOutput forwardPathInfoOutput = new ASTOutput(null, "forward-path-info");
            when.addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                {
                    addInput(new ASTInput("data",
                            new NonLazyUserDataDocument(new NonLazyUserDataElement("path-info") {
                                {
                                    setText(forwardPathInfo);
                                }
                            })));
                    addOutput(new ASTOutput("data", forwardPathInfoOutput));
                }
            });
            // Handle server-side redirect and exit portal redirect
            final ASTOutput isServerSideRedirectOutput = new ASTOutput(null, "is-server-side-redirect");
            when.addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                {
                    addInput(new ASTInput("data",
                            new NonLazyUserDataDocument(new NonLazyUserDataElement("server-side") {
                                {
                                    setText(Boolean.toString(doServerSideRedirect));
                                }
                            })));
                    addOutput(new ASTOutput("data", isServerSideRedirectOutput));
                }
            });
            final ASTOutput isRedirectExitPortal = new ASTOutput(null, "is-redirect-exit-portal");
            when.addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                {
                    addInput(new ASTInput("data",
                            new NonLazyUserDataDocument(new NonLazyUserDataElement("exit-portal") {
                                {
                                    setText(Boolean.toString(doRedirectExitPortal));
                                }
                            })));
                    addOutput(new ASTOutput("data", isRedirectExitPortal));
                }
            });
            // Aggregate redirect-url config
            final ASTHref redirectURLData;
            if (setvaluesDocument != null && isTransformedInstance) {
                // Setvalues document - things are little more complicated, so we delegate
                final ASTOutput redirectDataOutput = new ASTOutput(null, "redirect-data");

                final ASTHrefAggregate redirectDataAggregate = new ASTHrefAggregate("redirect-url",
                        new ASTHrefId(forwardPathInfoOutput), new ASTHrefId(isServerSideRedirectOutput),
                        new ASTHrefId(isRedirectExitPortal));
                redirectDataAggregate.getHrefs().add(new ASTHrefId(parametersOutput));

                when.addStatement(new ASTProcessorCall(XMLConstants.UNSAFE_XSLT_PROCESSOR_QNAME) {
                    {
                        addInput(new ASTInput("config", new ASTHrefURL(REVERSE_SETVALUES_XSL)));
                        addInput(new ASTInput("data", redirectDataAggregate));
                        addInput(new ASTInput("instance", new ASTHrefId(internalXUpdatedInstance)));
                        addInput(new ASTInput("setvalues", setvaluesDocument));
                        addOutput(new ASTOutput("data", redirectDataOutput));
                    }
                });
                redirectURLData = new ASTHrefId(redirectDataOutput);
            } else {
                // No setvalues document, we can simply aggregate with XPL
                final ASTHrefAggregate redirectDataAggregate = new ASTHrefAggregate("redirect-url",
                        new ASTHrefId(forwardPathInfoOutput), new ASTHrefId(isServerSideRedirectOutput),
                        new ASTHrefId(isRedirectExitPortal));
                if (isTransformedInstance) // Pass parameters only if needed
                    redirectDataAggregate.getHrefs().add(new ASTHrefId(parametersOutput));
                redirectURLData = redirectDataAggregate;
            }
            // Execute the redirect
            when.addStatement(new ASTProcessorCall(XMLConstants.REDIRECT_PROCESSOR_QNAME) {
                {
                    addInput(new ASTInput("data", redirectURLData));// {{setDebug("redirect 2");}}
                    final String[] locationParams = new String[] { "result page id", resultPageId };
                    setLocationData(new ExtendedLocationData((LocationData) resultElement.getData(),
                            "page redirection", resultElement, locationParams));
                }
            });
        }
    }

    // Signal if we did a redirect
    when.addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
        {
            addInput(
                    new ASTInput("data", new NonLazyUserDataDocument(new NonLazyUserDataElement("is-redirect") {
                        {
                            setText(Boolean.toString(resultPageId != null));
                        }
                    })));
            addOutput(new ASTOutput("data", redirect));
        }
    });

    // Export XUpdated instance from this branch
    when.addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
        {
            addInput(new ASTInput("data", new ASTHrefId(internalXUpdatedInstance)));
            addOutput(new ASTOutput("data", xupdatedInstance));
        }
    });
}

From source file:org.orbeon.oxf.processor.EmailProcessor.java

License:Open Source License

public void start(PipelineContext pipelineContext) {
    try {//w w  w  . ja v  a  2 s .  c om
        final Document dataDocument = readInputAsDOM4J(pipelineContext, INPUT_DATA);
        final Element messageElement = dataDocument.getRootElement();

        // Get system id (will likely be null if document is generated dynamically)
        final LocationData locationData = (LocationData) messageElement.getData();
        final String dataInputSystemId = locationData.getSystemID();

        // Set SMTP host
        final Properties properties = new Properties();
        final String testSmtpHostProperty = getPropertySet().getString(EMAIL_TEST_SMTP_HOST);

        if (testSmtpHostProperty != null) {
            // Test SMTP Host from properties overrides the local configuration
            properties.setProperty("mail.smtp.host", testSmtpHostProperty);
        } else {
            // Try regular config parameter and property
            String host = messageElement.element("smtp-host").getTextTrim();
            if (host != null && !host.equals("")) {
                // Precedence goes to the local config parameter
                properties.setProperty("mail.smtp.host", host);
            } else {
                // Otherwise try to use a property
                host = getPropertySet().getString(EMAIL_SMTP_HOST);
                if (host == null)
                    host = getPropertySet().getString(EMAIL_HOST_DEPRECATED);
                if (host == null)
                    throw new OXFException("Could not find SMTP host in configuration or in properties");
                properties.setProperty("mail.smtp.host", host);

            }
        }

        // Create session
        final Session session;
        {
            // Get credentials
            final String usernameTrimmed;
            final String passwordTrimmed;
            {
                final Element credentials = messageElement.element("credentials");
                if (credentials != null) {
                    final Element usernameElement = credentials.element("username");
                    final Element passwordElement = credentials.element("password");
                    usernameTrimmed = (usernameElement != null) ? usernameElement.getStringValue().trim()
                            : null;
                    passwordTrimmed = (passwordElement != null) ? passwordElement.getStringValue().trim() : "";
                } else {
                    usernameTrimmed = null;
                    passwordTrimmed = null;
                }
            }

            // Check if credentials are supplied
            if (StringUtils.isNotEmpty(usernameTrimmed)) {
                // NOTE: A blank username doesn't trigger authentication

                if (logger.isInfoEnabled())
                    logger.info("Authentication");
                // Set the auth property to true
                properties.setProperty("mail.smtp.auth", "true");

                if (logger.isInfoEnabled())
                    logger.info("Username: " + usernameTrimmed);

                // Create an authenticator
                final Authenticator authenticator = new SMTPAuthenticator(usernameTrimmed, passwordTrimmed);

                // Create session with authenticator
                session = Session.getInstance(properties, authenticator);
            } else {
                if (logger.isInfoEnabled())
                    logger.info("No Authentication");
                session = Session.getInstance(properties);
            }
        }

        // Create message
        final Message message = new MimeMessage(session);

        // Set From
        message.addFrom(createAddresses(messageElement.element("from")));

        // Set To
        String testToProperty = getPropertySet().getString(EMAIL_TEST_TO);
        if (testToProperty == null)
            testToProperty = getPropertySet().getString(EMAIL_FORCE_TO_DEPRECATED);

        if (testToProperty != null) {
            // Test To from properties overrides local configuration
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(testToProperty));
        } else {
            // Regular list of To elements
            for (final Element toElement : Dom4jUtils.elements(messageElement, "to")) {
                final InternetAddress[] addresses = createAddresses(toElement);
                message.addRecipients(Message.RecipientType.TO, addresses);
            }
        }

        // Set Cc
        for (final Element ccElement : Dom4jUtils.elements(messageElement, "cc")) {
            final InternetAddress[] addresses = createAddresses(ccElement);
            message.addRecipients(Message.RecipientType.CC, addresses);
        }

        // Set Bcc
        for (final Element bccElement : Dom4jUtils.elements(messageElement, "bcc")) {
            final InternetAddress[] addresses = createAddresses(bccElement);
            message.addRecipients(Message.RecipientType.BCC, addresses);
        }

        // Set headers if any
        for (final Element headerElement : Dom4jUtils.elements(messageElement, "header")) {
            final String headerName = headerElement.element("name").getTextTrim();
            final String headerValue = headerElement.element("value").getTextTrim();

            // NOTE: Use encodeText() in case there are non-ASCII characters
            message.addHeader(headerName,
                    MimeUtility.encodeText(headerValue, DEFAULT_CHARACTER_ENCODING, null));
        }

        // Set the email subject
        // The JavaMail spec is badly written and is not clear about whether this needs to be done here. But it
        // seems to use the platform's default charset, which we don't want to deal with. So we preemptively encode.
        // The result is pure ASCII so that setSubject() will not attempt to re-encode it.
        message.setSubject(MimeUtility.encodeText(messageElement.element("subject").getStringValue(),
                DEFAULT_CHARACTER_ENCODING, null));

        // Handle body
        final Element textElement = messageElement.element("text");
        final Element bodyElement = messageElement.element("body");

        if (textElement != null) {
            // Old deprecated mechanism (simple text body)
            message.setText(textElement.getStringValue());
        } else if (bodyElement != null) {
            // New mechanism with body and parts
            handleBody(pipelineContext, dataInputSystemId, message, bodyElement);
        } else {
            throw new OXFException("Main text or body element not found");// TODO: location info
        }

        // Send message
        final Transport transport = session.getTransport("smtp");
        Transport.send(message);
        transport.close();
    } catch (Exception e) {
        throw new OXFException(e);
    }
}

From source file:org.orbeon.oxf.processor.EmailProcessor.java

License:Open Source License

private void handlePart(PipelineContext pipelineContext, String dataInputSystemId, Part parentPart,
        Element partOrBodyElement) throws Exception {
    final String name = partOrBodyElement.attributeValue("name");
    String contentTypeAttribute = partOrBodyElement.attributeValue("content-type");
    final String contentType = NetUtils.getContentTypeMediaType(contentTypeAttribute);
    final String charset;
    {/*www  . j  ava2  s .  com*/
        final String c = NetUtils.getContentTypeCharset(contentTypeAttribute);
        charset = (c != null) ? c : DEFAULT_CHARACTER_ENCODING;
    }
    final String contentTypeWithCharset = contentType + "; charset=" + charset;
    final String src = partOrBodyElement.attributeValue("src");

    // Either a String or a FileItem
    final Object content;
    if (src != null) {
        // Content of the part is not inline

        // Generate a FileItem from the source
        final SAXSource source = getSAXSource(EmailProcessor.this, pipelineContext, src, dataInputSystemId,
                contentType);
        content = handleStreamedPartContent(pipelineContext, source);
    } else {
        // Content of the part is inline

        // In the cases of text/html and XML, there must be exactly one root element
        final boolean needsRootElement = "text/html".equals(contentType);// || ProcessorUtils.isXMLContentType(contentType);
        if (needsRootElement && partOrBodyElement.elements().size() != 1)
            throw new ValidationException(
                    "The <body> or <part> element must contain exactly one element for text/html",
                    (LocationData) partOrBodyElement.getData());

        // Create Document and convert it into a String
        final Element rootElement = (Element) (needsRootElement ? partOrBodyElement.elements().get(0)
                : partOrBodyElement);
        final Document partDocument = new NonLazyUserDataDocument();
        partDocument.setRootElement((Element) rootElement.clone());
        content = handleInlinePartContent(partDocument, contentType);
    }

    if (!XMLUtils.isTextOrJSONContentType(contentType)) {
        // This is binary content (including application/xml)
        if (content instanceof FileItem) {
            final FileItem fileItem = (FileItem) content;
            parentPart.setDataHandler(new DataHandler(new DataSource() {
                public String getContentType() {
                    return contentType;
                }

                public InputStream getInputStream() throws IOException {
                    return fileItem.getInputStream();
                }

                public String getName() {
                    return name;
                }

                public OutputStream getOutputStream() throws IOException {
                    throw new IOException("Write operation not supported");
                }
            }));
        } else {
            byte[] data = NetUtils.base64StringToByteArray((String) content);
            parentPart.setDataHandler(new DataHandler(new SimpleBinaryDataSource(name, contentType, data)));
        }
    } else {
        // This is text content (including text/xml)
        if (content instanceof FileItem) {
            // The text content was encoded when written to the FileItem
            final FileItem fileItem = (FileItem) content;
            parentPart.setDataHandler(new DataHandler(new DataSource() {
                public String getContentType() {
                    // This always contains a charset
                    return contentTypeWithCharset;
                }

                public InputStream getInputStream() throws IOException {
                    // This is encoded with the appropriate charset (user-defined, or the default)
                    return fileItem.getInputStream();
                }

                public String getName() {
                    return name;
                }

                public OutputStream getOutputStream() throws IOException {
                    throw new IOException("Write operation not supported");
                }
            }));
        } else {
            parentPart.setDataHandler(
                    new DataHandler(new SimpleTextDataSource(name, contentTypeWithCharset, (String) content)));
        }
    }

    // Set content-disposition header
    String contentDisposition = partOrBodyElement.attributeValue("content-disposition");
    if (contentDisposition != null)
        parentPart.setDisposition(contentDisposition);

    // Set content-id header
    String contentId = partOrBodyElement.attributeValue("content-id");
    if (contentId != null)
        parentPart.setHeader("content-id", "<" + contentId + ">");
    //part.setContentID(contentId);
}

From source file:org.orbeon.oxf.processor.generator.RequestGenerator.java

License:Open Source License

private Document filterRequestDocument(Document requestDocument, Node config) {

    // We always want to keep the root element (even if nothing is selected)
    requestDocument.getRootElement().addAttribute(MARK_ATTRIBUTE, MARK_ATTRIBUTE_VALUE);

    for (Iterator i = XPathUtils.selectIterator(config, "/config/*"); i.hasNext();) {
        Element includeExcludeElement = (Element) i.next();
        LocationData locationData = (LocationData) includeExcludeElement.getData();
        String includeExcludeXPath = includeExcludeElement.getText();
        if (includeExcludeElement.getName().equals(INCLUDE_ELEMENT)) {
            for (Iterator j = XPathUtils.selectIterator(requestDocument, includeExcludeXPath); j.hasNext();) {
                Element e = referencedElement((Node) j.next(), locationData, includeExcludeXPath);
                markAncestors(e);//from  w ww  .ja  v a 2s  .  c o  m
                markDescendants(e);
            }
        } else if (includeExcludeElement.getName().equals(EXCLUDE_ELEMENT)) {
            for (Iterator j = XPathUtils.selectIterator(requestDocument, includeExcludeXPath); j.hasNext();) {
                Element e = referencedElement((Node) j.next(), locationData, includeExcludeXPath);
                e.detach();
            }
        }
    }

    // Prune unnecessary nodes
    prune(requestDocument.getRootElement());

    return requestDocument;
}

From source file:org.orbeon.oxf.processor.JavaProcessor.java

License:Open Source License

private Processor getProcessor(PipelineContext context) {
    try {//from   w  w w. jav  a 2s  . c  o m
        // Read config input into a String, cache if possible
        ProcessorInput input = getInputByName(INPUT_CONFIG);
        final Config config = readCacheInputAsObject(context, input, new CacheableInputReader<Config>() {
            public Config read(PipelineContext context, ProcessorInput input) {
                Document configDocument = readInputAsDOM4J(context, INPUT_CONFIG);
                Element configElement = configDocument.getRootElement();
                Config config = new Config();
                config.clazz = configElement.attributeValue("class");

                // Get source path
                String sourcePathAttributeValue = configElement.attributeValue("sourcepath");
                if (sourcePathAttributeValue == null)
                    sourcePathAttributeValue = ".";
                File sourcePath = getFileFromURL(sourcePathAttributeValue,
                        JavaProcessor.this.getLocationData());
                if (!sourcePath.isDirectory())
                    throw new ValidationException(
                            "Invalid sourcepath attribute: cannot find directory for URL: "
                                    + sourcePathAttributeValue,
                            (LocationData) configElement.getData());
                try {
                    config.sourcepath = sourcePath.getCanonicalPath();
                } catch (IOException e) {
                    throw new ValidationException(
                            "Invalid sourcepath attribute: cannot find directory for URL: "
                                    + sourcePathAttributeValue,
                            (LocationData) configElement.getData());
                }

                return config;
            }
        });

        // Check if need to compile
        String sourceFile = config.sourcepath + "/" + config.clazz.replace('.', '/') + ".java";
        String destinationDirectory = SystemUtils.getTemporaryDirectory().getAbsolutePath();
        String destinationFile = destinationDirectory + "/" + config.clazz.replace('.', '/') + ".class";

        // Check if file is up-to-date
        long currentTimeMillis = System.currentTimeMillis();
        Long sourceLastModified;
        Long destinationLastModified;
        synchronized (lastModifiedMap) {
            sourceLastModified = (Long) lastModifiedMap.get(currentTimeMillis, sourceFile);
            if (sourceLastModified == null) {
                sourceLastModified = new Long(new File(sourceFile).lastModified());
                lastModifiedMap.put(currentTimeMillis, sourceFile, sourceLastModified);
            }
            destinationLastModified = (Long) lastModifiedMap.get(currentTimeMillis, destinationFile);
            if (destinationLastModified == null) {
                destinationLastModified = new Long(new File(destinationFile).lastModified());
                lastModifiedMap.put(currentTimeMillis, destinationFile, destinationLastModified);
            }
        }
        boolean fileUpToDate = sourceLastModified.longValue() < destinationLastModified.longValue();

        // Compile
        if (!fileUpToDate) {
            StringBuilderWriter javacOutput = new StringBuilderWriter();

            final ArrayList<String> argLst = new ArrayList<String>();
            final String[] cmdLine;
            {
                argLst.add("-g");
                final String cp = buildClassPath(context);
                if (cp != null) {
                    argLst.add("-classpath");
                    argLst.add(cp);
                }

                if (config.sourcepath != null && config.sourcepath.length() > 0) {
                    argLst.add("-sourcepath");
                    argLst.add(config.sourcepath);
                }
                argLst.add("-d");
                final File tmp = SystemUtils.getTemporaryDirectory();
                final String tmpPth = tmp.getAbsolutePath();
                argLst.add(tmpPth);
                final String fnam = config.sourcepath + "/" + config.clazz.replace('.', '/') + ".java";
                argLst.add(fnam);

                cmdLine = new String[argLst.size()];
                argLst.toArray(cmdLine);
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Compiling class '" + config.clazz + "'");
                logger.debug("javac " + argLst.toString());
            }
            Throwable thrown = null;
            int exitCode = 1;
            try {
                // Get compiler class, either user-specified or default to Sun compiler
                String compilerMain = getPropertySet().getString(COMPILER_CLASS_PROPERTY,
                        DEFAULT_COMPILER_MAIN);

                ClassLoader classLoader;
                {
                    URI compilerJarURI = getPropertySet().getURI(COMPILER_JAR_PROPERTY);
                    if (compilerJarURI != null) {
                        // 1: Always honor user-specified compiler JAR if present
                        // Use special class loader pointing to this URL
                        classLoader = new URLClassLoader(new URL[] { compilerJarURI.toURL() },
                                JavaProcessor.class.getClassLoader());
                        if (logger.isDebugEnabled())
                            logger.debug("Java processor using user-specified compiler JAR: "
                                    + compilerJarURI.toString());
                    } else {
                        // 2: Try to use the class loader that loaded this class
                        classLoader = JavaProcessor.class.getClassLoader();
                        try {
                            Class.forName(compilerMain, true, classLoader);
                            logger.debug("Java processor using current class loader");
                        } catch (ClassNotFoundException e) {
                            // Class not found
                            // 3: Try to get to Sun tools.jar
                            String javaHome = System.getProperty("java.home");
                            if (javaHome != null) {
                                File javaHomeFile = new File(javaHome);
                                if (javaHomeFile.getName().equals("jre")) {
                                    File toolsFile = new File(javaHomeFile.getParentFile(),
                                            "lib" + File.separator + "tools.jar");
                                    if (toolsFile.exists()) {
                                        // JAR file exists, will use it to load compiler class
                                        classLoader = new URLClassLoader(
                                                new URL[] { toolsFile.toURI().toURL() },
                                                JavaProcessor.class.getClassLoader());
                                        if (logger.isDebugEnabled())
                                            logger.debug("Java processor using default tools.jar under "
                                                    + toolsFile.toString());
                                    }
                                }
                            }
                        }
                    }
                }

                // Load compiler class using class loader defined above
                Class compilerClass = Class.forName(compilerMain, true, classLoader);

                // Get method and run compiler
                Method compileMethod = compilerClass.getMethod("compile",
                        new Class[] { String[].class, PrintWriter.class });
                Object result = compileMethod.invoke(null, cmdLine, new PrintWriter(javacOutput));
                exitCode = ((Integer) result).intValue();

            } catch (final Throwable t) {
                thrown = t;
            }
            if (exitCode != 0) {
                String javacOutputString = "\n" + javacOutput.toString();
                javacOutputString = StringUtils.replace(javacOutputString, "\n", "\n    ");
                throw new OXFException("Error compiling '" + argLst.toString() + "'" + javacOutputString,
                        thrown);
            }
        }

        // Try to get sourcepath info
        InternalCacheKey sourcepathKey = new InternalCacheKey(JavaProcessor.this, "javaFile",
                config.sourcepath);
        Object sourcepathValidity = new Long(0);
        Sourcepath sourcepath = (Sourcepath) ObjectCache.instance().findValid(sourcepathKey,
                sourcepathValidity);

        // Create classloader
        if (sourcepath == null
                || (sourcepath.callNameToProcessorClass.containsKey(config.clazz) && !fileUpToDate)) {
            if (logger.isDebugEnabled())
                logger.debug("Creating classloader for sourcepath '" + config.sourcepath + "'");
            sourcepath = new Sourcepath();
            sourcepath.classLoader = new URLClassLoader(
                    new URL[] { SystemUtils.getTemporaryDirectory().toURI().toURL(),
                            new File(config.sourcepath).toURI().toURL() },
                    this.getClass().getClassLoader());
            ObjectCache.instance().add(sourcepathKey, sourcepathValidity, sourcepath);
        }

        // Get processor class
        Class<Processor> processorClass = sourcepath.callNameToProcessorClass.get(config.clazz);
        if (processorClass == null) {
            processorClass = (Class<Processor>) sourcepath.classLoader.loadClass(config.clazz);
            sourcepath.callNameToProcessorClass.put(config.clazz, processorClass);
        }

        // Create processor from class
        Thread.currentThread().setContextClassLoader(processorClass.getClassLoader());
        return processorClass.newInstance();

    } catch (final IOException e) {
        throw new OXFException(e);
    } catch (final IllegalAccessException e) {
        throw new OXFException(e);
    } catch (final InstantiationException e) {
        throw new OXFException(e);
    } catch (final ClassNotFoundException e) {
        throw new OXFException(e);
    }
}

From source file:org.orbeon.oxf.processor.PageFlowControllerBuilder.java

License:Open Source License

public static void handleEpilogue(final String controllerContext, List<ASTStatement> statements,
        final String epilogueURL, final Element epilogueElement, final ASTOutput epilogueData,
        final ASTOutput epilogueModelData, final ASTOutput epilogueInstance) {
    if (epilogueURL == null) {
        // Run HTML serializer if no epilogue is specified
        statements.add(new ASTChoose(new ASTHrefId(epilogueData)) {
            {//w ww .j ava2 s  . com
                addWhen(new ASTWhen("not(/*/@xsi:nil = 'true')") {
                    {
                        setNamespaces(NAMESPACES_WITH_XSI_AND_XSLT);
                        // The epilogue did not do the serialization
                        addStatement(new ASTProcessorCall(XMLConstants.HTML_SERIALIZER_PROCESSOR_QNAME) {
                            {
                                Document config = new NonLazyUserDataDocument(
                                        new NonLazyUserDataElement("config"));
                                Element rootElement = config.getRootElement();
                                rootElement.addElement("version").addText("5.0");
                                rootElement.addElement("encoding").addText("utf-8");
                                addInput(new ASTInput("config", config));
                                addInput(new ASTInput("data", new ASTHrefId(epilogueData)));
                                //setLocationData(TODO);
                            }
                        });
                    }
                });
                addWhen(new ASTWhen());
            }
        });
    } else {
        // Send result through epilogue
        statements.add(new ASTProcessorCall(XMLConstants.PIPELINE_PROCESSOR_QNAME) {
            {
                final String url;
                try {
                    url = URLFactory.createURL(controllerContext, epilogueURL).toExternalForm();
                } catch (MalformedURLException e) {
                    throw new OXFException(e);
                }
                addInput(new ASTInput("config", new ASTHrefURL(url)));
                addInput(new ASTInput("data", new ASTHrefId(epilogueData)));
                addInput(new ASTInput("model-data", new ASTHrefId(epilogueModelData)));
                addInput(new ASTInput("instance", new ASTHrefId(epilogueInstance)));
                final String[] locationParams = new String[] { "pipeline", epilogueURL };
                setLocationData(new ExtendedLocationData((LocationData) epilogueElement.getData(),
                        "executing epilogue", epilogueElement, locationParams, true));
            }
        });
    }
}

From source file:org.orbeon.oxf.processor.PageFlowControllerBuilder.java

License:Open Source License

/**
 * Handle <page>/* w  w w .  ja va 2s.c om*/
 */
public static void handlePage(final StepProcessorContext stepProcessorContext, final String urlBase,
        List<ASTStatement> statementsList, final Element pageElement, final String matcherOutputOrParamId,
        final ASTOutput viewData, final ASTOutput epilogueModelData, final ASTOutput viewInstance,
        final Map<String, String> pageIdToPathInfo, final Map<String, Document> pageIdToSetvaluesDocument,
        final String instancePassing) {

    // Get page attributes
    final String modelAttribute = pageElement.attributeValue("model");
    final String viewAttribute = pageElement.attributeValue("view");
    final String defaultSubmissionAttribute = pageElement.attributeValue("default-submission");

    // Get setvalues document
    final Document setvaluesDocument = getSetValuesDocument(pageElement);

    // Get actions
    final List actionElements = pageElement.elements("action");

    // Handle initial instance
    final ASTOutput defaultSubmission = new ASTOutput("data", "default-submission");
    if (defaultSubmissionAttribute != null) {
        statementsList.add(new ASTProcessorCall(XMLConstants.URL_GENERATOR_PROCESSOR_QNAME) {
            {
                final String url;
                try {
                    url = URLFactory.createURL(urlBase, defaultSubmissionAttribute).toExternalForm();
                } catch (MalformedURLException e) {
                    throw new OXFException(e);
                }
                final Document configDocument = new NonLazyUserDataDocument(
                        new NonLazyUserDataElement("config"));
                configDocument.getRootElement().addText(url);

                addInput(new ASTInput("config", configDocument));
                addOutput(defaultSubmission);
            }
        });
    }

    // XForms Input
    final ASTOutput isRedirect = new ASTOutput(null, "is-redirect");

    // Always hook up XML submission
    final ASTOutput xformedInstance = new ASTOutput("instance", "xformed-instance");
    {
        final LocationData locDat = Dom4jUtils.getLocationData();
        xformedInstance.setLocationData(locDat);
    }

    // Use XML Submission pipeline
    statementsList.add(new ASTProcessorCall(XMLConstants.PIPELINE_PROCESSOR_QNAME) {
        {
            addInput(new ASTInput("config", new ASTHrefURL(XFORMS_XML_SUBMISSION_XPL)));
            if (setvaluesDocument != null) {
                addInput(new ASTInput("setvalues", setvaluesDocument));
                addInput(new ASTInput("matcher-result", new ASTHrefId(matcherOutputOrParamId)));
            } else {
                addInput(new ASTInput("setvalues", Dom4jUtils.NULL_DOCUMENT));
                addInput(new ASTInput("matcher-result", Dom4jUtils.NULL_DOCUMENT));
            }
            if (defaultSubmissionAttribute != null) {
                addInput(new ASTInput("default-submission", new ASTHrefId(defaultSubmission)));
            } else {
                addInput(new ASTInput("default-submission", Dom4jUtils.NULL_DOCUMENT));
            }
            addOutput(xformedInstance);
        }
    });

    // Make sure the xformed-instance id is used for p:choose
    statementsList.add(new ASTProcessorCall(XMLConstants.NULL_PROCESSOR_QNAME) {
        {
            addInput(new ASTInput("data", new ASTHrefId(xformedInstance)));
        }
    });

    // Execute actions
    final ASTOutput xupdatedInstance = new ASTOutput(null, "xupdated-instance");
    final ASTOutput actionData = new ASTOutput(null, "action-data");
    final int[] actionNumber = new int[] { 0 };
    final boolean[] foundActionWithoutWhen = new boolean[] { false };
    final ASTChoose actionsChoose = new ASTChoose(new ASTHrefId(xformedInstance)) {
        {

            // Always add a branch to test on whether the XML submission asked to bypass actions, model, view, and epilogue
            // Use of this <bypass> document is arguably a HACK 
            addWhen(new ASTWhen() {
                {

                    setTest("/bypass[@xsi:nil = 'true']");
                    setNamespaces(NAMESPACES_WITH_XSI_AND_XSLT);

                    addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                        {
                            addInput(new ASTInput("data", Dom4jUtils.NULL_DOCUMENT));
                            addOutput(new ASTOutput("data", xupdatedInstance));
                        }
                    });
                    addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                        {
                            final Document config = new NonLazyUserDataDocument(
                                    new NonLazyUserDataElement("is-redirect"));
                            config.getRootElement().addText("true");
                            addInput(new ASTInput("data", config));
                            addOutput(new ASTOutput("data", isRedirect));
                        }
                    });
                    addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                        {
                            addInput(new ASTInput("data", Dom4jUtils.NULL_DOCUMENT));
                            addOutput(new ASTOutput("data", actionData));
                        }
                    });
                }
            });

            for (Object actionElement1 : actionElements) {

                // Get info about action
                actionNumber[0]++;
                final Element actionElement = (Element) actionElement1;
                final String whenAttribute;
                {
                    // NOTE: Prior to 2012-06-27, the XSD schema would put a default value of true()
                    final String tempWhen = actionElement.attributeValue("when");
                    if (tempWhen == null)
                        whenAttribute = "true()";
                    else
                        whenAttribute = tempWhen;
                }
                ;
                final String actionAttribute = actionElement.attributeValue("action");

                // Execute action
                addWhen(new ASTWhen() {
                    {

                        // Add condition, remember that we found an <action> without a when
                        if (whenAttribute != null) {
                            if (foundActionWithoutWhen[0])
                                throw new ValidationException("Unreachable <action>",
                                        (LocationData) actionElement.getData());
                            setTest(whenAttribute);
                            setNamespaces(new NamespaceMapping(
                                    Dom4jUtils.getNamespaceContextNoDefault(actionElement)));
                            setLocationData((LocationData) actionElement.getData());
                        } else {
                            foundActionWithoutWhen[0] = true;
                        }

                        final boolean resultTestsOnActionData =
                                // Must have an action, in the first place
                                actionAttribute != null &&
                        // More than one <result>: so at least the first one must have a "when"
                        actionElement.elements("result").size() > 1;

                        final ASTOutput internalActionData = actionAttribute == null ? null
                                : new ASTOutput(null, "internal-action-data-" + actionNumber[0]);
                        if (actionAttribute != null) {
                            // TODO: handle passing and modifications of action data in model, and view, and pass to instance
                            addStatement(new StepProcessorCall(stepProcessorContext, urlBase, actionAttribute,
                                    "action") {
                                {
                                    addInput(new ASTInput("data", Dom4jUtils.NULL_DOCUMENT));
                                    addInput(new ASTInput("instance", new ASTHrefId(xformedInstance)));
                                    addInput(new ASTInput("xforms-model", Dom4jUtils.NULL_DOCUMENT));
                                    addInput(new ASTInput("matcher", new ASTHrefId(matcherOutputOrParamId)));
                                    final ASTOutput dataOutput = new ASTOutput("data", internalActionData);
                                    final String[] locationParams = new String[] { "pipeline", actionAttribute,
                                            "page id", pageElement.attributeValue("id"), "when",
                                            whenAttribute };
                                    dataOutput.setLocationData(new ExtendedLocationData(
                                            (LocationData) actionElement.getData(),
                                            "reading action data output", pageElement, locationParams, true));
                                    addOutput(dataOutput);
                                    setLocationData(
                                            new ExtendedLocationData((LocationData) actionElement.getData(),
                                                    "executing action", pageElement, locationParams, true));
                                }
                            });

                            // Force execution of action if no <result> is reading it
                            if (!resultTestsOnActionData) {
                                addStatement(
                                        new ASTProcessorCall(XMLConstants.NULL_SERIALIZER_PROCESSOR_QNAME) {
                                            {
                                                addInput(new ASTInput("data",
                                                        new ASTHrefId(internalActionData)));
                                            }
                                        });
                            }

                            // Export internal-action-data as action-data
                            addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                                {
                                    addInput(new ASTInput("data", new ASTHrefId(internalActionData)));
                                    addOutput(new ASTOutput("data", actionData));
                                }
                            });
                        } else {
                            addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                                {
                                    addInput(new ASTInput("data", Dom4jUtils.NULL_DOCUMENT));
                                    addOutput(new ASTOutput("data", actionData));
                                }
                            });
                        }

                        if (actionElement.elements("result").size() > 0 && internalActionData != null) {
                            // At least one result testing on action

                            // Test based on action
                            addStatement(new ASTChoose(new ASTHrefId(internalActionData)) {
                                {
                                    for (Object o : actionElement.elements("result")) {
                                        final Element resultElement = (Element) o;
                                        final String resultWhenAttribute;
                                        {
                                            // NOTE: Prior to 2012-06-27, the XSD schema would put a default value of true()
                                            final String tempWhen = resultElement.attributeValue("when");
                                            if (tempWhen == null)
                                                resultWhenAttribute = "true()";
                                            else
                                                resultWhenAttribute = tempWhen;
                                        }
                                        ;

                                        // Execute result
                                        addWhen(new ASTWhen() {
                                            {
                                                if (resultWhenAttribute != null) {
                                                    setTest(resultWhenAttribute);
                                                    setNamespaces(new NamespaceMapping(Dom4jUtils
                                                            .getNamespaceContextNoDefault(resultElement)));
                                                    final String[] locationParams = new String[] { "page id",
                                                            pageElement.attributeValue("id"), "when",
                                                            resultWhenAttribute };
                                                    setLocationData(new ExtendedLocationData(
                                                            (LocationData) resultElement.getData(),
                                                            "executing result", resultElement, locationParams,
                                                            true));
                                                }
                                                executeResult(this, pageIdToPathInfo, pageIdToSetvaluesDocument,
                                                        xformedInstance, resultElement, internalActionData,
                                                        isRedirect, xupdatedInstance, instancePassing);
                                            }
                                        });
                                    }

                                    // Continue when all results fail
                                    addWhen(new ASTWhen() {
                                        {
                                            addStatement(new ASTProcessorCall(
                                                    XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                                                {
                                                    addInput(new ASTInput("data", new NonLazyUserDataDocument(
                                                            new NonLazyUserDataElement("is-redirect") {
                                                                {
                                                                    setText("false");
                                                                }
                                                            })));
                                                    addOutput(new ASTOutput("data", isRedirect));
                                                }
                                            });
                                            addStatement(new ASTProcessorCall(
                                                    XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                                                {
                                                    addInput(new ASTInput("data",
                                                            new ASTHrefId(xformedInstance)));
                                                    addOutput(new ASTOutput("data", xupdatedInstance));
                                                }
                                            });
                                        }
                                    });
                                }
                            });

                        } else {
                            // No result or result not depending on action
                            final Element resultElement = actionElement.element("result");
                            executeResult(this, pageIdToPathInfo, pageIdToSetvaluesDocument, xformedInstance,
                                    resultElement, internalActionData, isRedirect, xupdatedInstance,
                                    instancePassing);
                        }
                    }
                });
            }

            if (!foundActionWithoutWhen[0]) {
                // Defaul branch for when all actions fail
                addWhen(new ASTWhen() {
                    {
                        addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                            {
                                addInput(new ASTInput("data", new ASTHrefId(xformedInstance)));
                                addOutput(new ASTOutput("data", xupdatedInstance));
                            }
                        });
                        addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                            {
                                final Document config = new NonLazyUserDataDocument(
                                        new NonLazyUserDataElement("is-redirect"));
                                config.getRootElement().addText("false");
                                addInput(new ASTInput("data", config));
                                addOutput(new ASTOutput("data", isRedirect));
                            }
                        });
                        addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                            {
                                addInput(new ASTInput("data", Dom4jUtils.NULL_DOCUMENT));
                                addOutput(new ASTOutput("data", actionData));
                            }
                        });
                    }
                });
            }
        }
    };

    // Add choose statement
    statementsList.add(actionsChoose);

    // Only continue if there was no redirect
    statementsList.add(new ASTChoose(new ASTHrefId(isRedirect)) {
        {
            addWhen(new ASTWhen("/is-redirect = 'false'") {
                {

                    // Handle page model
                    final ASTOutput modelData = new ASTOutput(null, "model-data");
                    final ASTOutput modelInstance = new ASTOutput(null, "model-instance");
                    if (modelAttribute != null) {
                        // There is a model
                        addStatement(
                                new StepProcessorCall(stepProcessorContext, urlBase, modelAttribute, "model") {
                                    {
                                        addInput(new ASTInput("data", new ASTHrefId(actionData)));
                                        addInput(new ASTInput("instance", new ASTHrefId(xupdatedInstance)));
                                        addInput(new ASTInput("xforms-model", Dom4jUtils.NULL_DOCUMENT));
                                        addInput(
                                                new ASTInput("matcher", new ASTHrefId(matcherOutputOrParamId)));
                                        final String[] locationParams = new String[] { "page id",
                                                pageElement.attributeValue("id"), "model", modelAttribute };
                                        {
                                            final ASTOutput dataOutput = new ASTOutput("data", modelData);
                                            dataOutput.setLocationData(new ExtendedLocationData(
                                                    (LocationData) pageElement.getData(),
                                                    "reading page model data output", pageElement,
                                                    locationParams, true));
                                            addOutput(dataOutput);
                                        }
                                        {
                                            final ASTOutput instanceOutput = new ASTOutput("instance",
                                                    modelInstance);
                                            addOutput(instanceOutput);
                                            instanceOutput.setLocationData(new ExtendedLocationData(
                                                    (LocationData) pageElement.getData(),
                                                    "reading page model instance output", pageElement,
                                                    locationParams, true));
                                        }
                                        setLocationData(new ExtendedLocationData(
                                                (LocationData) pageElement.getData(), "executing page model",
                                                pageElement, locationParams, true));
                                    }
                                });
                    } else if (viewAttribute != null) {
                        // There is no model but there is a view
                        addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                            {
                                addInput(new ASTInput("data", new ASTHrefId(actionData)));
                                addOutput(new ASTOutput("data", modelData));
                            }
                        });
                        addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                            {
                                addInput(new ASTInput("data", new ASTHrefId(xupdatedInstance)));
                                addOutput(new ASTOutput("data", modelInstance));
                            }
                        });
                    }

                    // Handle page view
                    if (viewAttribute != null) {
                        // There is a view
                        addStatement(
                                new StepProcessorCall(stepProcessorContext, urlBase, viewAttribute, "view") {
                                    {
                                        addInput(new ASTInput("data", new ASTHrefId(modelData)));
                                        addInput(new ASTInput("instance", new ASTHrefId(modelInstance)));
                                        addInput(new ASTInput("xforms-model", Dom4jUtils.NULL_DOCUMENT));
                                        addInput(
                                                new ASTInput("matcher", new ASTHrefId(matcherOutputOrParamId)));
                                        final String[] locationParams = new String[] { "page id",
                                                pageElement.attributeValue("id"), "view", viewAttribute };
                                        {
                                            final ASTOutput dataOutput = new ASTOutput("data", viewData);
                                            dataOutput.setLocationData(new ExtendedLocationData(
                                                    (LocationData) pageElement.getData(),
                                                    "reading page view data output", pageElement,
                                                    locationParams, true));
                                            addOutput(dataOutput);
                                        }
                                        {
                                            final ASTOutput instanceOutput = new ASTOutput("instance",
                                                    viewInstance);
                                            instanceOutput.setLocationData(new ExtendedLocationData(
                                                    (LocationData) pageElement.getData(),
                                                    "reading page view instance output", pageElement,
                                                    locationParams, true));
                                            addOutput(instanceOutput);
                                        }
                                        setLocationData(new ExtendedLocationData(
                                                (LocationData) pageElement.getData(), "executing page view",
                                                pageElement, locationParams, true));
                                    }
                                });
                    } else {
                        // There is no view, send nothing to epilogue
                        addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                            {
                                addInput(new ASTInput("data", Dom4jUtils.NULL_DOCUMENT));
                                addOutput(new ASTOutput("data", viewData));
                            }
                        });
                        addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                            {
                                addInput(new ASTInput("data", Dom4jUtils.NULL_DOCUMENT));
                                addOutput(new ASTOutput("data", viewInstance));
                            }
                        });
                    }

                    if (modelAttribute != null && viewAttribute == null) {
                        // With XForms NG we want lazy evaluation of the instance, so we should not force a
                        // read on the instance. We just connect the output.
                        addStatement(new ASTProcessorCall(XMLConstants.NULL_PROCESSOR_QNAME) {
                            {
                                addInput(new ASTInput("data", new ASTHrefId(modelInstance)));
                            }
                        });
                    }

                    if (modelAttribute == null && viewAttribute == null) {
                        // Send out epilogue model data as a null document
                        addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                            {
                                addInput(new ASTInput("data", Dom4jUtils.NULL_DOCUMENT));
                                addOutput(new ASTOutput("data", epilogueModelData));
                            }
                        });
                    } else {
                        // Send out epilogue model data as produced by the model or used by the view
                        addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                            {
                                addInput(new ASTInput("data", new ASTHrefId(modelData)));
                                addOutput(new ASTOutput("data", epilogueModelData));
                            }
                        });
                    }

                }
            });
            addWhen(new ASTWhen() {
                {
                    // There is a redirection due to the action

                    // With XForms NG we want lazy evaluation of the instance, so we should not force a
                    // read on the instance. We just connect the output.
                    addStatement(new ASTProcessorCall(XMLConstants.NULL_PROCESSOR_QNAME) {
                        {
                            addInput(new ASTInput("data", new ASTHrefId(xupdatedInstance)));
                        }
                    });
                    // Just connect the output
                    addStatement(new ASTProcessorCall(XMLConstants.NULL_PROCESSOR_QNAME) {
                        {
                            addInput(new ASTInput("data", new ASTHrefId(actionData)));
                        }
                    });
                    addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                        {
                            addInput(new ASTInput("data", Dom4jUtils.NULL_DOCUMENT));
                            addOutput(new ASTOutput("data", viewData));
                        }
                    });
                    addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                        {
                            addInput(new ASTInput("data", Dom4jUtils.NULL_DOCUMENT));
                            addOutput(new ASTOutput("data", epilogueModelData));
                        }
                    });
                    addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                        {
                            addInput(new ASTInput("data", Dom4jUtils.NULL_DOCUMENT));
                            addOutput(new ASTOutput("data", viewInstance));
                        }
                    });
                }
            });
        }
    });
}

From source file:org.orbeon.oxf.processor.PageFlowControllerBuilder.java

License:Open Source License

private static void executeResult(ASTWhen when, final Map<String, String> pageIdToPathInfo,
        final Map<String, Document> pageIdToSetvaluesDocument, final ASTOutput instanceToUpdate,
        final Element resultElement, final ASTOutput actionData, final ASTOutput redirect,
        final ASTOutput xupdatedInstance, String instancePassing) {

    // Instance to update: either current, or instance from other page
    final String resultPageId = resultElement == null ? null : resultElement.attributeValue("page");
    Attribute instancePassingAttribute = resultElement == null ? null
            : resultElement.attribute("instance-passing");
    final String _instancePassing = instancePassingAttribute == null ? instancePassing
            : instancePassingAttribute.getValue();

    // Create resulting instance
    final ASTOutput internalXUpdatedInstance;
    final boolean isTransformedInstance;
    if (resultElement != null && resultElement.attribute("transform") != null
            && !resultElement.elements().isEmpty()) {
        // Generic transform mechanism
        internalXUpdatedInstance = new ASTOutput("data", "internal-xupdated-instance");
        isTransformedInstance = true;//from  w  ww  .  j a v a2s  .com

        final Document transformConfig = Dom4jUtils
                .createDocumentCopyParentNamespaces((Element) resultElement.elements().get(0));
        final QName transformQName = Dom4jUtils.extractAttributeValueQName(resultElement, "transform");

        // Run transform
        final String resultTraceAttribute = resultElement.attributeValue("trace");
        when.addStatement(new ASTProcessorCall(transformQName) {
            {
                addInput(new ASTInput("config", transformConfig));// transform
                addInput(new ASTInput("instance", new ASTHrefId(instanceToUpdate)));// source-instance
                addInput(new ASTInput("data", new ASTHrefId(instanceToUpdate)));// destination-instance
                //addInput(new ASTInput("request-instance", new ASTHrefId(requestInstance)));// params-instance TODO
                if (actionData != null)
                    addInput(new ASTInput("action", new ASTHrefId(actionData)));// action
                else
                    addInput(new ASTInput("action", Dom4jUtils.NULL_DOCUMENT));// action
                addOutput(new ASTOutput("data", internalXUpdatedInstance) {
                    {
                        setDebug(resultTraceAttribute);
                    }
                });// updated-instance
            }
        });
    } else {
        internalXUpdatedInstance = instanceToUpdate;
        isTransformedInstance = false;
    }

    // Do redirect if we are going to a new page (NOTE: even if the new page has the same id as the current page)
    if (resultPageId != null) {
        final String forwardPathInfo = pageIdToPathInfo.get(resultPageId);
        if (forwardPathInfo == null)
            throw new OXFException("Cannot find page with id '" + resultPageId + "'");

        final Document setvaluesDocument = pageIdToSetvaluesDocument.get(resultPageId);
        final boolean doServerSideRedirect = _instancePassing != null
                && _instancePassing.equals(INSTANCE_PASSING_FORWARD);
        final boolean doRedirectExitPortal = _instancePassing != null
                && _instancePassing.equals(INSTANCE_PASSING_REDIRECT_PORTAL);

        // TODO: we should probably optimize all the redirect handling below with a dedicated processor
        {
            // Do redirect passing parameters from internalXUpdatedInstance without modifying URL
            final ASTOutput parametersOutput;
            if (isTransformedInstance) {
                parametersOutput = new ASTOutput(null, "parameters");
                // Pass parameters only if needed
                final QName instanceToParametersProcessor = XMLConstants.INSTANCE_TO_PARAMETERS_PROCESSOR_QNAME;
                when.addStatement(new ASTProcessorCall(instanceToParametersProcessor) {
                    {
                        addInput(new ASTInput("instance", new ASTHrefId(internalXUpdatedInstance)));
                        addInput(new ASTInput("filter",
                                (setvaluesDocument != null) ? setvaluesDocument : Dom4jUtils.NULL_DOCUMENT));
                        addOutput(new ASTOutput("data", parametersOutput));
                    }
                });
            } else {
                parametersOutput = null;
            }
            // Handle path info
            final ASTOutput forwardPathInfoOutput = new ASTOutput(null, "forward-path-info");
            when.addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                {
                    addInput(new ASTInput("data",
                            new NonLazyUserDataDocument(new NonLazyUserDataElement("path-info") {
                                {
                                    setText(forwardPathInfo);
                                }
                            })));
                    addOutput(new ASTOutput("data", forwardPathInfoOutput));
                }
            });
            // Handle server-side redirect and exit portal redirect
            final ASTOutput isServerSideRedirectOutput = new ASTOutput(null, "is-server-side-redirect");
            when.addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                {
                    addInput(new ASTInput("data",
                            new NonLazyUserDataDocument(new NonLazyUserDataElement("server-side") {
                                {
                                    setText(Boolean.toString(doServerSideRedirect));
                                }
                            })));
                    addOutput(new ASTOutput("data", isServerSideRedirectOutput));
                }
            });
            final ASTOutput isRedirectExitPortal = new ASTOutput(null, "is-redirect-exit-portal");
            when.addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
                {
                    addInput(new ASTInput("data",
                            new NonLazyUserDataDocument(new NonLazyUserDataElement("exit-portal") {
                                {
                                    setText(Boolean.toString(doRedirectExitPortal));
                                }
                            })));
                    addOutput(new ASTOutput("data", isRedirectExitPortal));
                }
            });
            // Aggregate redirect-url config
            final ASTHref redirectURLData;
            if (setvaluesDocument != null && isTransformedInstance) {
                // Setvalues document - things are little more complicated, so we delegate
                final ASTOutput redirectDataOutput = new ASTOutput(null, "redirect-data");

                final ASTHrefAggregate redirectDataAggregate = new ASTHrefAggregate("redirect-url",
                        new ASTHrefId(forwardPathInfoOutput), new ASTHrefId(isServerSideRedirectOutput),
                        new ASTHrefId(isRedirectExitPortal));
                redirectDataAggregate.getHrefs().add(new ASTHrefId(parametersOutput));

                when.addStatement(new ASTProcessorCall(XMLConstants.UNSAFE_XSLT_PROCESSOR_QNAME) {
                    {
                        addInput(new ASTInput("config", new ASTHrefURL(REVERSE_SETVALUES_XSL)));
                        addInput(new ASTInput("data", redirectDataAggregate));
                        addInput(new ASTInput("instance", new ASTHrefId(internalXUpdatedInstance)));
                        addInput(new ASTInput("setvalues", setvaluesDocument));
                        addOutput(new ASTOutput("data", redirectDataOutput));
                    }
                });
                redirectURLData = new ASTHrefId(redirectDataOutput);
            } else {
                // No setvalues document, we can simply aggregate with XPL
                final ASTHrefAggregate redirectDataAggregate = new ASTHrefAggregate("redirect-url",
                        new ASTHrefId(forwardPathInfoOutput), new ASTHrefId(isServerSideRedirectOutput),
                        new ASTHrefId(isRedirectExitPortal));
                if (isTransformedInstance) // Pass parameters only if needed
                    redirectDataAggregate.getHrefs().add(new ASTHrefId(parametersOutput));
                redirectURLData = redirectDataAggregate;
            }
            // Execute the redirect
            when.addStatement(new ASTProcessorCall(XMLConstants.REDIRECT_PROCESSOR_QNAME) {
                {
                    addInput(new ASTInput("data", redirectURLData));// {{setDebug("redirect 2");}}
                    final String[] locationParams = new String[] { "result page id", resultPageId };
                    setLocationData(new ExtendedLocationData((LocationData) resultElement.getData(),
                            "page redirection", resultElement, locationParams, true));
                }
            });
        }
    }

    // Signal if we did a redirect
    when.addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
        {
            addInput(
                    new ASTInput("data", new NonLazyUserDataDocument(new NonLazyUserDataElement("is-redirect") {
                        {
                            setText(Boolean.toString(resultPageId != null));
                        }
                    })));
            addOutput(new ASTOutput("data", redirect));
        }
    });

    // Export XUpdated instance from this branch
    when.addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
        {
            addInput(new ASTInput("data", new ASTHrefId(internalXUpdatedInstance)));
            addOutput(new ASTOutput("data", xupdatedInstance));
        }
    });
}