Example usage for javax.xml.namespace NamespaceContext getPrefix

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

Introduction

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

Prototype

String getPrefix(String namespaceURI);

Source Link

Document

Get prefix bound to Namespace URI in the current scope.

Usage

From source file:Main.java

/**
 * Builds an XPath string referencing the given node relative to it's parent.
 * /*from   w  w w . ja  v  a 2  s  .  c  o m*/
 * @param node
 * @param context namespace context used to determine correct namespace prefixes, see
 *            {@link SignavioNamespaceContext}
 * @return a relative XPath string or null (if no node given)
 */
private static String getNodeString(Node node, NamespaceContext context) {
    if (node == null) {
        return null;
    }

    // get qualified name
    String nodeName = node.getLocalName();
    if (nodeName == null)
        nodeName = node.getNodeName();

    if (node.getNamespaceURI() != null) {
        String prefix = context.getPrefix(node.getNamespaceURI());
        nodeName = prefix + ":" + node.getLocalName();
    }

    if (node instanceof Attr) {
        return "@" + nodeName;
    } else if (node instanceof Text) {
        nodeName = "text()";
    }

    // determine position
    Node current = node;
    while (current.getPreviousSibling() != null) {
        current = current.getPreviousSibling();
    }
    int position = 1;

    while (current != node) {
        if (current.getNodeName().equals(node.getNodeName()))
            position++;
        current = current.getNextSibling();
    }

    return nodeName + "[" + position + "]";
}

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

public static String getPath(Stack<QName> stack, NamespaceContext ctx) {
    if (ctx == null)
        logger.fatal("NamespaceContext is null");
    StringBuilder ret = new StringBuilder();
    for (QName q : stack) {
        if (q == null)
            throw new IllegalStateException("q is null");
        ret.append("/");
        String prefix = ctx.getPrefix(q.getNamespaceURI());
        if (prefix != null && prefix.length() > 0)
            ret.append(prefix).append(":");
        ret.append(q.getLocalPart());//from w  ww  .jav a  2  s .  c o m
    }
    return ret.toString();
}

From source file:Main.java

public static String getXPathForElement(Node e, NamespaceContext ctx) {
    StringBuffer sb = new StringBuffer();
    List<Node> path = new ArrayList<Node>();

    Node currentNode = e;// w  ww .  ja v a 2  s.c  o  m
    while (currentNode.getParentNode() != currentNode.getOwnerDocument()) {
        path.add(0, currentNode);
        if (currentNode instanceof Attr) {
            Attr a = (Attr) currentNode;
            currentNode = a.getOwnerElement();
        } else {
            currentNode = currentNode.getParentNode();
        }
    }
    path.add(0, currentNode); // We need the root element

    for (Node n : path) {
        sb.append("/");

        if (n.getNodeType() == Node.ATTRIBUTE_NODE) {
            sb.append("@");
        }

        String namespaceURI = n.getNamespaceURI();
        if (namespaceURI != null && !namespaceURI.equals("")) {
            sb.append(ctx.getPrefix(namespaceURI)).append(":");
        }
        sb.append(n.getLocalName());

        if (n.getNodeType() == Node.ELEMENT_NODE) {
            appendElementQualifier(sb, (Element) n);
        }
    }

    return sb.toString();
}

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/* w  w w. j av  a 2s.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:gov.nij.bundles.intermediaries.ers.EntityResolutionServiceIntermediaryTest.java

@Before
public void setUp() throws Exception {

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

        @Override// w w  w  .j ava 2  s. c om
        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:eu.esdihumboldt.hale.io.xslt.XslTransformationUtil.java

/**
 * Create a XPath statement to select instances specified by the given type
 * entity definition./*w  ww  .  ja  v  a2 s  . c o  m*/
 * 
 * @param ted the type entity definition
 * @param context the context for the XPath expression, e.g. the empty
 *            string for the document root or <code>/</code> for anywhere in
 *            the document
 * @param namespaces the namespace context
 * @return the XPath expression or <code>null</code> if there are no
 *         elements that match the type
 */
