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) 

Source Link

Usage

From source file:org.apereo.portal.groups.pags.dao.jpa.PersonAttributesGroupTestDefinitionImpl.java

License:Apache License

@Override
public void toElement(org.dom4j.Element parent) {

    if (parent == null) {
        String msg = "Argument 'parent' cannot be null.";
        throw new IllegalArgumentException(msg);
    }/*  w w w.  j a  va2 s  .  c o m*/

    org.dom4j.Element elementTest = DocumentHelper.createElement(new QName("test"));
    elementTest.addElement("attribute-name").addText(this.getAttributeName());
    elementTest.addElement("tester-class").addText(this.getTesterClassName());
    elementTest.addElement("test-value").addText(this.getTestValue());
    parent.add(elementTest);
}

From source file:org.apereo.portal.groups.pags.dao.jpa.PersonAttributesGroupTestGroupDefinitionImpl.java

License:Apache License

@Override
public void toElement(org.dom4j.Element parent) {
    if (parent == null) {
        String msg = "Argument 'parent' cannot be null.";
        throw new IllegalArgumentException(msg);
    }/*from   w  ww.  java 2 s . co  m*/
    org.dom4j.Element elementTestGroup = DocumentHelper.createElement(new QName("test-group"));
    for (IPersonAttributesGroupTestDefinition test : tests) {
        test.toElement(elementTestGroup);
    }
    parent.add(elementTestGroup);
}

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

License:Open Source License

public void start(PipelineContext context) {
    try {//from   w ww  .j  a v  a 2s.c om
        List configs = readCacheInputAsObject(context, getInputByName(INPUT_CONFIG),
                new CacheableInputReader<List>() {
                    public List read(PipelineContext context, ProcessorInput input) {
                        List configs = new ArrayList();
                        Document document = readInputAsDOM4J(context, input);

                        for (Iterator i = XPathUtils.selectIterator(document, "/config/start-task"); i
                                .hasNext();) {
                            Element startTaskElement = (Element) i.next();
                            Config config = new Config(Config.START);
                            config.setName(XPathUtils.selectStringValueNormalize(startTaskElement, "name"));

                            // Create new processor definition
                            ProcessorDefinition processorDefinition = new ProcessorDefinition();
                            config.setProcessorDefinition(processorDefinition);

                            {
                                // Use processor QName
                                final Element processorNameElement = startTaskElement
                                        .element(new QName("processor-name"));
                                final QName processorQName = Dom4jUtils
                                        .extractTextValueQName(processorNameElement, true);
                                processorDefinition.setName(processorQName);

                                for (final Iterator j = XPathUtils.selectIterator(startTaskElement, "input"); j
                                        .hasNext();) {
                                    Element inputElement = (Element) j.next();
                                    String name = inputElement.attributeValue("name");
                                    String url = inputElement.attributeValue("url");
                                    if (url != null) {
                                        processorDefinition.addInput(name, url);
                                    } else {
                                        final Iterator it = inputElement.elementIterator();
                                        if (it.hasNext()) {
                                            final Element srcElt = (Element) it.next();
                                            final Element elt = (Element) srcElt.clone();
                                            processorDefinition.addInput(name, elt);
                                        } else
                                            throw new OXFException("Node not found input element");
                                    }
                                }
                            }

                            String startTimeString = XPathUtils.selectStringValueNormalize(startTaskElement,
                                    "start-time");
                            long startTime = 0;
                            if ("now".equalsIgnoreCase(startTimeString)) {
                                startTime = System.currentTimeMillis();
                            } else {
                                startTime = DateUtils.parseISODateOrDateTime(startTimeString);
                            }
                            config.setStartTime(startTime);

                            String interval = XPathUtils.selectStringValueNormalize(startTaskElement,
                                    "interval");
                            try {
                                config.setInterval(Long.parseLong(interval));
                            } catch (NumberFormatException e) {
                                throw new OXFException("Unsupported long value", e);
                            }

                            String sync = XPathUtils.selectStringValueNormalize(startTaskElement,
                                    "synchronized");
                            config.setSynchro(Boolean.valueOf(sync).booleanValue());

                            configs.add(config);
                        }

                        for (Iterator i = XPathUtils.selectIterator(document, "/config/stop-task"); i
                                .hasNext();) {
                            Element el = (Element) i.next();
                            Config config = new Config(Config.STOP);
                            config.setName(XPathUtils.selectStringValueNormalize(el, "name"));
                            configs.add(config);
                        }
                        return configs;
                    }
                });

        ExternalContext externalContext = (ExternalContext) context
                .getAttribute(PipelineContext.EXTERNAL_CONTEXT);
        TaskScheduler scheduler = TaskScheduler.getInstance(externalContext.getWebAppContext());

        //assert externalContext != null;

        for (Iterator i = configs.iterator(); i.hasNext();) {
            Config config = (Config) i.next();
            switch (config.getAction()) {
            case Config.START:
                // Create processor and connect its inputs
                Processor processor = InitUtils.createProcessor(config.getProcessorDefinition());
                processor.setId(config.getName());

                // Create and schedule a task
                // NOTE: The ExternalContext passed:
                // - has visibility on the application context only
                // - doesn't keep references to the current context
                ProcessorTask task = new ProcessorTask(config.getName(), processor, config.isSynchro(),
                        new WebAppExternalContext(externalContext.getWebAppContext(),
                                scala.Option.apply((HttpSession) null)));
                task.setSchedule(config.getStartTime(), config.getInterval());
                scheduler.schedule(task);
                break;
            case Config.STOP:
                // Find task and cancel it
                Task[] tasks = scheduler.getRunningTasks();
                for (int ti = 0; ti < tasks.length; ti++) {
                    if (tasks[ti] instanceof ProcessorTask && (tasks[ti]).getName().equals(config.getName()))
                        tasks[ti].cancel();
                }
                break;
            }
        }

    } catch (Exception e) {
        throw new OXFException(e);
    }
}

