Example usage for javax.xml.stream XMLStreamWriter getNamespaceContext

List of usage examples for javax.xml.stream XMLStreamWriter getNamespaceContext

Introduction

In this page you can find the example usage for javax.xml.stream XMLStreamWriter getNamespaceContext.

Prototype

public NamespaceContext getNamespaceContext();

Source Link

Document

Returns the current namespace context.

Usage

From source file:Main.java

public static String getDefaultNamespaceURI(final XMLStreamWriter writer) {
    return writer.getNamespaceContext().getNamespaceURI(XMLConstants.DEFAULT_NS_PREFIX);
}

From source file:microsoft.exchange.webservices.data.core.EwsServiceXmlWriter.java

/**
 * @param element DOM element// ww w  .  j  a  v a 2 s. co  m
 * @param writer XML stream writer
 * @throws XMLStreamException the XML stream exception
 */
public static void addElement(Element element, XMLStreamWriter writer) throws XMLStreamException {
    String nameSpace = element.getNamespaceURI();
    String prefix = element.getPrefix();
    String localName = element.getLocalName();
    if (prefix == null) {
        prefix = "";
    }
    if (localName == null) {
        localName = element.getNodeName();

        if (localName == null) {
            throw new IllegalStateException("Element's local name cannot be null!");
        }
    }

    String decUri = writer.getNamespaceContext().getNamespaceURI(prefix);
    boolean declareNamespace = decUri == null || !decUri.equals(nameSpace);

    if (nameSpace == null || nameSpace.length() == 0) {
        writer.writeStartElement(localName);
    } else {
        writer.writeStartElement(prefix, localName, nameSpace);
    }

    NamedNodeMap attrs = element.getAttributes();
    for (int i = 0; i < attrs.getLength(); i++) {
        Node attr = attrs.item(i);

        String name = attr.getNodeName();
        String attrPrefix = "";
        int prefixIndex = name.indexOf(':');
        if (prefixIndex != -1) {
            attrPrefix = name.substring(0, prefixIndex);
            name = name.substring(prefixIndex + 1);
        }

        if ("xmlns".equals(attrPrefix)) {
            writer.writeNamespace(name, attr.getNodeValue());
            if (name.equals(prefix) && attr.getNodeValue().equals(nameSpace)) {
                declareNamespace = false;
            }
        } else {
            if ("xmlns".equals(name) && "".equals(attrPrefix)) {
                writer.writeNamespace("", attr.getNodeValue());
                if (attr.getNodeValue().equals(nameSpace)) {
                    declareNamespace = false;
                }
            } else {
                writer.writeAttribute(attrPrefix, attr.getNamespaceURI(), name, attr.getNodeValue());
            }
        }
    }

    if (declareNamespace) {
        if (nameSpace == null) {
            writer.writeNamespace(prefix, "");
        } else {
            writer.writeNamespace(prefix, nameSpace);
        }
    }

    NodeList nodes = element.getChildNodes();
    for (int i = 0; i < nodes.getLength(); i++) {
        Node n = nodes.item(i);
        writeNode(n, writer);
    }

    writer.writeEndElement();

}

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

/**
 * @param reader/*from  w  w w .j  a  v a 2  s. c o  m*/
 * @param writer
 * @throws XMLStreamException
 */