public static String selectInstances(TypeEntityDefinition ted, String context, NamespaceContext namespaces) {
    TypeDefinition type = ted.getDefinition();

    // get the XML elements associated to the type
    XmlElements elements = type.getConstraint(XmlElements.class);

    if (elements.getElements().isEmpty()) {
        /*
         * XXX dirty hack
         * 
         * In CityGML 1.0 no element for AppearanceType is defined, only a
         * property that is not detected in this way. The source route
         * element is not known here, so we also cannot do a search based on
         * the type. Thus for now we handle it as a special case.
         */
        QName typeName = ted.getDefinition().getName();
        if ("http://www.opengis.net/citygml/appearance/1.0".equals(typeName.getNamespaceURI())
                && "AppearanceType".equals(typeName.getLocalPart())) {
            // create a dummy XML element
            elements = new XmlElements();
            elements.addElement(
                    new XmlElement(new QName("http://www.opengis.net/citygml/appearance/1.0", "Appearance"),
                            ted.getDefinition(), null));
        } else
            // XXX dirty hack end
            return null;
    }

    // XXX which elements should be used?
    // for now use all elements
    StringBuilder select = new StringBuilder();
    boolean first = true;
    for (XmlElement element : elements.getElements()) {
        if (first) {
            first = false;
        } else {
            select.append(" | ");
        }

        select.append(context);
        select.append('/');
        String ns = element.getName().getNamespaceURI();
        if (ns != null && !ns.isEmpty()) {
            String prefix = namespaces.getPrefix(ns);
            if (prefix != null && !prefix.isEmpty()) {
                select.append(prefix);
                select.append(':');
            }
        }
        select.append(element.getName().getLocalPart());
    }

    // filter
    if (ted.getFilter() != null) {
        String filterxpath = FilterToXPath.toXPath(ted.getDefinition(), namespaces, ted.getFilter());

        if (filterxpath != null && !filterxpath.isEmpty()) {
            select.insert(0, '(');
            select.append(")[");
            select.append(StringEscapeUtils.escapeXml(filterxpath));
            select.append(']');
        }
    }

    return select.toString();
}

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// w  w w .  j a v a  2  s.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:com.esri.gpt.server.csw.provider3.GetRecordsProvider.java

/**
 * Translates namespaces./*ww w.j  ava2 s .  c  o m*/
 * @param parsed parsed namespaces
 * @param namespaces available namespaces
 */
protected void translateNamespaces(String[] parsed, List<String[]> namespaces) {
    if (parsed != null && namespaces != null) {
        NamespaceContext namespaceContext = CswNamespaces.CSW_30.makeNamespaceContext();
        for (int i = 0; i < parsed.length; i++) {
            String name = parsed[i];
            String[] el = name.split(":");
            if (el.length == 2) {
                String pfx = el[0];
                for (String[] namespace : namespaces) {
                    if (namespace[1].equals(pfx)) {
                        String uri = namespace[0];
                        String defPfx = namespaceContext.getPrefix(uri);
                        if (defPfx != null) {
                            name = defPfx + ":" + el[1];
                            break;
                        }
                    }
                }
            }
            parsed[i] = name;
        }
    }
}

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 a v a 2s .  c o  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.slc.sli.modeling.tools.xsdgen.Uml2XsdWriter.java

private static final String typeLexicalName(final QName name, final XMLStreamWriter context) {
    final NamespaceContext namespaceContext = context.getNamespaceContext();
    final String namespace = name.getNamespaceURI();
    if (namespace.length() > 0) {
        final String prefix = namespaceContext.getPrefix(namespace);
        if (prefix == null || prefix.length() == 0) {
            return name.getLocalPart();
        } else {/*from  w  ww. j a  v a 2  s.c o  m*/
            return prefix.concat(":").concat(name.getLocalPart());
        }
    } else {
        return name.getLocalPart();
    }
}