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.processor.PageFlowControllerProcessor.java

License:Open Source License

private static void handleEpilogue(final String controllerContext, List<ASTStatement> statements,
        final String epilogueURL, final Element epilogueElement, final ASTOutput epilogueData,
        final ASTOutput epilogueModelData, final ASTOutput epilogueInstance, final int defaultStatusCode) {
    // Send result through epilogue
    if (epilogueURL == null) {
        // Run HTML serializer
        statements.add(new ASTChoose(new ASTHrefId(epilogueData)) {
            {//from ww w.j  a  v a 2 s  . c  om
                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("status-code")
                                        .addText(Integer.toString(defaultStatusCode));
                                if (HTMLSerializer.DEFAULT_PUBLIC_DOCTYPE != null)
                                    rootElement.addElement("public-doctype")
                                            .addText(HTMLSerializer.DEFAULT_PUBLIC_DOCTYPE);
                                if (HTMLSerializer.DEFAULT_SYSTEM_DOCTYPE != null)
                                    rootElement.addElement("system-doctype")
                                            .addText(HTMLSerializer.DEFAULT_SYSTEM_DOCTYPE);
                                if (HTMLSerializer.DEFAULT_VERSION != null)
                                    rootElement.addElement("version").addText(HTMLSerializer.DEFAULT_VERSION);
                                addInput(new ASTInput("config", config));
                                addInput(new ASTInput("data", new ASTHrefId(epilogueData)));
                                //setLocationData(TODO);
                            }
                        });
                    }
                });
                addWhen(new ASTWhen());
            }
        });
    } else {
        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.PageFlowControllerProcessor.java

License:Open Source License

/**
 * Handle <page>//from   w  w  w .  j  av  a2s  .  c  om
 */
private void handlePage(final StepProcessorContext stepProcessorContext, final String controllerContext,
        List<ASTStatement> statementsList, final Element pageElement, final int pageNumber,
        final ASTOutput matcherOutput, final ASTOutput viewData, final ASTOutput epilogueModelData,
        final ASTOutput viewInstance, final Map<String, String> pageIdToPathInfo,
        final Map<String, String> pageIdToXFormsModel, 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(controllerContext, 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 XForms or 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(matcherOutput)));
            } 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 = actionElement.attributeValue("when");
                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-" + pageNumber + "-" + 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, controllerContext,
                                    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(matcherOutput)));
                                    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));
                                }
                            });
                        }

                        // Choose result
                        if (actionElement.elements("result").size() > 1
                                || (actionElement.element("result") != null
                                        && actionElement.element("result").attributeValue("when") != null)) {

                            // Help diagnose missing action/@action
                            if (internalActionData == null) {
                                throw new OXFException(
                                        "Found <result when=\"...\"> but <action> element is missing an action attribute.");
                            }

                            // Test based on action
                            addStatement(new ASTChoose(new ASTHrefId(internalActionData)) {
                                {
                                    for (Object o : actionElement.elements("result")) {
                                        final Element resultElement = (Element) o;
                                        final String resultWhenAttribute = resultElement.attributeValue("when");

                                        // 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(stepProcessorContext, controllerContext, this,
                                                        pageIdToXFormsModel, 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 {

                            // If we are not performing tests on the result from the action
                            final Element resultElement = actionElement.element("result");
                            executeResult(stepProcessorContext, controllerContext, this, pageIdToXFormsModel,
                                    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, controllerContext,
                                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(matcherOutput)));
                                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, controllerContext,
                                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(matcherOutput)));
                                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.PageFlowControllerProcessor.java

License:Open Source License

private void executeResult(StepProcessorContext stepProcessorContext, final String controllerContext,
        ASTWhen when, final Map<String, String> pageIdToXFormsModel, final Map<String, String> pageIdToPathInfo,
        final Map<String, Document> pageIdToSetvaluesDocument, final ASTOutput paramedInstance,
        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();
    final String otherXForms = pageIdToXFormsModel.get(resultPageId);

    // Whether we use the legacy XUpdate transformation
    final boolean useLegacyTransformation = (resultElement != null && !resultElement.elements().isEmpty()
            && resultElement.attribute("transform") == null);

    // Whether we use the destination page's instance
    final boolean useCurrentPageInstance = resultPageId == null || otherXForms == null
            || !useLegacyTransformation;

    final ASTOutput instanceToUpdate;
    if (useCurrentPageInstance) {
        // We use the current page's submitted instance, if any.
        instanceToUpdate = paramedInstance;
    } else {//  w w  w . ja v a2s  .  co  m
        // DEPRECATED: We use the resulting page's instance if possible (deprecated since xforms attribute on <page> is deprecated)
        instanceToUpdate = new ASTOutput("data", "other-page-instance");
        // Run the other page's XForms model
        final ASTOutput otherPageXFormsModel = new ASTOutput("data", "other-page-model");
        when.addStatement(
                new StepProcessorCall(stepProcessorContext, controllerContext, otherXForms, "xforms-model") {
                    {
                        addInput(new ASTInput("data", Dom4jUtils.NULL_DOCUMENT));
                        addInput(new ASTInput("instance", Dom4jUtils.NULL_DOCUMENT));
                        addInput(new ASTInput("xforms-model", Dom4jUtils.NULL_DOCUMENT));
                        addInput(new ASTInput("matcher", Dom4jUtils.NULL_DOCUMENT));
                        final ASTOutput dataOutput = new ASTOutput("data", otherPageXFormsModel);
                        final String[] locationParams = new String[] { "result page id", resultPageId,
                                "result page XForms model", otherXForms };
                        dataOutput.setLocationData(
                                new ExtendedLocationData((LocationData) resultElement.getData(),
                                        "reading other page XForms model data output", resultElement,
                                        locationParams, true));
                        addOutput(dataOutput);
                        setLocationData(new ExtendedLocationData((LocationData) resultElement.getData(),
                                "executing other page XForms model", resultElement, locationParams, true));
                    }
                });
        when.addStatement(new ASTProcessorCall(XMLConstants.IDENTITY_PROCESSOR_QNAME) {
            {
                addInput(new ASTInput("data",
                        new ASTHrefXPointer(new ASTHrefId(otherPageXFormsModel), EXTRACT_INSTANCE_XPATH)));
                addOutput(new ASTOutput("data", instanceToUpdate));
            }
        });
    }

    // 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;

        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(paramedInstance)));// 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 if (resultElement != null && !resultElement.elements().isEmpty()) {
        // Legacy transform mechanism (built-in XUpdate)
        internalXUpdatedInstance = new ASTOutput("data", "internal-xupdated-instance");
        isTransformedInstance = true;

        // Create XUpdate config
        // The code in this branch should be equivalent to the previous code doing the same
        // thing, except it will add the default namespace as well. I think there should be
        // the default namespace as well.
        final Document xupdateConfig = Dom4jUtils.createDocumentCopyParentNamespaces(resultElement);
        xupdateConfig.getRootElement().setQName(new QName("modifications", XUpdateConstants.XUPDATE_NAMESPACE));

        // Run XUpdate
        final String resultTraceAttribute = resultElement.attributeValue("trace");
        when.addStatement(new ASTProcessorCall(XMLConstants.XUPDATE_PROCESSOR_QNAME) {
            {
                addInput(new ASTInput("config", xupdateConfig));
                addInput(new ASTInput("data", new ASTHrefId(instanceToUpdate)));
                addInput(new ASTInput("instance", new ASTHrefId(paramedInstance)));
                if (actionData != null)
                    addInput(new ASTInput("action", new ASTHrefId(actionData)));
                addOutput(new ASTOutput("data", internalXUpdatedInstance) {
                    {
                        setDebug(resultTraceAttribute);
                    }
                });
            }
        });
    } 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));
        }
    });
}

