Example usage for org.dom4j DocumentHelper createNamespace

List of usage examples for org.dom4j DocumentHelper createNamespace

Introduction

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

Prototype

public static Namespace createNamespace(String prefix, String uri) 

Source Link

Usage

From source file:com.alibaba.citrus.springext.impl.SchemaImpl.java

License:Open Source License

/**
 * ?schema??/*ww  w  .j a va 2 s . c om*/
 * <ol>
 * <li>targetNamespace</li>
 * <li>include name</li>
 * </ol>
 */
@Override
protected void doAnalyze() {
    Document doc = getDocument(); // ??null
    org.dom4j.Element root = doc.getRootElement();

    // return if not a schema file
    if (!W3C_XML_SCHEMA_NS_URI.equals(root.getNamespaceURI()) || !"schema".equals(root.getName())) {
        return;
    }

    // parse targetNamespace
    if (parsingTargetNamespace) {
        Attribute attr = root.attribute("targetNamespace");

        if (attr != null) {
            targetNamespace = trimToNull(attr.getStringValue());
        }
    }

    // parse include
    Namespace xsd = DocumentHelper.createNamespace("xsd", W3C_XML_SCHEMA_NS_URI);
    QName includeName = DocumentHelper.createQName("include", xsd);
    List<String> includeNames = createLinkedList();

    // for each <xsd:include>
    for (Iterator<?> i = root.elementIterator(includeName); i.hasNext();) {
        org.dom4j.Element includeElement = (org.dom4j.Element) i.next();
        String schemaLocation = trimToNull(includeElement.attributeValue("schemaLocation"));

        if (schemaLocation != null) {
            includeNames.add(schemaLocation);
        }
    }

    includes = includeNames.toArray(new String[includeNames.size()]);

    // parse xsd:element
    QName elementName = DocumentHelper.createQName("element", xsd);

    // for each <xsd:element>
    for (Iterator<?> i = root.elementIterator(elementName); i.hasNext();) {
        Element element = new ElementImpl((org.dom4j.Element) i.next());

        if (element.getName() != null) {
            this.elements.put(element.getName(), element);
        }
    }
}

From source file:com.alibaba.citrus.springext.support.SchemaUtil.java

License:Open Source License

/** schema?includes */
public static Transformer getTransformerWhoAddsIndirectIncludes(final Map<String, Schema> includes) {
    return new Transformer() {
        public void transform(Document document, String systemId) {
            Element root = document.getRootElement();

            root.addNamespace("xsd", W3C_XML_SCHEMA_NS_URI);

            // <xsd:schema>
            if (W3C_XML_SCHEMA_NS_URI.equals(root.getNamespaceURI()) && "schema".equals(root.getName())) {
                Namespace xsd = DocumentHelper.createNamespace("xsd", W3C_XML_SCHEMA_NS_URI);
                QName includeName = DocumentHelper.createQName("include", xsd);

                // for each <xsd:include>
                for (Iterator<?> i = root.elementIterator(includeName); i.hasNext();) {
                    i.next();//from w w  w  .j  a v  a 2  s  .c om
                    i.remove();
                }

                // includes
                @SuppressWarnings("unchecked")
                List<Node> nodes = root.elements();
                int i = 0;

                for (Schema includedSchema : includes.values()) {
                    Element includeElement = DocumentHelper.createElement(includeName);
                    nodes.add(i++, includeElement);

                    includeElement.addAttribute("schemaLocation", includedSchema.getName());
                }
            }
        }
    };
}

From source file:com.alibaba.citrus.springext.support.SchemaUtil.java

License:Open Source License

