Example usage for javax.xml.namespace NamespaceContext getNamespaceURI

List of usage examples for javax.xml.namespace NamespaceContext getNamespaceURI

Introduction

In this page you can find the example usage for javax.xml.namespace NamespaceContext getNamespaceURI.

Prototype

String getNamespaceURI(String prefix);

Source Link

Document

Get Namespace URI bound to a prefix in the current scope.

Usage

From source file:Main.java

private static String getValidXpath(String xPath, NamespaceContext context) {
    if (context == null)
        return xPath;
    String namespaceURI = context.getNamespaceURI(DEFAULT_NS);
    // check if there is any default namespace
    if (namespaceURI != null && !namespaceURI.isEmpty()) {
        StringBuilder stringBuilder = new StringBuilder();
        String[] tags = xPath.split("/");
        int length = tags.length;
        for (int i = 0; i < length - 1; i++) {
            createNodeXPath(stringBuilder, tags[i]);
            stringBuilder.append("/");
        }//from   w w  w  . j a v  a2s.c  om
        createNodeXPath(stringBuilder, tags[length - 1]);
        return stringBuilder.toString();
    }
    return xPath;
}

From source file:Main.java

public static QName getXmlQName(final NamespaceContext context, final String value) {
    if (value == null) {
        return null;
    } else {/*  www. jav  a 2 s. c  o m*/
        final int colonIndex = value.indexOf(':');
        if (colonIndex == -1) {
            return new QName(value);
        } else {
            final String prefix = value.substring(0, colonIndex);
            final String name = value.substring(colonIndex + 1);
            final String namespaceUri = context.getNamespaceURI(prefix);
            return new QName(namespaceUri, name, prefix);
        }
    }
}

From source file:fr.gouv.finances.dgfip.xemelios.utils.XmlUtils.java

/**
 * For the moment, this method can only transform very simple XPath, like <tt>/n:foo/b:bar/@a</tt>
 * @param xpath/*from w  ww .j  a  v a2  s  . c o m*/
 * @param ns
 * @return
 */
public static String normalizeNS(String xpath, NamespaceContext ns) {
    StringTokenizer tokenizer = new StringTokenizer(xpath, "/", true);
    StringBuilder sb = new StringBuilder();
    while (tokenizer.hasMoreTokens()) {
        String token = tokenizer.nextToken();
        if (token.equals("/"))
            sb.append(token);
        else {
            boolean isAttribute = false;
            if (token.startsWith("@")) {
                token = token.substring(1);
                isAttribute = true;
            }
            int pos = token.indexOf(':');
            if (pos >= 0) {
                String prefix = token.substring(0, pos);
                String localName = token.substring(pos + 1);
                String newPrefix = ns.getPrefix(ns.getNamespaceURI(prefix));
                if (isAttribute && (newPrefix == null || newPrefix.length() == 0))
                    newPrefix = prefix;
                if (isAttribute)
                    sb.append("@");
                if (newPrefix.length() > 0)
                    sb.append(newPrefix).append(":");
                sb.append(localName);
            } else {
                if (!isAttribute) {
                    String localName = token;
                    if (XmlUtils.isValidNCName(localName)) {
                        String uri = ns.getNamespaceURI("");
                        if (uri != null) {
                            String newPrefix = ns.getPrefix(uri);
                            if (newPrefix.length() > 0)
                                sb.append(newPrefix).append(":");
                        }
                        sb.append(token);
                    } else {
                        sb.append(token);
                    }
                } else {
                    // attribute didn't had a namespace, let it like that
                    sb.append("@").append(token);
                }
            }
        }
    }
    return sb.toString();
}

From source file:jp.go.nict.langrid.bpel.entity.PartnerLink.java

/**
 * /* www.j  a v  a2s .co m*/
 * 
 */
public PartnerLink(NamespaceContext context, Node partnerLinkNode) {
    NamedNodeMap attrs = partnerLinkNode.getAttributes();
    setName(getAttr(attrs, "name"));
    setMyRole(getAttr(attrs, "myRole"));
    setPartnerRole(getAttr(attrs, "partnerRole"));
    String[] plts = getAttr(attrs, "partnerLinkType").split(":", 2);
    if (plts.length == 2) {
        String uri = context.getNamespaceURI(plts[0]);
        if (uri == null) {
            uri = plts[0];
            logger.warning(
                    "failed to resolve namespace prefix \"" + plts[0] + "\" for element \"" + plts[1] + "\"");
        }
        setPartnerLinkType(new QName(uri, plts[1]));
    } else {
        setPartnerLinkType(new QName(plts[0]));
    }
}

From source file:org.callimachusproject.rdfa.test.RDFaGenerationTest.java