From source file:org.orbeon.oxf.processor.sql.interpreters.AttributeInterpreter.java

License:Open Source License

private static QName getQName(Locator locator, String qNameString, Map prefixesMap) {

    final int colonIndex = qNameString.indexOf(':');
    if (colonIndex == -1)
        return new QName(qNameString);
    if (colonIndex == 0)
        throw new ValidationException("Invalid QName:" + qNameString, new LocationData(locator));

    final String prefix = qNameString.substring(0, colonIndex);
    final String localName = qNameString.substring(colonIndex + 1);

    if (prefixesMap.get(prefix) == null) {
        throw new ValidationException("Undeclared prefix for QName:" + qNameString, new LocationData(locator));
    } else {/* w ww .  ja v a  2s  .c o m*/
        return new QName(localName, new Namespace(prefix, (String) prefixesMap.get(prefix)));
    }
}

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

License:Open Source License

public void start(final PipelineContext ctxt) {
    try {/*from   ww  w .j  av  a  2  s  . c o m*/
        final Node cfg = readInputAsDOM4J(ctxt, INPUT_CONFIG);

        for (Iterator i = XPathUtils.selectIterator(cfg, "/processors//processor"); i.hasNext();) { // support multiple nesting levels
            Element processorElement = (Element) i.next();

            // Extract processor name
            final QName processorQName = extractProcessorQName(processorElement);
            final String processorURI = extractProcessorURI(processorElement);// [BACKWARD COMPATIBILITY]
            if (processorQName == null && processorURI == null)
                throw new OXFException("Missing or empty processor name!");

            if (processorQName != null)
                logger.debug("Binding name: " + Dom4jUtils.qNameToExplodedQName(processorQName));
            if (processorURI != null)
                logger.debug("Binding name: " + processorURI);

            // Defined as a class
            Node classDef = XPathUtils.selectSingleNode(processorElement, "class");
            if (classDef != null) {
                final String className = XPathUtils.selectStringValueNormalize(classDef, "@name");
                if (logger.isDebugEnabled())
                    logger.debug("To class: " + className);

                final String defaultName = (processorQName != null)
                        ? Dom4jUtils.qNameToExplodedQName(processorQName)
                        : processorURI;
                final QName defaultQName = (processorQName != null) ? processorQName : new QName(processorURI);

                ProcessorFactory processorFactory = new ProcessorFactory() {
                    public Processor createInstance() {
                        try {
                            Processor processor = (Processor) Class.forName(className).newInstance();
                            processor.setName(defaultQName);
                            return processor;
                        } catch (ClassNotFoundException e) {
                            throw new OXFException("Cannot load processor '" + defaultName
                                    + "' because the class implementing this processor ('" + className
                                    + "') cannot be found");
                        } catch (NoClassDefFoundError e) {
                            throw new OXFException("Cannot load processor '" + defaultName
                                    + "' because it needs a class that cannot be loaded: '" + e.getMessage()
                                    + "'");
                        } catch (Exception e) {
                            throw new OXFException(e);
                        }
                    }
                };

                if (processorQName != null)
                    ProcessorFactoryRegistry.bind(processorQName, processorFactory);
                if (processorURI != null)
                    ProcessorFactoryRegistry.bind(processorURI, processorFactory);
            }

            // Defined based on an other processor (instantiation)
            final Element instantiationDef = (Element) XPathUtils.selectSingleNode(processorElement,
                    "instantiation");
            if (instantiationDef != null) {

                ProcessorFactory processorFactory = new ProcessorFactory() {
                    public Processor createInstance() {
                        try {
                            // Find base processor
                            final QName processorQName = extractProcessorQName(instantiationDef);
                            final String processorURI = extractProcessorURI(instantiationDef);// [BACKWARD COMPATIBILITY]
                            if (processorQName == null && processorURI == null)
                                throw new OXFException("Missing or empty processor name!");

                            if (processorQName != null)
                                logger.debug(
                                        "Binding name: " + Dom4jUtils.qNameToExplodedQName(processorQName));
                            if (processorURI != null)
                                logger.debug("Binding name: " + processorURI);

                            final QName defaultQName = (processorQName != null) ? processorQName
                                    : new QName(processorURI);

                            Processor baseProcessor = ((processorQName != null)
                                    ? ProcessorFactoryRegistry.lookup(processorQName)
                                    : ProcessorFactoryRegistry.lookup(processorURI)).createInstance();
                            // Override the name - can this have unexpected consequences?
                            baseProcessor.setName(defaultQName);

                            for (Iterator j = XPathUtils.selectIterator(instantiationDef, "input"); j
                                    .hasNext();) {
                                final Element inputElement = (Element) j.next();
                                final String name = XPathUtils.selectStringValueNormalize(inputElement,
                                        "@name");
                                final String href = XPathUtils.selectStringValueNormalize(inputElement,
                                        "@href");

                                if (href != null) {
                                    // Connect to URL generator
                                    Processor urlGenerator = PipelineUtils.createURLGenerator(href);
                                    PipelineUtils.connect(urlGenerator, OUTPUT_DATA, baseProcessor, name);
                                } else {
                                    final ProcessorInput processorConfigInput = getInputByName(INPUT_CONFIG);
                                    final Object processorConfigValidity = getInputValidity(ctxt,
                                            processorConfigInput);
                                    // We must have some XML in the <input> tag
                                    final Element childElement = (Element) inputElement.elements().get(0);
                                    final String sid = Dom4jUtils.makeSystemId(childElement);
                                    final DOMGenerator domGenerator = PipelineUtils.createDOMGenerator(
                                            childElement, "input from registry", processorConfigValidity, sid);
                                    PipelineUtils.connect(domGenerator, OUTPUT_DATA, baseProcessor, name);
                                }
                            }
                            return baseProcessor;
                        } catch (Exception e) {
                            throw new OXFException(e);
                        }
                    }
                };

                if (processorQName != null)
                    ProcessorFactoryRegistry.bind(processorQName, processorFactory);
                if (processorURI != null)
                    ProcessorFactoryRegistry.bind(processorURI, processorFactory);
            }
        }
    } catch (Exception e) {
        throw new OXFException(e);
    }
}