/** ?URI? */
public static Transformer getAddPrefixTransformer(final SchemaSet schemas, String prefix) {
    if (prefix != null) {
        if (!prefix.endsWith("/")) {
            prefix += "/";
        }//from  www.  j  av a 2  s  .com
    }

    final String normalizedPrefix = prefix;

    return new Transformer() {
        public void transform(Document document, String systemId) {
            if (normalizedPrefix != null) {
                Element root = document.getRootElement();

                // <xsd:schema>
                if (W3C_XML_SCHEMA_NS_URI.equals(root.getNamespaceURI()) && "schema".equals(root.getName())) {
                    Namespace xsd = DocumentHelper.createNamespace("xsd", W3C_XML_SCHEMA_NS_URI);
                    QName includeName = DocumentHelper.createQName("include", xsd);
                    QName importName = DocumentHelper.createQName("import", xsd);

                    // for each <xsd:include>
                    for (Iterator<?> i = root.elementIterator(includeName); i.hasNext();) {
                        Element includeElement = (Element) i.next();
                        String schemaLocation = trimToNull(includeElement.attributeValue("schemaLocation"));

                        if (schemaLocation != null) {
                            schemaLocation = getNewSchemaLocation(schemaLocation, null, systemId);

                            if (schemaLocation != null) {
                                includeElement.addAttribute("schemaLocation", schemaLocation);
                            }
                        }
                    }

                    // for each <xsd:import>
                    for (Iterator<?> i = root.elementIterator(importName); i.hasNext();) {
                        Element importElement = (Element) i.next();
                        String schemaLocation = importElement.attributeValue("schemaLocation");
                        String namespace = trimToNull(importElement.attributeValue("namespace"));

                        if (schemaLocation != null || namespace != null) {
                            schemaLocation = getNewSchemaLocation(schemaLocation, namespace, systemId);

                            if (schemaLocation != null) {
                                importElement.addAttribute("schemaLocation", schemaLocation);
                            }
                        }
                    }
                }
            }
        }

        private String getNewSchemaLocation(String schemaLocation, String namespace, String systemId) {
            // ?schemaLocation
            if (schemaLocation != null) {
                Schema schema = schemas.findSchema(schemaLocation);

                if (schema != null) {
                    return normalizedPrefix + schema.getName();
                } else {
                    return schemaLocation; // location??
                }
            }

            // ??namespace
            if (namespace != null) {
                Set<Schema> nsSchemas = schemas.getNamespaceMappings().get(namespace);

                if (nsSchemas != null && !nsSchemas.isEmpty()) {
                    // ?nsschema?schema
                    String versionedExtension = getVersionedExtension(systemId);

                    if (versionedExtension != null) {
                        for (Schema schema : nsSchemas) {
                            if (schema.getName().endsWith(versionedExtension)) {
                                return normalizedPrefix + schema.getName();
                            }
                        }
                    }

                    // schema?beans.xsd?beans-2.5.xsd?beans-2.0.xsd
                    return normalizedPrefix + nsSchemas.iterator().next().getName();
                }
            }

            return null;
        }

        /** spring-aop-2.5.xsd?-2.5.xsd */
        private String getVersionedExtension(String systemId) {
            if (systemId != null) {
                int dashIndex = systemId.lastIndexOf("-");
                int slashIndex = systemId.lastIndexOf("/");

                if (dashIndex > slashIndex) {
                    return systemId.substring(dashIndex);
                }
            }

            return null;
        }
    };
}

From source file:com.flaptor.hounder.searcher.OpenSearch.java

License:Apache License

/**
 * Creates a OpenSearch's compatible DOM document.
 * The generated dom contains only valid xml characters (infringing chars are removed).
 * Compliant with OpenSearch 1.0 with most of the Nutch 0.8.1 extensions.
 * @param baseUrl the url of the webapp//  w  w w .  j av a  2 s.  co  m
 * @param htmlSearcher the name of the component (servlet/jsp) that returns the search results in an HTML page
 * @param opensearchSearcher the name of the component (servlet/jsp) that returns the search results in an OpenSearch RSS page
 * @param extraParams the parameters present in the request, not passed explicitly (such as sort, reverse, etc.)
 * @param queryString the query string, as entered by the user
 * @param start the offset of the first result
 * @param count the number of results requested (the actual number of results found may be smaller)
 * @param sr the SearchResults structure containing the result of performing the query
 * @return a DOM document
 * <br>An empty sr argument means that no results were found.
 */