XPathExpression conjoinXPaths(Document fragment, String base) throws Exception {
    String path = "//*";
    final Element e = fragment.getDocumentElement();
    if (e == null)
        return null;
    final XPathIterator conjunction = new XPathIterator(e, base);
    if (conjunction.hasNext()) {
        path += "[";
        boolean first = true;
        while (conjunction.hasNext()) {
            if (!first)
                path += " and ";
            XPathExpression x = conjunction.next();
            String exp = x.toString();
            boolean positive = true;
            if (exp.startsWith("-")) {
                positive = false;/*from ww w  .  j  a  va 2s .c o m*/
                exp = exp.substring(1);
            }
            // remove the initial '/'
            exp = exp.substring(1);
            if (positive)
                path += exp;
            else
                path += "not(" + exp + ")";
            first = false;
        }
        path += "]";
    }
    XPath xpath = xPathFactory.newXPath();
    // add namespace prefix resolver to the xpath based on the current element
    xpath.setNamespaceContext(new AbstractNamespaceContext() {
        public String getNamespaceURI(String prefix) {
            // for the empty prefix lookup the default namespace
            if (prefix.isEmpty())
                return e.lookupNamespaceURI(null);
            for (int i = 0; i < conjunction.contexts.size(); i++) {
                NamespaceContext c = conjunction.contexts.get(i);
                String ns = c.getNamespaceURI(prefix);
                if (ns != null)
                    return ns;
            }
            return null;
        }
    });
    final String exp = path;
    final XPathExpression compiled = xpath.compile(path);
    if (verbose)
        System.out.println(exp);

    return new XPathExpression() {
        public String evaluate(Object source) throws XPathExpressionException {
            return compiled.evaluate(source);
        }

        public String evaluate(InputSource source) throws XPathExpressionException {
            return compiled.evaluate(source);
        }

        public Object evaluate(Object source, QName returnType) throws XPathExpressionException {
            return compiled.evaluate(source, returnType);
        }

        public Object evaluate(InputSource source, QName returnType) throws XPathExpressionException {
            return compiled.evaluate(source, returnType);
        }

        public String toString() {
            return exp;
        }
    };
}

From source file:eu.semaine.util.XMLTool.java

/**
 * Create an XML document from the given XPath expression.
 * The given string is interpreted as a limited subset of XPath expressions and split into parts.
 * Each part except the last one is expected to follow precisely the following form:
 * <code>"/" ( prefix ":" ) ? localname ( "[" "@" attName "=" "'" attValue "'" "]" ) ?</code>
 * The last part must be either//  ww w. java2s .c  o m
 * <code> "/" "text()"</code>
 * or
 * </code> "/" "@" attributeName </code>.
 * @param xpathExpression an xpath expression from which the given document can be created. must not be null.
 * @param value the value to insert at the location identified by the xpath expression. if this is null, the empty string is added.
 * @param namespaceContext the namespace context to use for resolving namespace prefixes.
 *  If this is null, the namespace context returned by {@link #getDefaultNamespaceContext()} will be used.
 * @param document if not null, the xpath expression + value pair will be added to the document. 
 * If null, a new document will be created from the xpathExpression and value pair.
 * @return a document containing the given information
 * @throws NullPointerException if xpathExpression is null.
 * @throws IllegalArgumentException if the xpath expression is not valid, or if the xpath expression is incompatible with the given document (e.g., different root node) 
 */