From source file:org.orbeon.oxf.transformer.xupdate.TemplatesHandlerImpl.java

License:Open Source License

/**
 * Parse a name / namespace attributes of &lt;xu:element> and
 * &lt;xu:attribute>//from   www . jav a  2 s . co  m
 */
private QName parseQName(Element element) {
    String name = element.attributeValue("name");
    String namespace = element.attributeValue("namespace");
    int columnPosition = name.indexOf(':');

    // Check syntax of qname
    if (columnPosition == 0 || columnPosition == name.length() - 1)
        throw new ValidationException("Invalid qname '" + name + "'", (LocationData) element.getData());

    if (columnPosition == -1 && namespace == null) {
        // Simple name
        return new QName(name);
    } else if (columnPosition != -1 && namespace == null) {
        // Qualified name using namespace declaration in context
        String prefix = name.substring(0, columnPosition);
        String namespaceFromContext = (String) Dom4jUtils.getNamespaceContext(element).get(prefix);
        if (namespaceFromContext == null)
            throw new ValidationException("No namespace declared for prefix '" + prefix + "'",
                    (LocationData) element.getData());
        return new QName(name.substring(columnPosition + 1),
                new org.dom4j.Namespace(prefix, namespaceFromContext));
    } else if (columnPosition == -1 && namespace != null) {
        // Non-qualified name with namespace declaration
        return new QName(name, new org.dom4j.Namespace("", namespace));
    } else if (columnPosition != -1 && namespace != null) {
        // Qualified name using namespace specified
        return new QName(name.substring(columnPosition + 1),
                new org.dom4j.Namespace(name.substring(0, columnPosition), namespace));
    } else {
        // This can't happen
        throw new OXFException("Invalid state");
    }
}

