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:org.apache.axiom.om.impl.util.OMSerializerUtil.java

/**
 * @param prefix /*from  www .j  a v a  2 s. com*/
 * @param namespace
 * @param writer
 * @return true if the prefix is associated with the namespace in the current context
 */
public static boolean isAssociated(String prefix, String namespace, XMLStreamWriter writer)
        throws XMLStreamException {

    // The "xml" prefix is always (implicitly) associated. Returning true here makes sure that
    // we never write a declaration for the xml namespace. See WSCOMMONS-281 for a discussion
    // of this issue.
    if ("xml".equals(prefix)) {
        return true;
    }

    // NOTE: Calling getNamespaceContext() on many XMLStreamWriter implementations is expensive.
    // Please use other writer methods first.

    // For consistency, convert null arguments.
    // This helps get around the parser implementation differences.
    // In addition, the getPrefix/getNamespace methods cannot be called with null parameters.
    prefix = (prefix == null) ? "" : prefix;
    namespace = (namespace == null) ? "" : namespace;

    if (namespace.length() > 0) {
        // QUALIFIED NAMESPACE
        // Get the namespace associated with the prefix
        String writerPrefix = writer.getPrefix(namespace);
        if (prefix.equals(writerPrefix)) {
            return true;
        }

        // It is possible that the namespace is associated with multiple prefixes,
        // So try getting the namespace as a second step.
        if (writerPrefix != null) {
            NamespaceContext nsContext = writer.getNamespaceContext();
            if (nsContext != null) {
                String writerNS = nsContext.getNamespaceURI(prefix);
                return namespace.equals(writerNS);
            }
        }
        return false;
    } else {
        // UNQUALIFIED NAMESPACE

        // Cannot associate a prefix with an unqualifed name.
        // However sometimes axiom creates a fake prefix name if xmns="" is not in effect.
        // So return true
        if (prefix.length() > 0) {
            return true;
        }

        // Get the namespace associated with the prefix.
        // It is illegal to call getPrefix with null, but the specification is not
        // clear on what happens if called with "".  So the following code is 
        // protected
        try {
            String writerPrefix = writer.getPrefix("");
            if (writerPrefix != null && writerPrefix.length() == 0) {
                return true;
            }
        } catch (Throwable t) {
            if (DEBUG_ENABLED) {
                log.debug("Caught exception from getPrefix(\"\"). Processing continues: " + t);
            }
        }

        // Fallback to using the namespace context
        NamespaceContext nsContext = writer.getNamespaceContext();
        if (nsContext != null) {
            String writerNS = nsContext.getNamespaceURI("");
            if (writerNS != null && writerNS.length() > 0) {
                return false;
            }
        }
        return true;
    }
}

From source file:org.apache.axis2.databinding.utils.ConverterUtil.java