public static final Document buildDom_1_0(String baseUrl, String htmlSearcher, String opensearchSearcher,
        String extraParams, String queryString, int start, int count, GroupedSearchResults sr, int status,
        String statusMessage, boolean useXslt) {

    String encodedQuery = null;
    try {
        encodedQuery = URLEncoder.encode(queryString, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        // Should never happen!
        encodedQuery = "";
    }
    Document dom = DocumentHelper.createDocument();
    if (useXslt) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("type", "text/xsl");
        map.put("href", xsltPath);
        dom.addProcessingInstruction("xml-stylesheet", map);
    }

    Namespace opensearchNs = DocumentHelper.createNamespace("opensearch", XMLNS_A9_OPENSEARCH_1_0);
    Namespace hounderNs = DocumentHelper.createNamespace("hounder", XMLNS_HOUNDER_OPENSEARCH_1_0);
    Element root;
    Element channel;
    if (!useXslt) {
        root = dom.addElement("rss").addAttribute("version", "2.0");
        channel = root.addElement("channel");
    } else {
        channel = dom.addElement("searchResults");
        root = channel;
    }
    root.add(opensearchNs);
    root.add(hounderNs);

    channel.addElement("title").addText(titlePrefix + " " + DomUtil.filterXml(queryString));
    channel.addElement("link")
            .addText(baseUrl + "/" + htmlSearcher + "?query=" + encodedQuery + "&start=" + start + extraParams);
    channel.addElement("description").addText(descPrefix + " " + DomUtil.filterXml(queryString));
    channel.addElement(QName.get("totalResults", opensearchNs))
            .addText(Integer.toString(sr.totalGroupsEstimation()));
    channel.addElement(QName.get("startIndex", opensearchNs)).addText(Integer.toString(start));
    channel.addElement(QName.get("itemsPerPage", opensearchNs)).addText(Integer.toString(count));
    channel.addElement(QName.get("query", hounderNs)).addText(DomUtil.filterXml(queryString));
    AQuery suggestedQuery = sr.getSuggestedQuery();
    if (null != suggestedQuery) {
        channel.addElement(QName.get("suggestedQuery", hounderNs))
                .addText(DomUtil.filterXml(suggestedQuery.toString()));
    }
    channel.addElement(QName.get("status", hounderNs)).addText(Integer.toString(status));
    channel.addElement(QName.get("statusDesc", hounderNs)).addText(statusMessage);
    if (sr.lastDocumentOffset() > 0) {
        channel.addElement(QName.get("nextPage", hounderNs)).addText(baseUrl + "/" + opensearchSearcher
                + "?query=" + encodedQuery + "&start=" + (sr.lastDocumentOffset()) + extraParams);
    }

    for (int i = 0; i < sr.groups(); i++) {
        Vector<org.apache.lucene.document.Document> docs = sr.getGroup(i).last();
        Element parent = null;
        for (int j = 0; j < docs.size(); j++) {
            org.apache.lucene.document.Document doc = sr.getGroup(i).last().get(j);
            if (0 == j) {// j=0 is head of group. j>0 is tail
                parent = createAndAddElement(doc, channel, hounderNs);
            } else {
                createAndAddElement(doc, parent, hounderNs);
            }

        }
    }
    return dom;
}

From source file:com.liferay.portal.xml.SAXReaderImpl.java

License:Open Source License

public Namespace createNamespace(String prefix, String uri) {
    return new NamespaceImpl(DocumentHelper.createNamespace(prefix, uri));
}

From source file:cz.fi.muni.xkremser.editor.server.newObject.MonographBuilder.java

License:Open Source License