From source file:org.orbeon.oxf.processor.pdf.PDFTemplateProcessor.java

License:Open Source License

/**
 * Resolve attribute value templates (AVTs).
 *
 * @param pipelineContext    current pipeline context
 * @param contextNode        context node for evaluation
 * @param variableToValueMap variables//w  w  w.j  a v a2  s.  c  o  m
 * @param functionLibrary    XPath function library to use
 * @param functionContext    context object to pass to the XForms function
 * @param element            element on which the AVT attribute is present
 * @param attributeValue     attribute value
 * @return                   resolved attribute value
 */
private static String resolveAttributeValueTemplates(PipelineContext pipelineContext, NodeInfo contextNode,
        Map<String, ValueRepresentation> variableToValueMap, FunctionLibrary functionLibrary,
        XPathCache.FunctionContext functionContext, Element element, String attributeValue) {

    if (attributeValue == null)
        return null;

    return XPathCache.evaluateAsAvt(contextNode, attributeValue,
            new NamespaceMapping(Dom4jUtils.getNamespaceContextNoDefault(element)), variableToValueMap,
            functionLibrary, functionContext, null, (LocationData) element.getData());
}

From source file:org.orbeon.oxf.processor.pdf.PDFTemplateProcessor.java

License:Open Source License

private void handleGroup(PipelineContext pipelineContext, GroupContext groupContext, List<Element> statements,
        FunctionLibrary functionLibrary, PdfReader reader) throws DocumentException, IOException {

    final NodeInfo contextNode = (NodeInfo) groupContext.contextNodeSet.get(groupContext.contextPosition - 1);
    final Map<String, ValueRepresentation> variableToValueMap = new HashMap<String, ValueRepresentation>();

    variableToValueMap.put("page-count", new Int64Value(reader.getNumberOfPages()));
    variableToValueMap.put("page-number", new Int64Value(groupContext.pageNumber));
    variableToValueMap.put("page-height", new FloatValue(groupContext.pageHeight));

    // Iterate through statements
    for (final Element currentElement : statements) {

        // Check whether this statement applies to the current page
        final String elementPage = currentElement.attributeValue("page");
        if ((elementPage != null) && !Integer.toString(groupContext.pageNumber).equals(elementPage))
            continue;

        final NamespaceMapping namespaceMapping = new NamespaceMapping(
                Dom4jUtils.getNamespaceContextNoDefault(currentElement));

        final String elementName = currentElement.getName();
        if (elementName.equals("group")) {
            // Handle group

            final GroupContext newGroupContext = new GroupContext(groupContext);

            final String ref = currentElement.attributeValue("ref");
            if (ref != null) {
                final NodeInfo newContextNode = (NodeInfo) XPathCache.evaluateSingle(
                        groupContext.contextNodeSet, groupContext.contextPosition, ref, namespaceMapping,
                        variableToValueMap, functionLibrary, null, null,
                        (LocationData) currentElement.getData());

                if (newContextNode == null)
                    continue;

                newGroupContext.contextNodeSet = Collections.singletonList((Item) newContextNode);
                newGroupContext.contextPosition = 1;
            }/*  w  ww.  j  ava  2s . c o m*/

            final String offsetXString = resolveAttributeValueTemplates(pipelineContext, contextNode,
                    variableToValueMap, null, null, currentElement, currentElement.attributeValue("offset-x"));
            if (offsetXString != null) {
                newGroupContext.offsetX = groupContext.offsetX + Float.parseFloat(offsetXString);
            }

            final String offsetYString = resolveAttributeValueTemplates(pipelineContext, contextNode,
                    variableToValueMap, null, null, currentElement, currentElement.attributeValue("offset-y"));
            if (offsetYString != null) {
                newGroupContext.offsetY = groupContext.offsetY + Float.parseFloat(offsetYString);
            }

            final String fontPitch = resolveAttributeValueTemplates(pipelineContext, contextNode,
                    variableToValueMap, null, null, currentElement,
                    currentElement.attributeValue("font-pitch"));
            if (fontPitch != null)
                newGroupContext.fontPitch = Float.parseFloat(fontPitch);

            final String fontFamily = resolveAttributeValueTemplates(pipelineContext, contextNode,
                    variableToValueMap, null, null, currentElement,
                    currentElement.attributeValue("font-family"));
            if (fontFamily != null)
                newGroupContext.fontFamily = fontFamily;

            final String fontSize = resolveAttributeValueTemplates(pipelineContext, contextNode,
                    variableToValueMap, null, null, currentElement, currentElement.attributeValue("font-size"));
            if (fontSize != null)
                newGroupContext.fontSize = Float.parseFloat(fontSize);

            handleGroup(pipelineContext, newGroupContext, Dom4jUtils.elements(currentElement), functionLibrary,
                    reader);

        } else if (elementName.equals("repeat")) {
            // Handle repeat

            final String nodeset = currentElement.attributeValue("nodeset");
            final List iterations = XPathCache.evaluate(groupContext.contextNodeSet,
                    groupContext.contextPosition, nodeset, namespaceMapping, variableToValueMap,
                    functionLibrary, null, null, (LocationData) currentElement.getData());

            final String offsetXString = resolveAttributeValueTemplates(pipelineContext, contextNode,
                    variableToValueMap, null, null, currentElement, currentElement.attributeValue("offset-x"));
            final String offsetYString = resolveAttributeValueTemplates(pipelineContext, contextNode,
                    variableToValueMap, null, null, currentElement, currentElement.attributeValue("offset-y"));
            final float offsetIncrementX = (offsetXString == null) ? 0 : Float.parseFloat(offsetXString);
            final float offsetIncrementY = (offsetYString == null) ? 0 : Float.parseFloat(offsetYString);

            for (int iterationIndex = 1; iterationIndex <= iterations.size(); iterationIndex++) {

                final GroupContext newGroupContext = new GroupContext(groupContext);

                newGroupContext.contextNodeSet = iterations;
                newGroupContext.contextPosition = iterationIndex;

                newGroupContext.offsetX = groupContext.offsetX + (iterationIndex - 1) * offsetIncrementX;
                newGroupContext.offsetY = groupContext.offsetY + (iterationIndex - 1) * offsetIncrementY;

                handleGroup(pipelineContext, newGroupContext, Dom4jUtils.elements(currentElement),
                        functionLibrary, reader);
            }
        } else if (elementName.equals("field")) {

            final String fieldNameStr = currentElement.attributeValue("acro-field-name");

            if (fieldNameStr != null) {
                final String value = currentElement.attributeValue("value") == null
                        ? currentElement.attributeValue("ref")
                        : currentElement.attributeValue("value");
                // Get value from instance

                final String text = XPathCache.evaluateAsString(groupContext.contextNodeSet,
                        groupContext.contextPosition, value, namespaceMapping, variableToValueMap,
                        functionLibrary, null, null, (LocationData) currentElement.getData());
                final String fieldName = XPathCache.evaluateAsString(groupContext.contextNodeSet,
                        groupContext.contextPosition, fieldNameStr, namespaceMapping, variableToValueMap,
                        functionLibrary, null, null, (LocationData) currentElement.getData());
                groupContext.acroFields.setField(fieldName, text);

            } else {
                // Handle field

                final String leftAttribute = currentElement.attributeValue("left") == null
                        ? currentElement.attributeValue("left-position")
                        : currentElement.attributeValue("left");
                final String topAttribute = currentElement.attributeValue("top") == null
                        ? currentElement.attributeValue("top-position")
                        : currentElement.attributeValue("top");

                final String leftPosition = resolveAttributeValueTemplates(pipelineContext, contextNode,
                        variableToValueMap, null, null, currentElement, leftAttribute);
                final String topPosition = resolveAttributeValueTemplates(pipelineContext, contextNode,
                        variableToValueMap, null, null, currentElement, topAttribute);

                final String size = resolveAttributeValueTemplates(pipelineContext, contextNode,
                        variableToValueMap, null, null, currentElement, currentElement.attributeValue("size"));
                final String value = currentElement.attributeValue("value") == null
                        ? currentElement.attributeValue("ref")
                        : currentElement.attributeValue("value");

                final FontAttributes fontAttributes = getFontAttributes(currentElement, pipelineContext,
                        groupContext, variableToValueMap, contextNode);

                // Output value
                final BaseFont baseFont = BaseFont.createFont(fontAttributes.fontFamily, BaseFont.CP1252,
                        BaseFont.NOT_EMBEDDED);
                groupContext.contentByte.beginText();
                {
                    groupContext.contentByte.setFontAndSize(baseFont, fontAttributes.fontSize);

                    final float xPosition = Float.parseFloat(leftPosition) + groupContext.offsetX;
                    final float yPosition = groupContext.pageHeight
                            - (Float.parseFloat(topPosition) + groupContext.offsetY);

                    // Get value from instance
                    final String text = XPathCache.evaluateAsString(groupContext.contextNodeSet,
                            groupContext.contextPosition, value, namespaceMapping, variableToValueMap,
                            functionLibrary, null, null, (LocationData) currentElement.getData());

                    // Iterate over characters and print them
                    if (text != null) {
                        int len = Math.min(text.length(),
                                (size != null) ? Integer.parseInt(size) : Integer.MAX_VALUE);
                        for (int j = 0; j < len; j++)
                            groupContext.contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER,
                                    text.substring(j, j + 1),
                                    xPosition + ((float) j) * fontAttributes.fontPitch, yPosition, 0);
                    }
                }
                groupContext.contentByte.endText();
            }
        } else if (elementName.equals("barcode")) {
            // Handle barcode

            final String leftAttribute = currentElement.attributeValue("left");
            final String topAttribute = currentElement.attributeValue("top");

            final String leftPosition = resolveAttributeValueTemplates(pipelineContext, contextNode,
                    variableToValueMap, null, null, currentElement, leftAttribute);
            final String topPosition = resolveAttributeValueTemplates(pipelineContext, contextNode,
                    variableToValueMap, null, null, currentElement, topAttribute);

            //                final String size = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, currentElement.attributeValue("size"));
            final String value = currentElement.attributeValue("value") == null
                    ? currentElement.attributeValue("ref")
                    : currentElement.attributeValue("value");
            final String type = currentElement.attributeValue("type") == null ? "CODE39"
                    : currentElement.attributeValue("type");
            final float height = currentElement.attributeValue("height") == null ? 10.0f
                    : Float.parseFloat(currentElement.attributeValue("height"));

            final float xPosition = Float.parseFloat(leftPosition) + groupContext.offsetX;
            final float yPosition = groupContext.pageHeight
                    - (Float.parseFloat(topPosition) + groupContext.offsetY);
            final String text = XPathCache.evaluateAsString(groupContext.contextNodeSet,
                    groupContext.contextPosition, value, namespaceMapping, variableToValueMap, functionLibrary,
                    null, null, (LocationData) currentElement.getData());

            final FontAttributes fontAttributes = getFontAttributes(currentElement, pipelineContext,
                    groupContext, variableToValueMap, contextNode);
            final BaseFont baseFont = BaseFont.createFont(fontAttributes.fontFamily, BaseFont.CP1252,
                    BaseFont.NOT_EMBEDDED);

            final Barcode barcode = createBarCode(type);
            barcode.setCode(text);
            barcode.setBarHeight(height);
            barcode.setFont(baseFont);
            barcode.setSize(fontAttributes.fontSize);
            final Image barcodeImage = barcode.createImageWithBarcode(groupContext.contentByte, null, null);
            barcodeImage.setAbsolutePosition(xPosition, yPosition);
            groupContext.contentByte.addImage(barcodeImage);
        } else if (elementName.equals("image")) {
            // Handle image

            // Read image
            final Image image;
            {
                final String hrefAttribute = currentElement.attributeValue("href");
                final String inputName = ProcessorImpl.getProcessorInputSchemeInputName(hrefAttribute);
                if (inputName != null) {
                    // Read the input
                    final ByteArrayOutputStream os = new ByteArrayOutputStream();
                    readInputAsSAX(pipelineContext, inputName,
                            new BinaryTextXMLReceiver(null, os, true, false, null, false, false, null, false));

                    // Create the image
                    image = Image.getInstance(os.toByteArray());
                } else {
                    // Read and create the image
                    final URL url = URLFactory.createURL(hrefAttribute);

                    // Use ConnectionResult so that header/session forwarding takes place
                    final ConnectionResult connectionResult = new Connection().open(
                            NetUtils.getExternalContext(), new IndentedLogger(logger, ""), false,
                            Connection.Method.GET.name(), url, null, null, null, null,
                            Connection.getForwardHeaders());

                    if (connectionResult.statusCode != 200) {
                        connectionResult.close();
                        throw new OXFException("Got invalid return code while loading image: "
                                + url.toExternalForm() + ", " + connectionResult.statusCode);
                    }

                    // Make sure things are cleaned-up not too late
                    pipelineContext.addContextListener(new PipelineContext.ContextListener() {
                        public void contextDestroyed(boolean success) {
                            connectionResult.close();
                        }
                    });

                    // Here we decide to copy to temp file and load as a URL. We could also provide bytes directly.
                    final String tempURLString = NetUtils.inputStreamToAnyURI(
                            connectionResult.getResponseInputStream(), NetUtils.REQUEST_SCOPE);
                    image = Image.getInstance(URLFactory.createURL(tempURLString));
                }
            }

            final String fieldNameStr = currentElement.attributeValue("acro-field-name");
            if (fieldNameStr != null) {
                // Use field as placeholder

                final String fieldName = XPathCache.evaluateAsString(groupContext.contextNodeSet,
                        groupContext.contextPosition, fieldNameStr, namespaceMapping, variableToValueMap,
                        functionLibrary, null, null, (LocationData) currentElement.getData());
                final float[] positions = groupContext.acroFields.getFieldPositions(fieldName);

                if (positions != null) {
                    final Rectangle rectangle = new Rectangle(positions[1], positions[2], positions[3],
                            positions[4]);

                    // This scales the image so that it fits in the box (but the aspect ratio is not changed)
                    image.scaleToFit(rectangle.getWidth(), rectangle.getHeight());

                    final float yPosition = positions[2] + rectangle.getHeight() - image.getScaledHeight();
                    image.setAbsolutePosition(
                            positions[1] + (rectangle.getWidth() - image.getScaledWidth()) / 2, yPosition);

                    // Add image
                    groupContext.contentByte.addImage(image);
                }

            } else {
                // Use position, etc.
                final String leftAttribute = currentElement.attributeValue("left");
                final String topAttribute = currentElement.attributeValue("top");
                final String scalePercentAttribute = currentElement.attributeValue("scale-percent");
                final String dpiAttribute = currentElement.attributeValue("dpi");

                final String leftPosition = resolveAttributeValueTemplates(pipelineContext, contextNode,
                        variableToValueMap, null, null, currentElement, leftAttribute);
                final String topPosition = resolveAttributeValueTemplates(pipelineContext, contextNode,
                        variableToValueMap, null, null, currentElement, topAttribute);

                final float xPosition = Float.parseFloat(leftPosition) + groupContext.offsetX;
                final float yPosition = groupContext.pageHeight
                        - (Float.parseFloat(topPosition) + groupContext.offsetY);

                final String scalePercent = resolveAttributeValueTemplates(pipelineContext, contextNode,
                        variableToValueMap, null, null, currentElement, scalePercentAttribute);
                final String dpi = resolveAttributeValueTemplates(pipelineContext, contextNode,
                        variableToValueMap, null, null, currentElement, dpiAttribute);

                // Set image parameters
                image.setAbsolutePosition(xPosition, yPosition);
                if (scalePercent != null) {
                    image.scalePercent(Float.parseFloat(scalePercent));
                }
                if (dpi != null) {
                    final int dpiInt = Integer.parseInt(dpi);
                    image.setDpi(dpiInt, dpiInt);
                }

                // Add image
                groupContext.contentByte.addImage(image);
            }
        } else {
            // NOP
        }
    }
}