From source file:org.orbeon.oxf.xforms.function.XFormsFunction.java

License:Open Source License

private QName createQName(String qNameString, String qNameURI, int colonIndex, String prefix) {
    if (colonIndex == -1) {
        // NCName
        // NOTE: This assumes that if there is no prefix, the QName is in no namespace
        return new QName(qNameString);
    } else {//from w  w  w .  j  a  v a  2  s  . c  o  m
        // QName-but-not-NCName
        return new QName(qNameString.substring(colonIndex + 1), new Namespace(prefix, qNameURI));
    }
}

From source file:org.orbeon.oxf.xforms.processor.handlers.xhtml.XHTMLBodyHandler.java

License:Open Source License

public void start(String uri, String localname, String qName, Attributes attributes) throws SAXException {

    // Register control handlers on controller
    registerHandlers(handlerContext.getController(), containingDocument);

    // Add class for YUI skin
    // TODO: should be configurable somehow
    attributes = XMLUtils.appendToClassAttribute(attributes, "yui-skin-sam");

    // Start xhtml:body
    final XMLReceiver xmlReceiver = handlerContext.getController().getOutput();
    xmlReceiver.startElement(uri, localname, qName, attributes);
    helper = new XMLReceiverHelper(xmlReceiver);

    final String htmlPrefix = XMLUtils.prefixFromQName(qName);

    // Get formatting prefix and declare it if needed
    // TODO: would be nice to do this here, but then we need to make sure this prefix is available to other handlers
    //        formattingPrefix = handlerContext.findFormattingPrefixDeclare();

    final boolean isPortletClient;
    {/*from   w  ww  .j  a va 2  s .  co  m*/
        final ExternalContext.Request request = handlerContext.getExternalContext().getRequest();
        isPortletClient = "portlet".equals(NetUtils.getHeader(request.getHeaderValuesMap(), "orbeon-client"));
    }

    final String requestPath = containingDocument.getRequestPath();
    final String xformsSubmissionPath;
    {
        if (containingDocument.getDeploymentType() != XFormsConstants.DeploymentType.standalone
                || containingDocument.getContainerType().equals("portlet") || isPortletClient) {
            // Integrated or separate deployment mode or portlet
            xformsSubmissionPath = "/xforms-server-submit";
        } else {
            // Plain deployment mode: submission posts to URL of the current page and xforms-xml-submission.xpl intercepts that
            xformsSubmissionPath = requestPath;
        }
    }

    // Noscript panel is included before the xhtml:form element, in case the form is hidden through CSS
    if (!handlerContext.isNoScript()) {
        helper.element("", XMLConstants.XINCLUDE_URI, "include", new String[] { "href",
                getIncludedResourceURL(requestPath, "noscript-panel.xml"), "fixup-xml-base", "false" });
    }

    final StringBuilder sb = new StringBuilder("xforms-form");
    sb.append(handlerContext.isNoScript() ? " xforms-noscript" : " xforms-initially-hidden");

    // Hint/help appearance classes
    AppearanceTrait$.MODULE$.encodeAndAppendAppearance(sb, "hint",
            new QName(XFormsProperties.getHintAppearance(containingDocument)));
    AppearanceTrait$.MODULE$.encodeAndAppendAppearance(sb, "help",
            new QName(XFormsProperties.getHelpAppearance(containingDocument)));

    // Create xhtml:form element
    // NOTE: Do multipart as well with portlet client to simplify the proxying so we don't have to re-encode parameters
    final boolean doMultipartPOST = containingDocument.getStaticOps().hasControlByName("upload")
            || isPortletClient;
    helper.startElement(htmlPrefix, XMLConstants.XHTML_NAMESPACE_URI, "form", new String[] {
            // Add id so that things work in portals
            "id", XFormsUtils.getFormId(containingDocument),
            // Regular classes
            "class", sb.toString(),
            // Submission parameters
            "action", xformsSubmissionPath, "method", "POST",
            // In noscript mode, don't add event handler
            "onsubmit", handlerContext.isNoScript() ? null : "return false", doMultipartPOST ? "enctype" : null,
            doMultipartPOST ? "multipart/form-data" : null });

    {
        // Output encoded static and dynamic state
        helper.element(htmlPrefix, XMLConstants.XHTML_NAMESPACE_URI, "input",
                new String[] { "type", "hidden", "name", "$uuid", "value", containingDocument.getUUID() });
        // NOTE: we don't need $sequence here as HTML form posts are either:
        //
        // - 2nd phase of replace="all" submission: we don't (and can't) retry
        // - background upload: we don't want a sequence number as this run in parallel
        // - noscript mode: we don't (and can't) retry
        //
        // NOTE: Keep empty static state and dynamic state until client is able to deal without them
        final String clientEncodedStaticState = XFormsStateManager.instance()
                .getClientEncodedStaticState(containingDocument);
        //            if (clientEncodedStaticState != null) {
        helper.element(htmlPrefix, XMLConstants.XHTML_NAMESPACE_URI, "input",
                new String[] { "type", "hidden", "name", "$static-state", "value", clientEncodedStaticState });
        //            }
        final String clientEncodedDynamicState = XFormsStateManager.instance()
                .getClientEncodedDynamicState(containingDocument);
        //            if (clientEncodedDynamicState != null) {
        helper.element(htmlPrefix, XMLConstants.XHTML_NAMESPACE_URI, "input", new String[] { "type", "hidden",
                "name", "$dynamic-state", "value", clientEncodedDynamicState });
        //            }
    }

    if (!handlerContext.isNoScript()) {
        // Other fields used by JavaScript
        helper.element(htmlPrefix, XMLConstants.XHTML_NAMESPACE_URI, "input",
                new String[] { "type", "hidden", "name", "$server-events", "value", "" });
        helper.element(htmlPrefix, XMLConstants.XHTML_NAMESPACE_URI, "input", new String[] { "type", "text",
                "name", "$client-state", "value", "", "class", "xforms-initially-hidden" });

        // Store information about nested repeats hierarchy
        helper.element(htmlPrefix, XMLConstants.XHTML_NAMESPACE_URI, "input",
                new String[] { "type", "hidden", "name", "$repeat-tree", "value", containingDocument
                        .getStaticOps().getRepeatHierarchyString(containingDocument.getContainerNamespace()) });

        // Store information about the initial index of each repeat
        helper.element(htmlPrefix, XMLConstants.XHTML_NAMESPACE_URI, "input",
                new String[] { "type", "hidden", "name", "$repeat-indexes", "value",
                        XFormsRepeatControl.currentNamespacedIndexesString(containingDocument) });

        // Ajax loading indicator
        if (XFormsProperties.isAjaxShowLoadingIcon(containingDocument)) {

            helper.startElement(htmlPrefix, XMLConstants.XHTML_NAMESPACE_URI, "span",
                    new String[] { "class", "xforms-loading-loading" });
            helper.text("Loading..."); // text is hardcoded, but you can rewrite it in the theme if needed
            helper.endElement();

            helper.element(htmlPrefix, XMLConstants.XHTML_NAMESPACE_URI, "span",
                    new String[] { "class", "xforms-loading-none" });
        }

        // Ajax error panel
        XFormsError.outputAjaxErrorPanel(containingDocument, helper, htmlPrefix);

        // Help panel
        helper.element("", XMLConstants.XINCLUDE_URI, "include", new String[] { "href",
                getIncludedResourceURL(requestPath, "help-panel.xml"), "fixup-xml-base", "false" });

        // Templates
        {
            final String spanQName = XMLUtils.buildQName(htmlPrefix, "span");

            // HACK: We would be ok with just one template, but IE 6 doesn't allow setting the input/@type attribute properly

            // xf:select[@appearance = 'full'], xf:input[@type = 'xs:boolean']
            XFormsSelect1Handler.outputItemFullTemplate(this, xmlReceiver, htmlPrefix, spanQName,
                    containingDocument, reusableAttributes, attributes, "xforms-select-full-template",
                    "$xforms-item-name$", true, "checkbox");

            // xf:select1[@appearance = 'full']
            XFormsSelect1Handler.outputItemFullTemplate(this, xmlReceiver, htmlPrefix, spanQName,
                    containingDocument, reusableAttributes, attributes, "xforms-select1-full-template",
                    "$xforms-item-name$", false, "radio");
        }

    } else {
        // Noscript mode
        helper.element(htmlPrefix, XMLConstants.XHTML_NAMESPACE_URI, "input",
                new String[] { "type", "hidden", "name", "$noscript", "value", "true" });

        // Noscript error panel
        XFormsError.outputNoscriptErrorPanel(containingDocument, helper, htmlPrefix);
    }
}