public static Object getAnyTypeObject(XMLStreamReader xmlStreamReader, Class extensionMapperClass)
        throws XMLStreamException {
    Object returnObject = null;/*  w  ww  .j a v  a2 s  .c o m*/

    // make sure reader is at the first element.
    while (!xmlStreamReader.isStartElement()) {
        xmlStreamReader.next();
    }
    // first check whether this element is null or not
    String nillableValue = xmlStreamReader.getAttributeValue(Constants.XSI_NAMESPACE, "nil");
    if ("true".equals(nillableValue) || "1".equals(nillableValue)) {
        returnObject = null;
        xmlStreamReader.next();
    } else {
        String attributeType = xmlStreamReader.getAttributeValue(Constants.XSI_NAMESPACE, "type");
        if (attributeType != null) {
            String attributeTypePrefix = "";
            if (attributeType.indexOf(":") > -1) {
                attributeTypePrefix = attributeType.substring(0, attributeType.indexOf(":"));
                attributeType = attributeType.substring(attributeType.indexOf(":") + 1);
            }
            NamespaceContext namespaceContext = xmlStreamReader.getNamespaceContext();
            String attributeNameSpace = namespaceContext.getNamespaceURI(attributeTypePrefix);

            if (Constants.XSD_NAMESPACE.equals(attributeNameSpace)) {
                if ("base64Binary".equals(attributeType)) {
                    returnObject = XMLStreamReaderUtils.getDataHandlerFromElement(xmlStreamReader);
                } else {
                    String attribValue = xmlStreamReader.getElementText();
                    if (attribValue != null) {
                        if (attributeType.equals("string")) {
                            returnObject = attribValue;
                        } else if (attributeType.equals("int")) {
                            returnObject = new Integer(attribValue);
                        } else if (attributeType.equals("QName")) {
                            String namespacePrefix = null;
                            String localPart = null;
                            if (attribValue.indexOf(":") > -1) {
                                namespacePrefix = attribValue.substring(0, attribValue.indexOf(":"));
                                localPart = attribValue.substring(attribValue.indexOf(":") + 1);
                                returnObject = new QName(namespaceContext.getNamespaceURI(namespacePrefix),
                                        localPart);
                            }
                        } else if ("boolean".equals(attributeType)) {
                            returnObject = new Boolean(attribValue);
                        } else if ("anyURI".equals(attributeType)) {
                            try {
                                returnObject = new URI(attribValue);
                            } catch (URI.MalformedURIException e) {
                                throw new XMLStreamException("Invalid URI");
                            }
                        } else if ("date".equals(attributeType)) {
                            returnObject = ConverterUtil.convertToDate(attribValue);
                        } else if ("dateTime".equals(attributeType)) {
                            returnObject = ConverterUtil.convertToDateTime(attribValue);
                        } else if ("time".equals(attributeType)) {
                            returnObject = ConverterUtil.convertToTime(attribValue);
                        } else if ("byte".equals(attributeType)) {
                            returnObject = new Byte(attribValue);
                        } else if ("short".equals(attributeType)) {
                            returnObject = new Short(attribValue);
                        } else if ("float".equals(attributeType)) {
                            returnObject = new Float(attribValue);
                        } else if ("long".equals(attributeType)) {
                            returnObject = new Long(attribValue);
                        } else if ("double".equals(attributeType)) {
                            returnObject = new Double(attribValue);
                        } else if ("decimal".equals(attributeType)) {
                            returnObject = new BigDecimal(attribValue);
                        } else if ("unsignedLong".equals(attributeType)) {
                            returnObject = new UnsignedLong(attribValue);
                        } else if ("unsignedInt".equals(attributeType)) {
                            returnObject = new UnsignedInt(attribValue);
                        } else if ("unsignedShort".equals(attributeType)) {
                            returnObject = new UnsignedShort(attribValue);
                        } else if ("unsignedByte".equals(attributeType)) {
                            returnObject = new UnsignedByte(attribValue);
                        } else if ("positiveInteger".equals(attributeType)) {
                            returnObject = new PositiveInteger(attribValue);
                        } else if ("negativeInteger".equals(attributeType)) {
                            returnObject = new NegativeInteger(attribValue);
                        } else if ("nonNegativeInteger".equals(attributeType)) {
                            returnObject = new NonNegativeInteger(attribValue);
                        } else if ("nonPositiveInteger".equals(attributeType)) {
                            returnObject = new NonPositiveInteger(attribValue);
                        } else {
                            throw new ADBException("Unknown type ==> " + attributeType);
                        }
                    } else {
                        throw new ADBException("Attribute value is null");
                    }
                }
            } else {
                try {
                    Method getObjectMethod = extensionMapperClass.getMethod("getTypeObject",
                            new Class[] { String.class, String.class, XMLStreamReader.class });
                    returnObject = getObjectMethod.invoke(null,
                            new Object[] { attributeNameSpace, attributeType, xmlStreamReader });
                } catch (NoSuchMethodException e) {
                    throw new ADBException(
                            "Can not find the getTypeObject method in the " + "extension mapper class ", e);
                } catch (IllegalAccessException e) {
                    throw new ADBException(
                            "Can not access the getTypeObject method in the " + "extension mapper class ", e);
                } catch (InvocationTargetException e) {
                    throw new ADBException(
                            "Can not invoke the getTypeObject method in the " + "extension mapper class ", e);
                }

            }

        } else {
            throw new ADBException("Any type element type has not been given");
        }
    }
    return returnObject;
}

From source file:org.openengsb.openengsbplugin.tools.Tools.java

/**
 * Insert dom node into {@code parentDoc} at the given {@code xpath} (if this path doesnt exist, the elements are
 * created). Note: text content of nodes and attributes aren't considered.
 *///from ww w. j  av a2 s.  c o m
