Example usage for org.dom4j QName QName

List of usage examples for org.dom4j QName QName

Introduction

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

Prototype

public QName(String name, Namespace namespace) 

Source Link

Usage

From source file:org.openxml4j.opc.internal.unmarshallers.PackagePropertiesUnmarshaller.java

License:Apache License

private String loadTitle(Document xmlDoc) {
    Element el = xmlDoc.getRootElement().element(new QName(KEYWORD_TITLE, namespaceDC));
    if (el != null)
        return el.getStringValue();
    else//  ww w . j a  v a2 s. c  o  m
        return null;
}

From source file:org.openxml4j.opc.internal.unmarshallers.PackagePropertiesUnmarshaller.java

License:Apache License

private String loadVersion(Document xmlDoc) {
    Element el = xmlDoc.getRootElement().element(new QName(KEYWORD_VERSION, namespaceCP));
    if (el != null)
        return el.getStringValue();
    else// ww  w .  ja  v a2s  .  com
        return null;
}

From source file:org.openxml4j.opc.internal.unmarshallers.PackagePropertiesUnmarshaller.java

License:Apache License

/**
 * Check the element for the following OPC compliance rules:
 * //  w w  w. ja  v  a2  s  .  c  o  m
 * Rule M4.2: A format consumer shall consider the use of the Markup
 * Compatibility namespace to be an error.
 * 
 * Rule M4.3: Producers shall not create a document element that contains
 * refinements to the Dublin Core elements, except for the two specified in
 * the schema: <dcterms:created> and <dcterms:modified> Consumers shall
 * consider a document element that violates this constraint to be an error.
 * 
 * Rule M4.4: Producers shall not create a document element that contains
 * the xml:lang attribute. Consumers shall consider a document element that
 * violates this constraint to be an error.
 * 
 * Rule M4.5: Producers shall not create a document element that contains
 * the xsi:type attribute, except for a <dcterms:created> or
 * <dcterms:modified> element where the xsi:type attribute shall be present
 * and shall hold the value dcterms:W3CDTF, where dcterms is the namespace
 * prefix of the Dublin Core namespace. Consumers shall consider a document
 * element that violates this constraint to be an error.
 */
public void checkElementForOPCCompliance(Element el) throws InvalidFormatException {
    // Check the current element
    List declaredNamespaces = el.declaredNamespaces();
    Iterator itNS = declaredNamespaces.iterator();
    while (itNS.hasNext()) {
        Namespace ns = (Namespace) itNS.next();

        // Rule M4.2
        if (ns.getURI().equals(PackageNamespaces.MARKUP_COMPATIBILITY))
            throw new InvalidFormatException(
                    "OPC Compliance error [M4.2]: A format consumer shall consider the use of the Markup Compatibility namespace to be an error.");
    }

    // Rule M4.3
    if (el.getNamespace().getURI().equals(PackageProperties.NAMESPACE_DCTERMS)
            && !(el.getName().equals(KEYWORD_CREATED) || el.getName().equals(KEYWORD_MODIFIED)))
        throw new InvalidFormatException(
                "OPC Compliance error [M4.3]: Producers shall not create a document element that contains refinements to the Dublin Core elements, except for the two specified in the schema: <dcterms:created> and <dcterms:modified> Consumers shall consider a document element that violates this constraint to be an error.");

    // Rule M4.4
    if (el.attribute(new QName("lang", namespaceXML)) != null)
        throw new InvalidFormatException(
                "OPC Compliance error [M4.4]: Producers shall not create a document element that contains the xml:lang attribute. Consumers shall consider a document element that violates this constraint to be an error.");

    // Rule M4.5
    if (el.getNamespace().getURI().equals(PackageProperties.NAMESPACE_DCTERMS)) {
        // DCTerms namespace only use with 'created' and 'modified' elements
        String elName = el.getName();
        if (!(elName.equals(KEYWORD_CREATED) || elName.equals(KEYWORD_MODIFIED)))
            throw new InvalidFormatException("Namespace error : " + elName
                    + " shouldn't have the following naemspace -> " + PackageProperties.NAMESPACE_DCTERMS);

        // Check for the 'xsi:type' attribute
        Attribute typeAtt = el.attribute(new QName("type", namespaceXSI));
        if (typeAtt == null)
            throw new InvalidFormatException("The element '" + elName + "' must have the '"
                    + namespaceXSI.getPrefix() + ":type' attribute present !");

        // Check for the attribute value => 'dcterms:W3CDTF'
        if (!typeAtt.getValue().equals("dcterms:W3CDTF"))
            throw new InvalidFormatException("The element '" + elName + "' must have the '"
                    + namespaceXSI.getPrefix() + ":type' attribute with the value 'dcterms:W3CDTF' !");
    }

    // Check its children
    Iterator itChildren = el.elementIterator();
    while (itChildren.hasNext())
        checkElementForOPCCompliance((Element) itChildren.next());
}

From source file:org.openxml4j.opc.signature.RelationshipTransform.java

License:Apache License

@SuppressWarnings("unchecked")
public static void RemoveAllNameSpacesExceptRelationship(Element elem) {

    // if the default namespace is not correct or if it has a prefix
    // fix it by setting to correct value without prefix
    if (elem.getNamespace().getStringValue() != PackageNamespaces.RELATIONSHIPS
            || elem.getNamespace().getPrefix() != "") {
        elem.setQName(new QName(elem.getName(),
                DocumentFactory.getInstance().createNamespace("", PackageNamespaces.RELATIONSHIPS)));
    }/*from   w  ww  .  ja v a 2 s. c o m*/

    // remove all additional namespace declarations
    List<Namespace> additionalNameSpaces = elem.additionalNamespaces();
    for (Namespace nms : additionalNameSpaces) {
        elem.remove(nms);
    }
}