From source file:org.orbeon.oxf.xml.dom4j.Dom4jUtils.java

License:Open Source License

/**
 * Decode a String containing an exploded QName (also known as a "Clark name") into a QName.
 *//*from w ww  . j a  v  a  2  s .  c  om*/
public static QName explodedQNameToQName(String qName) {
    int openIndex = qName.indexOf("{");

    if (openIndex == -1)
        return new QName(qName);

    String namespaceURI = qName.substring(openIndex + 1, qName.indexOf("}"));
    String localName = qName.substring(qName.indexOf("}") + 1);
    return new QName(localName, new Namespace("p1", namespaceURI));
}

From source file:ubic.pubmedgate.interactions.DuplicateXMLParses.java

License:Apache License

private void fixXML(Document document, String path, Map<String, String> attributes) {
    List list = document.selectNodes(path);
    Iterator iter = list.iterator();
    while (iter.hasNext()) {
        String attribute = attributes.keySet().iterator().next();
        Element el = (Element) iter.next();

        if (el.attribute("parser") != null
                && el.attribute("parser").getValue().equals("Charniak-Johnson-McClosky")) {
            el.addAttribute("parser", "Charniak-Lease");
        }//from w w  w .  j  ava2  s . c om

        String tokenizer = el.attribute(attribute).getValue();
        String replacement = attributes.get(attribute);
        if (!tokenizer.equals(replacement)) {
            log.info(tokenizer + " -> " + replacement);
            Element newElement = el.createCopy();
            for (String attributeFix : attributes.keySet()) {
                newElement.addAttribute(new QName(attributeFix), attributes.get(attributeFix));
            }
            el.getParent().add(newElement);
        }

    }
}