protected void serializeElement(XMLStreamReader reader, XMLStreamWriter writer) throws XMLStreamException {

    // Note: To serialize the start tag, we must follow the order dictated by the JSR-173 (StAX) specification.
    // Please keep this code in sync with the code in OMSerializerUtil.serializeStartpart

    // The algorithm is:
    // ... generate writeStartElement
    //
    // ... generate setPrefix/setDefaultNamespace for each namespace declaration if the prefix is unassociated.
    // ... generate setPrefix/setDefaultNamespace if the prefix of the element is unassociated
    // ... generate setPrefix/setDefaultNamespace for each unassociated prefix of the attributes.
    //
    // ... generate writeNamespace/writerDefaultNamespace for the new namespace declarations determine during the "set" processing
    // ... generate writeAttribute for each attribute

    ArrayList writePrefixList = null;
    ArrayList writeNSList = null;

    // Get the prefix and namespace of the element.  "" and null are identical.
    String ePrefix = reader.getPrefix();
    ePrefix = (ePrefix != null && ePrefix.length() == 0) ? null : ePrefix;
    String eNamespace = reader.getNamespaceURI();
    eNamespace = (eNamespace != null && eNamespace.length() == 0) ? null : eNamespace;

    // Write the startElement if required
    if (eNamespace != null) {
        if (ePrefix == null) {
            if (!OMSerializerUtil.isAssociated("", eNamespace, writer)) {

                if (writePrefixList == null) {
                    writePrefixList = new ArrayList();
                    writeNSList = new ArrayList();
                }
                writePrefixList.add("");
                writeNSList.add(eNamespace);
            }

            writer.writeStartElement("", reader.getLocalName(), eNamespace);
        } else {

            if (!OMSerializerUtil.isAssociated(ePrefix, eNamespace, writer)) {
                if (writePrefixList == null) {
                    writePrefixList = new ArrayList();
                    writeNSList = new ArrayList();
                }
                writePrefixList.add(ePrefix);
                writeNSList.add(eNamespace);
            }

            writer.writeStartElement(ePrefix, reader.getLocalName(), eNamespace);
        }
    } else {
        writer.writeStartElement(reader.getLocalName());
    }

    // Generate setPrefix for the namespace declarations
    int count = reader.getNamespaceCount();
    for (int i = 0; i < count; i++) {
        String prefix = reader.getNamespacePrefix(i);
        prefix = (prefix != null && prefix.length() == 0) ? null : prefix;
        String namespace = reader.getNamespaceURI(i);
        namespace = (namespace != null && namespace.length() == 0) ? null : namespace;

        String newPrefix = OMSerializerUtil.generateSetPrefix(prefix, namespace, writer, false);
        // If this is a new association, remember it so that it can written out later
        if (newPrefix != null) {
            if (writePrefixList == null) {
                writePrefixList = new ArrayList();
                writeNSList = new ArrayList();
            }
            if (!writePrefixList.contains(newPrefix)) {
                writePrefixList.add(newPrefix);
                writeNSList.add(namespace);
            }
        }
    }

    // Generate setPrefix for the element
    // If the prefix is not associated with a namespace yet, remember it so that we can
    // write out a namespace declaration
    String newPrefix = OMSerializerUtil.generateSetPrefix(ePrefix, eNamespace, writer, false);
    // If this is a new association, remember it so that it can written out later
    if (newPrefix != null) {
        if (writePrefixList == null) {
            writePrefixList = new ArrayList();
            writeNSList = new ArrayList();
        }
        if (!writePrefixList.contains(newPrefix)) {
            writePrefixList.add(newPrefix);
            writeNSList.add(eNamespace);
        }
    }

    // Now Generate setPrefix for each attribute
    count = reader.getAttributeCount();
    for (int i = 0; i < count; i++) {
        String prefix = reader.getAttributePrefix(i);
        prefix = (prefix != null && prefix.length() == 0) ? null : prefix;
        String namespace = reader.getAttributeNamespace(i);
        namespace = (namespace != null && namespace.length() == 0) ? null : namespace;

        // Default prefix referencing is not allowed on an attribute
        if (prefix == null && namespace != null) {
            String writerPrefix = writer.getPrefix(namespace);
            writerPrefix = (writerPrefix != null && writerPrefix.length() == 0) ? null : writerPrefix;
            prefix = (writerPrefix != null) ? writerPrefix : generateUniquePrefix(writer.getNamespaceContext());
        }
        newPrefix = OMSerializerUtil.generateSetPrefix(prefix, namespace, writer, true);
        // If the prefix is not associated with a namespace yet, remember it so that we can
        // write out a namespace declaration
        if (newPrefix != null) {
            if (writePrefixList == null) {
                writePrefixList = new ArrayList();
                writeNSList = new ArrayList();
            }
            if (!writePrefixList.contains(newPrefix)) {
                writePrefixList.add(newPrefix);
                writeNSList.add(namespace);
            }
        }
    }

    // Now Generate setPrefix for each prefix referenced in an xsi:type
    // For example xsi:type="p:dataType"
    // The following code will make sure that setPrefix is called for "p".
    count = reader.getAttributeCount();
    for (int i = 0; i < count; i++) {
        String prefix = reader.getAttributePrefix(i);
        prefix = (prefix != null && prefix.length() == 0) ? null : prefix;
        String namespace = reader.getAttributeNamespace(i);
        namespace = (namespace != null && namespace.length() == 0) ? null : namespace;
        String localName = reader.getAttributeLocalName(i);

        if (XSI_URI.equals(namespace) && XSI_LOCAL_NAME.equals(localName)) {
            String value = reader.getAttributeValue(i);
            if (DEBUG_ENABLED) {
                log.debug("The value of xsi:type is " + value);
            }
            if (value != null) {
                value = value.trim();
                if (value.indexOf(":") > 0) {
                    String refPrefix = value.substring(0, value.indexOf(":"));
                    String refNamespace = reader.getNamespaceURI(refPrefix);
                    if (refNamespace != null && refNamespace.length() > 0) {

                        newPrefix = OMSerializerUtil.generateSetPrefix(refPrefix, refNamespace, writer, true);
                        // If the prefix is not associated with a namespace yet, remember it so that we can
                        // write out a namespace declaration
                        if (newPrefix != null) {
                            if (DEBUG_ENABLED) {
                                log.debug(
                                        "An xmlns:" + newPrefix + "=\"" + refNamespace + "\" will be written");
                            }
                            if (writePrefixList == null) {
                                writePrefixList = new ArrayList();
                                writeNSList = new ArrayList();
                            }
                            if (!writePrefixList.contains(newPrefix)) {
                                writePrefixList.add(newPrefix);
                                writeNSList.add(refNamespace);
                            }
                        }
                    }

                }
            }
        }
    }

    // Now write out the list of namespace declarations in this list that we constructed
    // while doing the "set" processing.
    if (writePrefixList != null) {
        for (int i = 0; i < writePrefixList.size(); i++) {
            String prefix = (String) writePrefixList.get(i);
            String namespace = (String) writeNSList.get(i);
            if (prefix != null) {
                if (namespace == null) {
                    writer.writeNamespace(prefix, "");
                } else {
                    writer.writeNamespace(prefix, namespace);
                }
            } else {
                writer.writeDefaultNamespace(namespace);
            }
        }
    }

    // Now write the attributes
    count = reader.getAttributeCount();
    for (int i = 0; i < count; i++) {
        String prefix = reader.getAttributePrefix(i);
        prefix = (prefix != null && prefix.length() == 0) ? null : prefix;
        String namespace = reader.getAttributeNamespace(i);
        namespace = (namespace != null && namespace.length() == 0) ? null : namespace;

        if (prefix == null && namespace != null) {
            // Default namespaces are not allowed on an attribute reference.
            // Earlier in this code, a unique prefix was added for this case...now obtain and use it
            prefix = writer.getPrefix(namespace);
            //XMLStreamWriter doesn't allow for getPrefix to know whether you're asking for the prefix
            //for an attribute or an element. So if the namespace matches the default namespace getPrefix will return
            //the empty string, as if it were an element, in all cases (even for attributes, and even if 
            //there was a prefix specifically set up for this), which is not the desired behavior.
            //Since the interface is base java, we can't fix it where we need to (by adding an attr boolean to 
            //XMLStreamWriter.getPrefix), so we hack it in here...
            if (prefix == null || "".equals(prefix)) {
                for (int j = 0; j < writePrefixList.size(); j++) {
                    if (namespace.equals((String) writeNSList.get(j))) {
                        prefix = (String) writePrefixList.get(j);
                    }
                }
            }
        } else if (namespace != null && !prefix.equals("xml")) {
            // Use the writer's prefix if it is different, but if the writers 
            // prefix is empty then do not replace because attributes do not
            // default to the default namespace like elements do.
            String writerPrefix = writer.getPrefix(namespace);
            if (!prefix.equals(writerPrefix) && !"".equals(writerPrefix)) {
                prefix = writerPrefix;
            }
        }
        if (namespace != null) {
            // Qualified attribute
            writer.writeAttribute(prefix, namespace, reader.getAttributeLocalName(i),
                    reader.getAttributeValue(i));
        } else {
            // Unqualified attribute
            writer.writeAttribute(reader.getAttributeLocalName(i), reader.getAttributeValue(i));
        }
    }
}

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