public static void insertDomNode(Document parentDoc, Node nodeToInsert, String xpath,
        NamespaceContext nsContext) throws XPathExpressionException {
    LOG.trace("insertDomNode() - start");
    String[] tokens = xpath.split("/");
    String currPath = "";
    Node parent = null;
    for (int i = 0; i < tokens.length; i++) {
        if (tokens[i].matches("[\\s]*")) {
            continue;
        }
        LOG.trace(String.format("parent = %s", parent == null ? "null" : parent.getLocalName()));
        currPath += "/" + tokens[i];
        Node result = Tools.evaluateXPath(currPath, parentDoc, nsContext, XPathConstants.NODE, Node.class);
        LOG.trace(String.format("result empty: %s", result == null));
        if (result == null) {
            String elemName = null;
            // attribute filter
            elemName = tokens[i].replaceAll("\\[.*\\]", "");

            Element element = null;

            if (elemName.contains(":")) {
                String[] elemenNameTokens = elemName.split(":");
                String prefix = elemenNameTokens[0];
                elemName = elemenNameTokens[1];
                element = parentDoc.createElementNS(nsContext.getNamespaceURI(prefix), elemName);
            } else {
                element = parentDoc.createElement(elemName);
            }
            LOG.trace(String.format("elementName: %s", elemName));
            parent.appendChild(element);
            result = element;
        }
        parent = result;
    }
    LOG.trace("finally inserting the node..");
    LOG.trace(String.format("parent node: %s", parent == null ? "null" : parent.getLocalName()));
    LOG.trace(
            String.format("node to insert = %s", nodeToInsert == null ? "null" : nodeToInsert.getLocalName()));
    parent.appendChild(nodeToInsert);
    LOG.trace("insertDomNode() - end");
}

From source file:org.slc.sli.modeling.xml.IndentingXMLStreamWriterTest.java

@Before
public void setup() throws XMLStreamException {
    outputStream = new ByteArrayOutputStream();
    streamWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(outputStream, "UTF-8");
    out = new IndentingXMLStreamWriter(streamWriter);
    out.setDefaultNamespace(DEFAULT_NAMESPACE);
    out.setPrefix(DEFAULT_PREFIX, DEFAULT_NAMESPACE);
    out.setPrefix(PREFIX, NAMESPACE);// w w w  .j a v  a2  s  .c o m

    NamespaceContext context = mock(NamespaceContext.class);
    when(context.getNamespaceURI(anyString())).thenReturn(NAMESPACE);
    out.setNamespaceContext(context);
}

From source file:org.slc.sli.modeling.xml.IndentingXMLStreamWriterTest.java

@Test
public void testGetNamespaceContext() {
    NamespaceContext context = out.getNamespaceContext();
    assertTrue(context.getNamespaceURI(NAMESPACE).equals(NAMESPACE));
}

From source file:org.xchain.framework.jxpath.JXPathValidator.java

static void validatePrefix(String prefix, NamespaceContext xmlns) {
    if ((prefix != null) && (!XMLConstants.DEFAULT_NS_PREFIX.equals(prefix))
            && XMLConstants.NULL_NS_URI.equals(xmlns.getNamespaceURI(prefix))) {
        throw new JXPathException("The prefix '" + prefix + "' is not defined in the current context.");
    }//from   w  w  w  . j  av a 2s.  c o m
}

From source file:org.xchain.framework.util.JXPathContextUtil.java

public static void validate(String value, NamespaceContext namespaceContext) {
    Matcher matcher = uriLocalNamePattern.matcher(value);
    if (matcher.matches()) {
        // this is valid, so return.
        return;/*from   ww  w .j  a v  a 2  s .  c o  m*/
    }

    matcher = prefixLocalNamePattern.matcher(value);
    if (matcher.matches()) {
        String prefix = matcher.group(1);

        if (prefix != null && !XMLConstants.DEFAULT_NS_PREFIX.equals(prefix)
                && XMLConstants.NULL_NS_URI.equals(namespaceContext.getNamespaceURI(prefix))) {
            throw new JXPathException(
                    "There is not namespace mapping for the prefix of qname '" + value + "'.");
        }
        return;
    }

    matcher = localNamePattern.matcher(value);
    if (matcher.matches()) {
        return;
    }

    throw new JXPathException("There is a syntax error in the qname '" + value + "'.");
}