public static Document xpath2doc(String xpathExpression, String value, NamespaceContext namespaceContext,
        Document document) throws NullPointerException, IllegalArgumentException {
    if (xpathExpression == null) {
        throw new NullPointerException("null argument");
    }
    if (value == null) {
        value = "";
    }
    if (namespaceContext == null) {
        namespaceContext = getDefaultNamespaceContext();
    }
    String[][] parts = splitXPathIntoParts(xpathExpression);
    Element currentElt = null;

    for (int i = 0; i < parts.length - 1; i++) {
        String[] part = parts[i];
        assert part != null;
        assert part.length == 4;
        String prefix = part[0];
        String localName = part[1];
        String attName = part[2];
        String attValue = part[3];
        String namespaceURI = prefix != null ? namespaceContext.getNamespaceURI(prefix) : null;
        if (prefix != null && namespaceURI.equals("")) {
            throw new IllegalArgumentException("Unknown prefix: " + prefix);
        }
        // Now traverse to or create element defined by prefix, localName and namespaceURI
        if (currentElt == null) { // at top level
            if (document == null) { // create a new document
                try {
                    document = XMLTool.newDocument(localName, namespaceURI);
                } catch (DOMException de) {
                    throw new IllegalArgumentException("Cannot create document for localname '" + localName
                            + "' and namespaceURI '" + namespaceURI + "'", de);
                }
                currentElt = document.getDocumentElement();
                currentElt.setPrefix(prefix);
            } else {
                currentElt = document.getDocumentElement();
                if (!currentElt.getLocalName().equals(localName)) {
                    throw new IllegalArgumentException(
                            "Incompatible root node specification: expression requests '" + localName
                                    + "', but document already has '" + currentElt.getLocalName() + "'!");
                }
                String currentNamespaceURI = currentElt.getNamespaceURI();
                if (!(currentNamespaceURI == null && namespaceURI == null
                        || currentNamespaceURI != null && currentNamespaceURI.equals(namespaceURI))) {
                    throw new IllegalArgumentException(
                            "Incompatible root namespace specification: expression requests '" + namespaceURI
                                    + "', but document already has '" + currentNamespaceURI + "'!");
                }
            }
        } else { // somewhere in the tree
            // First check if the requested child already exists
            List<Element> sameNameChildren = XMLTool.getChildrenByLocalNameNS(currentElt, localName,
                    namespaceURI);
            boolean found = false;
            if (attName == null) {
                if (sameNameChildren.size() > 0) {
                    currentElt = sameNameChildren.get(0);
                    found = true;
                }
            } else {
                for (Element c : sameNameChildren) {
                    if (c.hasAttribute(attName)) {
                        if (attValue == null || attValue.equals(c.getAttribute(attName))) {
                            currentElt = c;
                            found = true;
                            break;
                        }
                    }
                }
            }
            if (!found) { // need to create it
                currentElt = XMLTool.appendChildElement(currentElt, localName, namespaceURI);
                if (prefix != null)
                    currentElt.setPrefix(prefix);
                if (attName != null) {
                    currentElt.setAttribute(attName, attValue != null ? attValue : "");
                }
            }
        }

    }
    if (currentElt == null) {
        throw new IllegalArgumentException(
                "No elements or no final part created from XPath expression '" + xpathExpression + "'");
    }
    String[] lastPart = parts[parts.length - 1];
    assert lastPart.length <= 1;
    if (lastPart.length == 0) { // text content of the given node
        currentElt.setTextContent(value);
    } else {
        String attName = lastPart[0];
        currentElt.setAttribute(attName, value);
    }
    return document;
}

From source file:gov.nij.bundles.intermediaries.ers.EntityResolutionServiceIntermediaryTest.java

@Before
public void setUp() throws Exception {

    final NamespaceContext baseEntityResolutionNamespaceContext = new EntityResolutionNamespaceContext();
    testNamespaceContext = new NamespaceContext() {

        @Override/*from ww  w  .  ja v  a2s  .c  o m*/
        public String getNamespaceURI(String prefix) {
            if ("ext".equals(prefix)) {
                return "http://local.org/IEPD/Extensions/PersonSearchResults/1.0";
            }
            return baseEntityResolutionNamespaceContext.getNamespaceURI(prefix);
        }

        @Override
        public String getPrefix(String arg0) {
            return baseEntityResolutionNamespaceContext.getPrefix(arg0);
        }

        @SuppressWarnings("rawtypes")
        @Override
        public Iterator getPrefixes(String arg0) {
            return baseEntityResolutionNamespaceContext.getPrefixes(arg0);
        }

    };

    // Advise the person search results endpoint and replace it with a mock endpoint.
    // We then will test this mock endpoint to see if it gets the proper payload.
    context.getRouteDefinitions().get(0).adviceWith(context, new AdviceWithRouteBuilder() {
        @Override
        public void configure() throws Exception {
            // weave the vehicle search results in the route
            // and replace it with the following mock route path
            weaveByToString("To[EntityResolutionResponseEndpoint]").replace()
                    .to("mock:EntityResolutionResponseEndpoint");
            replaceFromWith("direct:entityResolutionRequestServiceEndpoint");
        }
    });

    context.start();

    // We should get one message
    entityResolutionResponseMock.expectedMessageCount(1);

    // Create a new exchange
    senderExchange = new DefaultExchange(context);

    Document doc = createDocument();
    List<SoapHeader> soapHeaders = new ArrayList<SoapHeader>();
    soapHeaders.add(makeSoapHeader(doc, "http://www.w3.org/2005/08/addressing", "MessageID", "12345"));
    soapHeaders.add(makeSoapHeader(doc, "http://www.w3.org/2005/08/addressing", "ReplyTo", "https://reply.to"));
    senderExchange.getIn().setHeader(Header.HEADER_LIST, soapHeaders);

    senderExchange.getIn().setHeader(CxfConstants.OPERATION_NAME, CXF_OPERATION_NAME);
    senderExchange.getIn().setHeader(CxfConstants.OPERATION_NAMESPACE, CXF_OPERATION_NAMESPACE);
}