/**
 * @param reader/*  w w w  . ja  va 2  s.  co  m*/
 * @param writer
 * @throws XMLStreamException
 */
protected void serializeAttributes(XMLStreamReader reader, XMLStreamWriter writer) throws XMLStreamException {
    int count = reader.getAttributeCount();
    String prefix = null;
    String namespaceName = null;
    String writerPrefix = null;
    for (int i = 0; i < count; i++) {
        prefix = reader.getAttributePrefix(i);
        namespaceName = reader.getAttributeNamespace(i);
        /*
           Some parser implementations return null for the unqualified namespace.
           But getPrefix(null) will throw an exception (according to the XMLStreamWriter
           javadoc. We guard against this by using "" for the unqualified namespace. 
        */
        namespaceName = (namespaceName == null) ? "" : namespaceName;

        // Using getNamespaceContext should be avoided when not necessary.
        // Some parser implementations construct a new NamespaceContext each time it is invoked.
        // writerPrefix = writer.getNamespaceContext().getPrefix(namespaceName);
        writerPrefix = writer.getPrefix(namespaceName);

        if (!"".equals(namespaceName)) {
            //prefix has already being declared but this particular attrib has a
            //no prefix attached. So use the prefix provided by the writer
            if (writerPrefix != null && (prefix == null || prefix.equals(""))) {
                writer.writeAttribute(writerPrefix, namespaceName, reader.getAttributeLocalName(i),
                        reader.getAttributeValue(i));

                //writer prefix is available but different from the current
                //prefix of the attrib. We should be decalring the new prefix
                //as a namespace declaration
            } else if (prefix != null && !"".equals(prefix) && !prefix.equals(writerPrefix)) {
                writer.writeNamespace(prefix, namespaceName);
                writer.writeAttribute(prefix, namespaceName, reader.getAttributeLocalName(i),
                        reader.getAttributeValue(i));

                //prefix is null (or empty), but the namespace name is valid! it has not
                //being written previously also. So we need to generate a prefix
                //here
            } else {
                prefix = generateUniquePrefix(writer.getNamespaceContext());
                writer.writeNamespace(prefix, namespaceName);
                writer.writeAttribute(prefix, namespaceName, reader.getAttributeLocalName(i),
                        reader.getAttributeValue(i));
            }
        } else {
            //empty namespace is equal to no namespace!
            writer.writeAttribute(reader.getAttributeLocalName(i), reader.getAttributeValue(i));
        }

    }
}