private void updateDcDoc(Document dcDoc, String pid, String signature, String sysno, DigitalObjectModel model) {
    Element dcRootEl = dcDoc.getRootElement();
    Attribute schemaLoc = dcRootEl.attribute("schemaLocation");
    dcRootEl.remove(schemaLoc);/*from   w ww. j ava  2  s .  c  o  m*/
    Namespace xsi = DocumentHelper.createNamespace("xsi2", FedoraNamespaces.SCHEMA_NAMESPACE_URI);
    dcRootEl.add(xsi);
    dcRootEl.addAttribute(new QName("schemaLocation", xsi),
            "http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd");

    XPath typeXpath = Dom4jUtils.createXPath("/oai_dc:dc/dc:identifier");
    List<? extends Node> nodes = typeXpath.selectNodes(dcDoc);
    for (Node node : nodes) {
        node.detach();
    }
    Element idUuid = dcRootEl.addElement("dc:identifier");
    idUuid.addText(pid);

    for (Node node : nodes) {
        if (node.getText() != null && !"".equals(node.getText().trim())
                && !node.getText().contains(Constants.FEDORA_UUID_PREFIX)) {
            Element temp = dcRootEl.addElement("dc:identifier");
            temp.addText(node.getText());
        }
    }

    if (signature != null) {
        Element idSignature = dcRootEl.addElement("dc:identifier");
        idSignature.addText("signature:" + signature);
    }
    if (sysno != null) {
        Element idSysno = dcRootEl.addElement("dc:identifier");
        idSysno.addText("sysno:" + sysno);
    }
    removeDcTypeElements(dcDoc);
    Element typeEl = dcRootEl.addElement("dc:type");
    typeEl.addText("model:" + model.toString());
    Element rightsEl = dcRootEl.addElement("dc:rights");
    rightsEl.addText("policy:" + Policy.PUBLIC.toString().toLowerCase());
    updateDcLanguages(dcDoc);
}

From source file:cz.fi.muni.xkremser.editor.server.newObject.PeriodicalBuilder.java

License:Open Source License

private void updateDcDoc(Document dcDoc, String pid, String signature, String sysno, DigitalObjectModel model) {
    Element dcRootEl = dcDoc.getRootElement();
    Attribute schemaLoc = dcRootEl.attribute("schemaLocation");
    dcRootEl.remove(schemaLoc);//from   w ww  .j av  a  2 s.co m
    Namespace xsi = DocumentHelper.createNamespace("xsi2", FedoraNamespaces.SCHEMA_NAMESPACE_URI);
    dcRootEl.add(xsi);
    dcRootEl.addAttribute(new QName("schemaLocation", xsi),
            "http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd");

    XPath typeXpath = Dom4jUtils.createXPath("/oai_dc:dc/dc:identifier");
    List<? extends Node> nodes = typeXpath.selectNodes(dcDoc);
    for (Node node : nodes) {
        node.detach();
    }
    Element idUuid = dcRootEl.addElement("dc:identifier");
    idUuid.addText(pid);

    for (Node node : nodes) {
        if (node.getText() != null && !"".equals(node.getText().trim())
                && !node.getText().contains(Constants.FEDORA_UUID_PREFIX)) {
            Element temp = dcRootEl.addElement("dc:identifier");
            temp.addText(node.getText());
        }
    }

    if (signature != null) {
        Element idSignature = dcRootEl.addElement("dc:identifier");
        idSignature.addText("signature:" + signature);
    }
    if (sysno != null) {
        Element idSysno = dcRootEl.addElement("dc:identifier");
        idSysno.addText("sysno:" + sysno);
    }
    removeDcTypeElements(dcDoc);
    Element typeEl = dcRootEl.addElement("dc:type");
    typeEl.addText("model:" + model.getValue());
    Element rightsEl = dcRootEl.addElement("dc:rights");
    rightsEl.addText("policy:" + Policy.PUBLIC.toString().toLowerCase());
    updateDcLanguages(dcDoc);
}

From source file:cz.mzk.editor.server.newObject.MonographBuilder.java

License:Open Source License