From source file:org.orbeon.oxf.processor.pipeline.AggregatorProcessor.java

License:Open Source License

@Override
public ProcessorOutput createOutput(String name) {
    final ProcessorOutput output = new CacheableTransformerOutputImpl(AggregatorProcessor.this, name) {
        public void readImpl(PipelineContext context, XMLReceiver xmlReceiver) {

            try {
                // Read config
                final Element config = readCacheInputAsDOM4J(context, INPUT_CONFIG).getRootElement();
                final String rootQName = config.element("root").getText();
                final String rootPrefix;
                final String rootLocalName;
                final String rootNamespaceURI;

                // Get declared namespaces
                int columnPosition = rootQName.indexOf(':');
                if (columnPosition == -1) {
                    rootPrefix = "";
                    rootLocalName = rootQName;
                    rootNamespaceURI = "";
                } else {
                    rootPrefix = rootQName.substring(0, columnPosition);
                    rootLocalName = rootQName.substring(columnPosition + 1);
                    String tempNamespaceURI = null;
                    for (Iterator i = config.elements("namespace").iterator(); i.hasNext();) {
                        Element namespaceElement = (Element) i.next();
                        if (namespaceElement.attributeValue("prefix").equals(rootPrefix)) {
                            tempNamespaceURI = namespaceElement.attributeValue("uri");
                            break;
                        }/*w w  w. j a  v a2  s  . c om*/
                    }
                    if (tempNamespaceURI == null)
                        throw new ValidationException("Undeclared namespace prefix '" + rootPrefix + "'",
                                (LocationData) config.getData());

                    rootNamespaceURI = tempNamespaceURI;
                }

                // Start document
                xmlReceiver.startDocument();
                if (!rootNamespaceURI.equals(""))
                    xmlReceiver.startPrefixMapping(rootPrefix, rootNamespaceURI);
                xmlReceiver.startElement(rootNamespaceURI, rootLocalName, rootQName, XMLUtils.EMPTY_ATTRIBUTES);

                // Processor input processors
                for (Iterator i = getInputsByName(INPUT_DATA).iterator(); i.hasNext();) {
                    ProcessorInput input = (ProcessorInput) i.next();
                    readInputAsSAX(context, input, new EmbeddedDocumentXMLReceiver(xmlReceiver));
                }

                // End document
                xmlReceiver.endElement(rootNamespaceURI, rootLocalName, rootQName);
                if (!rootNamespaceURI.equals(""))
                    xmlReceiver.endPrefixMapping(rootPrefix);
                xmlReceiver.endDocument();
            } catch (SAXException e) {
                throw new OXFException(e);
            }
        }

        @Override
        public OutputCacheKey getKeyImpl(PipelineContext pipelineContext) {

            // Create input information
            final List<CacheKey> keys = new ArrayList<CacheKey>();
            for (final List<ProcessorInput> inputs : getConnectedInputs().values()) {
                for (final ProcessorInput input : inputs) {
                    final OutputCacheKey outputKey = getInputKey(pipelineContext, input);
                    if (outputKey == null) {
                        return null;
                    }
                    keys.add(outputKey);
                }
            }

            // Add local key if needed
            if (supportsLocalKeyValidity()) {
                final CacheKey localKey = getLocalKey(pipelineContext);
                if (localKey == null) {
                    return null;
                }
                keys.add(localKey);
            }

            // Concatenate current processor info and input info
            final CacheKey[] outputKeys = new CacheKey[keys.size()];
            keys.toArray(outputKeys);
            final Class processorClass = getProcessorClass();
            final String outputName = getName();

            return new CompoundOutputCacheKey(processorClass, outputName, outputKeys);
        }
    };
    addOutput(name, output);
    return output;
}

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