From source file:org.apache.axiom.om.impl.util.OMSerializerUtil.java

/**
 * Method serializeNamespace.// w  ww .j  a  va 2s .co  m
 *
 * @param namespace
 * @param writer
 * @throws XMLStreamException
 * @deprecated Use serializeStartpart instead
 */
public static void serializeNamespace(OMNamespace namespace, XMLStreamWriter writer) throws XMLStreamException {
    if (namespace == null) {
        return;
    }
    String uri = namespace.getNamespaceURI();
    String prefix = namespace.getPrefix();

    if (uri != null && !"".equals(uri)) {
        String prefixFromWriter = writer.getPrefix(uri);

        // Handling Default Namespaces First
        // Case 1 :
        //        here we are trying define a default namespace. But has this been defined in the current context.
        //        yes, there can be a default namespace, but it may have a different URI. If its a different URI
        //        then explicitly define the default namespace here.
        // Case 2 :
        //        The passed in namespace is a default ns, but there is a non-default ns declared
        //        in the current scope.
        if (("".equals(prefix) && "".equals(prefixFromWriter)
                && !uri.equals(writer.getNamespaceContext().getNamespaceURI("")))
                || (prefix != null && "".equals(prefix)
                        && (prefixFromWriter == null || !prefix.equals(prefixFromWriter)))) {
            // this has not been declared earlier
            writer.writeDefaultNamespace(uri);
            writer.setDefaultNamespace(uri);
        } else {
            prefix = prefix == null ? getNextNSPrefix(writer) : prefix;
            if (prefix != null && !prefix.equals(prefixFromWriter)
                    && !checkForPrefixInTheCurrentContext(writer, uri, prefix)) {
                writer.writeNamespace(prefix, uri);
                writer.setPrefix(prefix, uri);
            }
        }
    } else {
        // now the nsURI passed is "" or null. Meaning we gonna work with defaultNS.
        // check whether there is a defaultNS already declared. If yes, is it the same as this ?
        String currentDefaultNSURI = writer.getNamespaceContext().getNamespaceURI("");
        if ((currentDefaultNSURI != null && !currentDefaultNSURI.equals(uri))
                || uri != null && !uri.equals(currentDefaultNSURI)) {
            // this has not been declared earlier
            writer.writeDefaultNamespace(uri);
            writer.setDefaultNamespace(uri);
        }
    }
}