@SuppressWarnings("unchecked")
private void updateDcDoc(Document dcDoc, String pid, String signature, String sysno, DigitalObjectModel model) {
    Element dcRootEl = dcDoc.getRootElement();
    Attribute schemaLoc = dcRootEl.attribute("schemaLocation");
    dcRootEl.remove(schemaLoc);//  ww w  .  j av a 2s  .c o m
    Namespace xsi = DocumentHelper.createNamespace("xsi2", FedoraNamespaces.SCHEMA_NAMESPACE_URI);
    dcRootEl.add(xsi);
    dcRootEl.addAttribute(new QName("schemaLocation", xsi),
            "http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd");

    XPath typeXpath = Dom4jUtils.createXPath("/oai_dc:dc/dc:identifier");
    List<? extends Node> nodes = typeXpath.selectNodes(dcDoc);
    for (Node node : nodes) {
        node.detach();
    }
    Element idUuid = dcRootEl.addElement("dc:identifier");
    idUuid.addText(pid);

    for (Node node : nodes) {
        if (node.getText() != null && !"".equals(node.getText().trim())
                && !node.getText().contains(Constants.FEDORA_UUID_PREFIX)) {
            Element temp = dcRootEl.addElement("dc:identifier");
            temp.addText(node.getText());
        }
    }

    if (signature != null) {
        Element idSignature = dcRootEl.addElement("dc:identifier");
        idSignature.addText("signature:" + signature);
    }
    if (sysno != null) {
        Element idSysno = dcRootEl.addElement("dc:identifier");
        idSysno.addText("sysno:" + sysno);
    }
    removeDcTypeElements(dcDoc);
    Element typeEl = dcRootEl.addElement("dc:type");
    typeEl.addText("model:" + model.getValue());
    Element rightsEl = dcRootEl.addElement("dc:rights");
    rightsEl.addText("policy:" + getPolicy().toString().toLowerCase());
    updateDcLanguages(dcDoc);
}

From source file:itensil.repository.web.ShellServlet.java

License:Open Source License

/**
 *  /getProps/*from   w w  w .  ja v a2 s. c o m*/
 *
 * Get node properties
 *
 */
@ContentType("text/xml")
public void webGetProps(HttpServletRequest request, HttpServletResponse response) throws Exception {

    String uri = request.getParameter("uri");
    if (!(Check.isEmpty(uri) || uri.length() < 2)) {

        RepositoryHelper.beginTransaction();
        RepositoryHelper.useReadOnly();
        uri = RepositoryHelper.resolveUri(uri);
        MutableRepositoryNode node = getNode(uri);
        NodeProperties props = node.getProperties(new DefaultNodeVersion());
        Document doc = DocumentHelper.createDocument();
        Element root = doc.addElement("properties");
        Namespace davNs = DocumentHelper.createNamespace(PropertyHelper.DEFAULT_PREFIX,
                PropertyHelper.DEFAULT_QNAMESPACE);
        root.add(davNs);
        root.add(DocumentHelper.createNamespace(PropertyHelper.ITENSIL_PREFIX,
                PropertyHelper.ITENSIL_QNAMESPACE));
        root.add(DocumentHelper.createNamespace(PropertyHelper.ITENSIL_ENTITY_PREFIX,
                PropertyHelper.ITENSIL_ENTITY_QNAMESPACE));
        root.addAttribute("uri", node.getUri());
        root.addElement(new org.dom4j.QName("displayname", davNs)).addText(UriHelper.name(uri));
        if (node.isCollection()) {
            root.addElement(new org.dom4j.QName("collection", davNs));
        }
        int nsCount = 0;
        if (props != null) {
            for (Map.Entry<QName, String> prop : props.getPropertyMap().entrySet()) {
                Namespace ns = root.getNamespaceForURI(prop.getKey().getNamespaceURI());
                if (ns == null) {
                    nsCount++;
                    root.addNamespace(prop.getKey().getNamespaceURI(), "ns" + nsCount);
                }
                Element pElem = root.addElement(new org.dom4j.QName(prop.getKey().getLocalPart(), ns));
                String val = prop.getValue();
                if (val != null)
                    pElem.addText(val);
            }
        }
        RepositoryHelper.commitTransaction();
        ServletUtil.setExpired(response);
        doc.write(response.getWriter());
    } else {
        throw new NotFoundException("[blank]");
    }
}

From source file:net.contextfw.web.application.component.DOMBuilder.java

License:Apache License

public DOMBuilder(String rootName, AttributeSerializer<Object> serializer, ComponentBuilder componentBuilder,
        Collection<KeyValue<String, String>> namespaces) {

    this.serializer = serializer;
    root = DocumentHelper.createElement(rootName);
    document = DocumentHelper.createDocument();
    document.setRootElement(root);//from   w w w .j av a 2s .  com
    for (KeyValue<String, String> namespace : namespaces) {
        root.add(DocumentHelper.createNamespace(namespace.getKey(), namespace.getValue()));
    }

    this.componentBuilder = componentBuilder;
}