License:Open Source License

public static LocationData getElementLocationData(Element element) {
    final Object elementData = element.getData();
    return (elementData instanceof LocationData) ? (LocationData) elementData : null;
}

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

License:Open Source License

public static Processor createProcessorWithInputs(Element testNode, boolean saxDebug) {
    // Create processor
    QName processorName = XMLProcessorRegistry.extractProcessorQName(testNode);
    ProcessorFactory processorFactory = ProcessorFactoryRegistry.lookup(processorName);
    if (processorFactory == null)
        throw new OXFException("Cannot find processor factory with name '" + processorName.getNamespacePrefix()
                + ":" + processorName.getName() + "'");

    Processor processor = processorFactory.createInstance();

    // Connect inputs
    for (Iterator j = XPathUtils.selectIterator(testNode, "input"); j.hasNext();) {
        Element inputElement = (Element) j.next();
        String name = XPathUtils.selectStringValue(inputElement, "@name");
        if (XPathUtils.selectStringValue(inputElement, "@href") == null) {
            // Case of embedded XML
            Element originalElement = (Element) ((Element) inputElement).elementIterator().next();
            if (originalElement == null)
                throw new OXFException("Input content is mandatory");
            Element copiedElement = Dom4jUtils.copyElementCopyParentNamespaces(originalElement);
            final String sid = Dom4jUtils.makeSystemId(originalElement);
            final DOMGenerator domGenerator = new DOMGenerator(copiedElement, "input from pipeline utils",
                    DOMGenerator.ZeroValidity, sid);

            if (saxDebug) {
                final SAXLoggerProcessor loggerProcessor = new SAXLoggerProcessor();
                PipelineUtils.connect(domGenerator, "data", loggerProcessor, "data");
                PipelineUtils.connect(loggerProcessor, "data", processor, name);
            } else {
                PipelineUtils.connect(domGenerator, "data", processor, name);
            }//from  ww  w .  jav a 2 s  .com
        } else {
            // Href
            LocationData locationData = (LocationData) inputElement.getData();
            URL fullURL = createRelativeURL(locationData, XPathUtils.selectStringValue(inputElement, "@href"));

            URLGenerator urlGenerator = new URLGenerator(fullURL);
            urlGenerator.setLocationData(locationData);
            PipelineUtils.connect(urlGenerator, "data", processor, name);
        }
    }
    return processor;
}

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