From source file:org.apache.axiom.om.impl.util.OMSerializerUtil.java

private static boolean checkForPrefixInTheCurrentContext(XMLStreamWriter writer, String nameSpaceName,
        String prefix) throws XMLStreamException {
    Iterator prefixesIter = writer.getNamespaceContext().getPrefixes(nameSpaceName);
    while (prefixesIter.hasNext()) {
        String prefix_w = (String) prefixesIter.next();
        if (prefix_w.equals(prefix)) {
            // if found do not declare the ns
            return true;
        }//  w ww .  j  av  a  2s.  co  m
    }
    return false;
}

From source file:org.apache.axiom.om.impl.util.OMSerializerUtil.java

public static String getNextNSPrefix(XMLStreamWriter writer) {
    String prefix = getNextNSPrefix();
    while (writer.getNamespaceContext().getNamespaceURI(prefix) != null) {
        prefix = getNextNSPrefix();//from  w  ww.ja  va  2 s .co m
    }

    return prefix;
}

From source file:org.apache.axiom.om.impl.util.OMSerializerUtil.java

/**
 * @param prefix /*from ww  w .j  a va 2s  .  c o  m*/
 * @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.deegree.services.csw.exporthandling.GetCapabilitiesHelper.java

private void writeTemplateElement(XMLStreamWriter writer, XMLStreamReader inStream,
        Map<String, String> varToValue) throws XMLStreamException {

    if (inStream.getEventType() != XMLStreamConstants.START_ELEMENT) {
        throw new XMLStreamException("Input stream does not point to a START_ELEMENT event.");
    }/*from  ww w .j  a  va2 s  .  c  o m*/
    int openElements = 0;
    boolean firstRun = true;
    while (firstRun || openElements > 0) {
        firstRun = false;
        int eventType = inStream.getEventType();

        switch (eventType) {
        case CDATA: {
            writer.writeCData(inStream.getText());
            break;
        }
        case CHARACTERS: {
            String s = new String(inStream.getTextCharacters(), inStream.getTextStart(),
                    inStream.getTextLength());
            // TODO optimize
            for (String param : varToValue.keySet()) {
                String value = varToValue.get(param);
                s = s.replace(param, value);
            }
            writer.writeCharacters(s);

            break;
        }
        case END_ELEMENT: {
            writer.writeEndElement();
            openElements--;
            break;
        }
        case START_ELEMENT: {
            if (inStream.getNamespaceURI() == "" || inStream.getPrefix() == DEFAULT_NS_PREFIX
                    || inStream.getPrefix() == null) {
                writer.writeStartElement(inStream.getLocalName());
            } else {
                if (writer.getNamespaceContext().getPrefix(inStream.getPrefix()) == "") {
                    // TODO handle special cases for prefix binding, see
                    // http://download.oracle.com/docs/cd/E17409_01/javase/6/docs/api/javax/xml/namespace/NamespaceContext.html#getNamespaceURI(java.lang.String)
                    writer.setPrefix(inStream.getPrefix(), inStream.getNamespaceURI());
                }
                writer.writeStartElement(inStream.getPrefix(), inStream.getLocalName(),
                        inStream.getNamespaceURI());
            }
            // copy all namespace bindings
            for (int i = 0; i < inStream.getNamespaceCount(); i++) {
                String nsPrefix = inStream.getNamespacePrefix(i);
                String nsURI = inStream.getNamespaceURI(i);
                writer.writeNamespace(nsPrefix, nsURI);
            }

            // copy all attributes
            for (int i = 0; i < inStream.getAttributeCount(); i++) {
                String localName = inStream.getAttributeLocalName(i);
                String nsPrefix = inStream.getAttributePrefix(i);
                String value = inStream.getAttributeValue(i);
                String nsURI = inStream.getAttributeNamespace(i);
                if (nsURI == null) {
                    writer.writeAttribute(localName, value);
                } else {
                    writer.writeAttribute(nsPrefix, nsURI, localName, value);
                }
            }

            openElements++;
            break;
        }
        default: {
            break;
        }
        }
        if (openElements > 0) {
            inStream.next();
        }
    }
}

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 {/*  w ww . j av  a2  s  .com*/
            return prefix.concat(":").concat(name.getLocalPart());
        }
    } else {
        return name.getLocalPart();
    }
}