From source file:org.orbeon.oxf.main.OPS.java

License:Open Source License

public void init() {

    // Initialize a basic logging configuration until the resource manager is setup
    LoggerFactory.initBasicLogger();/* www . ja v a 2s  .c  o m*/

    // 2. Initialize resource manager
    // Resources are first searched in a file hierarchy, then from the classloader
    final Map<String, Object> props = new LinkedHashMap<String, Object>();
    props.put("oxf.resources.factory", "org.orbeon.oxf.resources.PriorityResourceManagerFactory");
    if (resourceManagerSandbox != null) {
        // Use a sandbox
        props.put("oxf.resources.filesystem.sandbox-directory", resourceManagerSandbox);
    }
    props.put("oxf.resources.priority.1", "org.orbeon.oxf.resources.FilesystemResourceManagerFactory");
    props.put("oxf.resources.priority.2", "org.orbeon.oxf.resources.ClassLoaderResourceManagerFactory");
    if (logger.isInfoEnabled())
        logger.info("Initializing Resource Manager with: " + props);
    ResourceManagerWrapper.init(props);

    // 3. Initialize properties with default properties file.
    Properties.init(Properties.DEFAULT_PROPERTIES_URI);

    // 4. Initialize log4j (using the properties this time)
    LoggerFactory.initLogger();

    // 5. Build processor definition from command-line parameters
    if (otherArgs != null && otherArgs.length == 1) {
        // Assume the pipeline processor and a config input
        processorDefinition = new ProcessorDefinition();
        processorDefinition.setName(new QName("pipeline", XMLConstants.OXF_PROCESSORS_NAMESPACE));

        final String configURL;
        if (!NetUtils.urlHasProtocol(otherArgs[0])) {
            // URL is considered relative to current directory
            try {
                // Create absolute URL, and switch to the oxf: protocol
                String fileURL = new URL(new File(".").toURI().toURL(), otherArgs[0]).toExternalForm();
                configURL = "oxf:" + fileURL.substring(fileURL.indexOf(':') + 1);
            } catch (MalformedURLException e) {
                throw new OXFException(e);
            }
        } else {
            configURL = otherArgs[0];
        }

        processorDefinition.addInput("config", configURL);

        // Add additional inputs if any
        for (int i = 0; inputs != null && i < inputs.length; i++) {
            String input = inputs[i];
            int iEqual = input.indexOf("=");
            if (iEqual <= 0 || iEqual >= input.length() - 1) {
                throw new OXFException("Input \"" + input + "\" doesn't follow the syntax <name>=<url>");
            }
            String inputName = input.substring(0, iEqual);
            String inputValue = input.substring(iEqual + 1);
            if (inputValue.startsWith("<")) {
                // XML document
                try {
                    processorDefinition.addInput(inputName,
                            DocumentHelper.parseText(inputValue).getRootElement());
                } catch (DocumentException e) {
                    throw new OXFException(e);
                }
            } else {
                // URL
                processorDefinition.addInput(inputName, inputValue);
            }
        }
    } else {
        throw new OXFException("No main processor definition found.");
    }
}

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 {//from w w  w. ja  v a 2s .  c om
        // 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.pipeline.ast.ASTDocumentHandler.java

License:Open Source License

public boolean startPipeline(ASTPipeline pipeline) {
    currentElement = new NonLazyUserDataElement(new QName("config", PipelineProcessor.PIPELINE_NAMESPACE));
    document.setRootElement(currentElement);
    return true;//  w  w w . j a  v a2  s  . co  m
}

From source file:org.orbeon.oxf.processor.pipeline.ast.ASTDocumentHandler.java

License:Open Source License

public void param(ASTParam param) {
    Element paramElement = currentElement.addElement(new QName("param", PipelineProcessor.PIPELINE_NAMESPACE));
    paramElement.addAttribute("type", param.getType() == ASTParam.INPUT ? "input" : "output");
    paramElement.addAttribute("name", param.getName());
}

From source file:org.orbeon.oxf.processor.pipeline.ast.ASTDocumentHandler.java

License:Open Source License

public boolean startProcessorCall(ASTProcessorCall processorCall) {
    currentElement = currentElement.addElement(new QName("processor", PipelineProcessor.PIPELINE_NAMESPACE));
    if (processorCall.getName() != null) {
        currentElement.addAttribute("name", processorCall.getName().getQualifiedName());
    } else {//from w ww.ja  v  a  2s  .  c o  m
        currentElement.addAttribute("class", processorCall.getProcessor().getClass().getName());
    }
    return true;
}

From source file:org.orbeon.oxf.processor.pipeline.ast.ASTDocumentHandler.java

License:Open Source License

public void endInput(ASTInput input) {
    Element inputElement = currentElement.addElement(new QName("input", PipelineProcessor.PIPELINE_NAMESPACE));
    inputElement.addAttribute("name", input.getName());
    if (!href.isEmpty())
        inputElement.addAttribute("href", (String) href.pop());
    if (input.getContent() != null) {
        if (input.getContent() instanceof Document) {
            inputElement.add(((Document) input.getContent()).getRootElement().createCopy());
        } else {//from w ww.  j ava 2 s  . c  o  m
            inputElement.add((Node) input.getContent().clone());
        }
    }
}