From source file:gov.nij.bundles.intermediaries.ers.EntityResolutionMessageHandlerTest.java

@Before
public void setUp() throws Exception {
    final NamespaceContext baseEntityResolutionNamespaceContext = new EntityResolutionNamespaceContext();
    testNamespaceContext = new NamespaceContext() {

        @Override//from   w w  w  .j a  v a2s  .c o m
        public String getNamespaceURI(String prefix) {
            if ("ext".equals(prefix)) {
                return "http://local.org/IEPD/Extensions/PersonSearchResults/1.0";
            }
            return baseEntityResolutionNamespaceContext.getNamespaceURI(prefix);
        }

        @Override
        public String getPrefix(String arg0) {
            return baseEntityResolutionNamespaceContext.getPrefix(arg0);
        }

        @SuppressWarnings("rawtypes")
        @Override
        public Iterator getPrefixes(String arg0) {
            return baseEntityResolutionNamespaceContext.getPrefixes(arg0);
        }

    };
    entityResolutionMessageHandler = new EntityResolutionMessageHandler();
    testAttributeParametersMessageInputStream = getClass()
            .getResourceAsStream("/xml/TestAttributeParameters.xml");
    assertNotNull(testAttributeParametersMessageInputStream);
    entityResolutionMessageHandler.setAttributeParametersStream(testAttributeParametersMessageInputStream);
    testRequestMessageInputStream = getClass().getResourceAsStream("/xml/EntityMergeRequestMessage.xml");
    assertNotNull(testRequestMessageInputStream);
}

From source file:sapience.injectors.stax.inject.StringBasedStaxStreamInjector.java

/**
 * Helper method, taking a XML string like <ows:Metadata xmlns:ows=\"http://ogc.org/ows\" xmlns:xlink=\"http://wrc.org/xlink\" 
 * xlink:href=\"http://dude.com\"></ows:Metadata> from the reference 
 * and checks if //from   w  w  w. j  ava 2  s .co m
 * a  the used prefixes match the globally used ones and
 * b) any of the declared namespaces are redundant 
 * 
 * The same is true for the XPath definition
 * 
 * @param resultingXMLString
 * @param context
 */
private void processNamespace(StringBuilder sb, NamespaceContext global, LocalNamespaceContext local) {

    Matcher prefixMatcher = prefixPattern.matcher(sb);
    Matcher nsMatcher = nsPattern.matcher(sb);
    String prefix;
    String uri;

    /* process the local namespaces */
    while (nsMatcher.find()) {
        int start = nsMatcher.start();
        int end = nsMatcher.end();
        StringBuilder sbu = new StringBuilder(sb.substring(start, end));
        String thisPrefix = sbu.substring(sbu.indexOf(":") + 1, sbu.lastIndexOf("="));
        String thisUri = sbu.substring(sbu.indexOf("\"") + 1, sbu.lastIndexOf("\""));
        // add to local namespace context
        local.put(thisPrefix, thisUri);

        if ((prefix = global.getPrefix(thisUri)) != null) {
            // namespace is registered, let's remove it
            sb.delete(start - 1, end);

            // we have to reset, since we changed the state of the matched string with the deletion
            nsMatcher.reset();
        }

    }

    /* change the prefixes */
    try {
        while (prefixMatcher.find()) {
            int start = prefixMatcher.start();
            int end = prefixMatcher.end();

            String localprefix = sb.substring(start + 1, end - 1);
            if ((global.getNamespaceURI(localprefix) == null)
                    && (uri = local.getNamespaceURI(localprefix)) != null) {
                // get the other prefix
                prefix = global.getPrefix(uri);

                if ((prefix != null) && (!(localprefix.contentEquals(prefix)))) {
                    sb.replace(start + 1, end - 1, prefix);
                    prefixMatcher.reset();
                }
            }
        }
    } catch (StringIndexOutOfBoundsException e) {
        // we do nothing here
    }

}

From source file:org.apache.axiom.om.impl.serialize.StreamingOMSerializer.java

/**
 * Generates a unique namespace prefix that is not in the scope of the NamespaceContext
 *
 * @param nsCtxt//from   w w  w.ja v  a 2 s.  c  o m
 * @return string
 */
private String generateUniquePrefix(NamespaceContext nsCtxt) {
    String prefix = NAMESPACE_PREFIX + namespaceSuffix++;
    //null should be returned if the prefix is not bound!
    while (nsCtxt.getNamespaceURI(prefix) != null) {
        prefix = NAMESPACE_PREFIX + namespaceSuffix++;
    }

    return prefix;
}