License:Open Source License

public static Document createDocumentFromEmbeddedOrHref(Element element, String urlString) {
    final Document result;
    if (urlString == null) {
        // Case of embedded XML
        final Element originalElement = (Element) ((Element) element).elementIterator().next();
        if (originalElement == null)
            throw new OXFException("Content for element '" + element.getName() + "' is mandatory");
        Element copiedElement = Dom4jUtils.copyElementCopyParentNamespaces(originalElement);
        result = new NonLazyUserDataDocument();
        result.add(copiedElement);//from  w ww.  j  a  v a 2  s . c o m
    } else {
        // External URI
        final LocationData locationData = (LocationData) element.getData();
        result = createDocumentFromURL(urlString, locationData);
    }
    return result;
}

From source file:org.orbeon.oxf.properties.PropertyStore.java

License:Open Source License

/**
 * Construct a new property store./*ww  w.j  a  v a  2  s.c o  m*/
 *
 * @param propertiesDocument Document containing the properties definitions
 */
public PropertyStore(final Document propertiesDocument) {

    // NOTE: the use of "attributes" and "attribute" is for special use of the property store by certain processors
    for (final Iterator i = XPathUtils.selectIterator(propertiesDocument,
            "/properties//property | /attributes//attribute"); i.hasNext();) {
        final Element propertyElement = (Element) i.next();

        // Extract attributes
        final String processorName = propertyElement.attributeValue("processor-name");
        final String as = propertyElement.attributeValue("as");
        final String name = propertyElement.attributeValue("name");
        final String value = propertyElement.attributeValue("value");

        if (as != null) {
            // Read QName
            final QName typeQName = Dom4jUtils.extractAttributeValueQName(propertyElement, "as");

            if (SUPPORTED_TYPES.get(typeQName) == null)
                throw new ValidationException("Invalid as attribute: " + typeQName.getQualifiedName(),
                        (LocationData) propertyElement.getData());

            if (processorName != null) {
                // Processor-specific property
                final QName processorQName = Dom4jUtils.extractAttributeValueQName(propertyElement,
                        "processor-name");
                getProcessorPropertySet(processorQName).setProperty(propertyElement, name, typeQName, value);
            } else {
                // Global property
                getGlobalPropertySet().setProperty(propertyElement, name, typeQName, value);
            }
        }
    }
}