Example usage for javax.xml XMLConstants NULL_NS_URI

List of usage examples for javax.xml XMLConstants NULL_NS_URI

Introduction

In this page you can find the example usage for javax.xml XMLConstants NULL_NS_URI.

Prototype

String NULL_NS_URI

To view the source code for javax.xml XMLConstants NULL_NS_URI.

Click Source Link

Document

Namespace URI to use to represent that there is no Namespace.

Usage

From source file:com.evolveum.midpoint.util.DOMUtil.java

private static void setQNameAttribute(Element element, Attr attr, QName attributeQnameValue,
        Element definitionElement) {
    String attributeStringValue;/*from  ww  w  .ja v  a 2s . c o m*/

    if (attributeQnameValue == null) {
        attributeStringValue = "";
    } else if (XMLConstants.NULL_NS_URI.equals(attributeQnameValue.getNamespaceURI())) {
        if (QNameUtil.isPrefixUndeclared(attributeQnameValue.getPrefix())) {
            attributeStringValue = attributeQnameValue.getPrefix() + ":" + attributeQnameValue.getLocalPart(); // to give user a chance to see and fix this
        } else {
            attributeStringValue = attributeQnameValue.getLocalPart();
        }
    } else {
        String valuePrefix = lookupOrCreateNamespaceDeclaration(element, attributeQnameValue.getNamespaceURI(),
                attributeQnameValue.getPrefix(), definitionElement, false);
        assert StringUtils.isNotBlank(valuePrefix);
        attributeStringValue = valuePrefix + ":" + attributeQnameValue.getLocalPart();
    }

    NamedNodeMap attributes = element.getAttributes();
    checkValidXmlChars(attributeStringValue);
    attr.setValue(attributeStringValue);
    attributes.setNamedItem(attr);
}

From source file:com.evolveum.midpoint.util.DOMUtil.java

/**
 * Sets QName value for a given element.
 *
 * Contrary to standard XML semantics, namespace-less QNames are specified as simple names without prefix
 * (regardless of default prefix used in the XML document).
 *
 * @param element Element whose text content should be set to represent QName value
 * @param elementValue QName value to be stored into the element
 *//*ww w. j  a  v  a2  s .com*/
public static void setQNameValue(Element element, QName elementValue) {
    if (elementValue == null) {
        setElementTextContent(element, "");
    } else if (XMLConstants.NULL_NS_URI.equals(elementValue.getNamespaceURI())) {
        if (QNameUtil.isPrefixUndeclared(elementValue.getPrefix())) {
            setElementTextContent(element, elementValue.getPrefix() + ":" + elementValue.getLocalPart());
        } else {
            setElementTextContent(element, elementValue.getLocalPart());
        }
    } else {
        String prefix = lookupOrCreateNamespaceDeclaration(element, elementValue.getNamespaceURI(),
                elementValue.getPrefix(), element, false);
        assert StringUtils.isNotBlank(prefix);
        String stringValue = prefix + ":" + elementValue.getLocalPart();
        setElementTextContent(element, stringValue);
    }
}

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

/**
 * Create a namespace context from the given mapping bewteen prefixes and namespace uris.
 * @param prefixes2NamespaceURIs/*from  w ww  . j ava2 s. c o  m*/
 * @return a namespace context
 */
public static NamespaceContext createNamespaceContext(final Map<String, String> prefixes2NamespaceURIs) {
    return new NamespaceContext() {
        public String getNamespaceURI(String prefix) {
            if (prefix == null)
                throw new NullPointerException("Null prefix");
            else if (prefixes2NamespaceURIs.containsKey(prefix))
                return prefixes2NamespaceURIs.get(prefix);
            else if ("xml".equals(prefix))
                return XMLConstants.XML_NS_URI;
            return XMLConstants.NULL_NS_URI;
        }

        // This method isn't necessary for XPath processing.
        public String getPrefix(String uri) {
            throw new UnsupportedOperationException();
        }

        // This method isn't necessary for XPath processing either.
        public Iterator<Object> getPrefixes(String uri) {
            throw new UnsupportedOperationException();
        }
    };
}

From source file:com.centeractive.ws.builder.soap.WsdlUtils.java

public static String getTargetNamespace(Definition definition) {
    return definition.getTargetNamespace() == null ? XMLConstants.NULL_NS_URI : definition.getTargetNamespace();
}

From source file:nz.co.testamation.common.util.PrefixMapNamespaceContext.java

public String getNamespaceURI(String prefix) {
    switch (prefix) {
    case XMLConstants.XML_NS_PREFIX:
        return XMLConstants.XML_NS_URI;
    case XMLConstants.XMLNS_ATTRIBUTE:
        return XMLConstants.XMLNS_ATTRIBUTE_NS_URI;
    default://from   w  w w  .j  ava  2 s .  c  o  m
        return StringUtils.defaultString(prefixNamespaceMap.get(prefix), XMLConstants.NULL_NS_URI);
    }
}

From source file:org.apache.axis2.format.WrappedTextNodeStreamReader.java

public String getNamespaceURI(String prefix) {
    String namespaceURI = getNamespaceContext().getNamespaceURI(prefix);
    // NamespaceContext#getNamespaceURI and XMLStreamReader#getNamespaceURI have slightly
    // different semantics for unbound prefixes.
    return namespaceURI.equals(XMLConstants.NULL_NS_URI) ? null : prefix;
}

From source file:org.apache.geode.management.internal.configuration.utils.XmlUtilsJUnitTest.java

/**
 * Test method for {@link XmlUtils#changeNamespace(Node, String, String)}.
 *///from  ww w.j  a  va 2 s.  c o  m
@Test
public void testChangeNamespace() throws Exception {
    Document doc = XmlUtils.getDocumentBuilder().newDocument();
    Element root = doc.createElement("root");
    root = (Element) doc.appendChild(root);
    final Element child = doc.createElement("child");
    root.appendChild(child);
    final String ns2 = "urn:namespace2";
    final Element childWithNamespace = doc.createElementNS(ns2, "childWithNamespace");
    root.appendChild(childWithNamespace);
    root.appendChild(doc.createTextNode("some text"));

    assertEquals(null, root.getNamespaceURI());
    assertEquals(null, child.getNamespaceURI());
    assertEquals(ns2, childWithNamespace.getNamespaceURI());

    final String ns1 = "urn:namespace1";
    root = (Element) XmlUtils.changeNamespace(root, XMLConstants.NULL_NS_URI, ns1);

    assertEquals(ns1, root.getNamespaceURI());
    assertEquals(ns1, root.getElementsByTagName("child").item(0).getNamespaceURI());
    assertEquals(ns2, root.getElementsByTagName("childWithNamespace").item(0).getNamespaceURI());
}

From source file:org.dhatim.csv.CSVReader.java

public void parse(InputSource csvInputSource) throws IOException, SAXException {
    if (contentHandler == null) {
        throw new IllegalStateException("'contentHandler' not set.  Cannot parse CSV stream.");
    }/*ww w  . ja va 2s . c o  m*/
    if (execContext == null) {
        throw new IllegalStateException("'execContext' not set.  Cannot parse CSV stream.");
    }

    try {
        Reader csvStreamReader;
        au.com.bytecode.opencsv.CSVReader csvLineReader;
        String[] csvRecord;

        // Get a reader for the CSV source...
        csvStreamReader = csvInputSource.getCharacterStream();
        if (csvStreamReader == null) {
            csvStreamReader = new InputStreamReader(csvInputSource.getByteStream(), encoding);
        }

        // Create the CSV line reader...
        csvLineReader = new au.com.bytecode.opencsv.CSVReader(csvStreamReader, separator, quoteChar, escapeChar,
                skipLines);

        if (validateHeader) {
            validateHeader(csvLineReader);
        }

        // Start the document and add the root "csv-set" element...
        contentHandler.startDocument();
        contentHandler.startElement(XMLConstants.NULL_NS_URI, rootElementName, StringUtils.EMPTY,
                EMPTY_ATTRIBS);

        // Output each of the CVS line entries...
        int lineNumber = 0;
        int expectedCount = getExpectedColumnsCount();

        while ((csvRecord = csvLineReader.readNext()) != null) {
            lineNumber++; // First line is line "1"

            if (csvRecord.length < expectedCount && strict) {
                logger.debug("[CORRUPT-CSV] CSV line #" + lineNumber + " invalid [" + Arrays.asList(csvRecord)
                        + "].  The line should contain number of items at least as in CSV config file "
                        + csvFields.length + " fields [" + csvFields + "], but contains " + csvRecord.length
                        + " fields.  Ignoring!!");
                continue;
            }

            if (indent) {
                contentHandler.characters(INDENT_LF, 0, 1);
                contentHandler.characters(INDENT_1, 0, 1);
            }

            AttributesImpl attrs = new AttributesImpl();
            // If we reached here it means that this line has to be in the sax stream
            // hence we first add the record number attribute on the csv-record element
            attrs.addAttribute(XMLConstants.NULL_NS_URI, RECORD_NUMBER_ATTR, RECORD_NUMBER_ATTR, "xs:int",
                    Integer.toString(lineNumber));
            // if this line is truncated, we add the truncated attribute onto the csv-record element
            if (csvRecord.length < expectedCount)
                attrs.addAttribute(XMLConstants.NULL_NS_URI, RECORD_TRUNCATED_ATTR, RECORD_TRUNCATED_ATTR,
                        "xs:boolean", Boolean.TRUE.toString());
            contentHandler.startElement(XMLConstants.NULL_NS_URI, recordElementName, StringUtils.EMPTY, attrs);
            int recordIt = 0;
            for (Field field : fields) {
                String fieldName = field.getName();

                if (field.ignore()) {
                    int toSkip = parseIgnoreFieldDirective(fieldName);
                    if (toSkip == Integer.MAX_VALUE) {
                        break;
                    }
                    recordIt += toSkip;
                    continue;
                }

                if (indent) {
                    contentHandler.characters(INDENT_LF, 0, 1);
                    contentHandler.characters(INDENT_2, 0, 2);
                }

                // Don't insert the element if the csv record does not contain it!!
                if (recordIt < csvRecord.length) {
                    String value = csvRecord[recordIt];

                    contentHandler.startElement(XMLConstants.NULL_NS_URI, fieldName, StringUtils.EMPTY,
                            EMPTY_ATTRIBS);

                    StringFunctionExecutor stringFunctionExecutor = field.getStringFunctionExecutor();
                    if (stringFunctionExecutor != null) {
                        value = stringFunctionExecutor.execute(value);
                    }

                    contentHandler.characters(value.toCharArray(), 0, value.length());
                    contentHandler.endElement(XMLConstants.NULL_NS_URI, fieldName, StringUtils.EMPTY);
                }

                if (indent) {
                }

                recordIt++;
            }

            if (indent) {
                contentHandler.characters(INDENT_LF, 0, 1);
                contentHandler.characters(INDENT_1, 0, 1);
            }

            contentHandler.endElement(null, recordElementName, StringUtils.EMPTY);
        }

        if (indent) {
            contentHandler.characters(INDENT_LF, 0, 1);
        }

        // Close out the "csv-set" root element and end the document..
        contentHandler.endElement(XMLConstants.NULL_NS_URI, rootElementName, StringUtils.EMPTY);
        contentHandler.endDocument();
    } finally {
        // These properties need to be reset for every execution (e.g. when reader is pooled).
        contentHandler = null;
        execContext = null;
    }
}

From source file:org.dhatim.delivery.dom.DOMBuilder.java

public void startElement(StartElementEvent startEvent) throws SAXException {
    Element newElement = null;//from w w w.j a v  a  2s .  c  o  m
    int attsCount = startEvent.atts.getLength();
    Node currentNode = (Node) nodeStack.peek();

    try {
        if (startEvent.uri != null && startEvent.qName != null && !startEvent.qName.equals("")) {
            newElement = ownerDocument.createElementNS(startEvent.uri.intern(), startEvent.qName);
        } else {
            newElement = ownerDocument.createElement(startEvent.localName.intern());
        }

        currentNode.appendChild(newElement);
        if (!emptyElements.contains(startEvent.qName != null ? startEvent.qName : startEvent.localName)) {
            nodeStack.push(newElement);
        }
    } catch (DOMException e) {
        logger.error("DOMException creating start element: namespaceURI=" + startEvent.uri + ", localName="
                + startEvent.localName, e);
        throw e;
    }

    for (int i = 0; i < attsCount; i++) {
        String attNamespace = startEvent.atts.getURI(i);
        String attQName = startEvent.atts.getQName(i);
        String attLocalName = startEvent.atts.getLocalName(i);
        String attValue = startEvent.atts.getValue(i);
        try {
            if (attNamespace != null && attQName != null) {
                attNamespace = attNamespace.intern();
                if (attNamespace.equals(XMLConstants.NULL_NS_URI)) {
                    if (attQName.startsWith(XMLConstants.XMLNS_ATTRIBUTE)) {
                        attNamespace = XMLConstants.XMLNS_ATTRIBUTE_NS_URI;
                    } else if (attQName.startsWith("xml:")) {
                        attNamespace = XMLConstants.XML_NS_URI;
                    }
                }
                newElement.setAttributeNS(attNamespace, attQName, attValue);
            } else {
                newElement.setAttribute(attLocalName.intern(), attValue);
            }
        } catch (DOMException e) {
            logger.error("DOMException setting element attribute " + attLocalName + "=" + attValue
                    + "[namespaceURI=" + startEvent.uri + ", localName=" + startEvent.localName + "].", e);
            throw e;
        }
    }
}

From source file:org.dhatim.fixedlength.FixedLengthReader.java

public void parse(InputSource flInputSource) throws IOException, SAXException {
    if (contentHandler == null) {
        throw new IllegalStateException("'contentHandler' not set.  Cannot parse Fixed Length stream.");
    }/*from   www.  ja va2 s. c  o m*/
    if (execContext == null) {
        throw new IllegalStateException("'execContext' not set.  Cannot parse Fixed Length stream.");
    }

    try {
        Reader flStreamReader;
        BufferedReader flLineReader;
        String flRecord;
        int lineNumber = 0;

        // Get a reader for the Fixed Length source...
        flStreamReader = flInputSource.getCharacterStream();
        if (flStreamReader == null) {
            flStreamReader = new InputStreamReader(flInputSource.getByteStream(), encoding);
        }

        // Create the Fixed Length line reader...
        flLineReader = new BufferedReader(flStreamReader);

        // Start the document and add the root element...
        contentHandler.startDocument();
        contentHandler.startElement(XMLConstants.NULL_NS_URI, rootElementName, StringUtils.EMPTY,
                EMPTY_ATTRIBS);

        // Output each of the Fixed Length line entries...
        while ((flRecord = flLineReader.readLine()) != null) {
            lineNumber++; // First line is line "1"

            if (lineNumber <= this.skipLines) {
                continue;
            }
            boolean invalidLength = flRecord.length() < totalFieldLenght;
            if (invalidLength && strict) {
                if (logger.isWarnEnabled()) {
                    logger.debug("[WARNING-FIXEDLENGTH] Fixed Length line #" + lineNumber
                            + " is invalid.  The line doesn't contain enough characters to fill all the fields. This line is skipped.");
                }
                continue;
            }

            char[] recordChars = flRecord.toCharArray();

            if (indent) {
                contentHandler.characters(INDENT_LF, 0, 1);
                contentHandler.characters(INDENT_1, 0, 1);
            }

            AttributesImpl attrs = EMPTY_ATTRIBS;
            // Add a lineNumber ID
            if (this.lineNumber || invalidLength) {
                attrs = new AttributesImpl();
                if (this.lineNumber) {
                    attrs.addAttribute(XMLConstants.NULL_NS_URI, lineNumberAttributeName,
                            lineNumberAttributeName, "xs:int", Integer.toString(lineNumber));
                }
                if (invalidLength) {
                    attrs.addAttribute(XMLConstants.NULL_NS_URI, truncatedAttributeName, truncatedAttributeName,
                            "xs:boolean", Boolean.TRUE.toString());
                }
            }

            contentHandler.startElement(XMLConstants.NULL_NS_URI, recordElementName, StringUtils.EMPTY, attrs);

            // Loops through fields
            int fieldLengthTotal = 0;
            for (int i = 0; i < flFields.length; i++) {
                // Field name local to the loop
                String fieldName = fields[i].getName();
                // Field length local to the loop
                int fieldLength = fields[i].getLength();

                StringFunctionExecutor stringFunctionExecutor = fields[i].getStringFunctionExecutor();

                if (!fields[i].ignore()) {
                    if (indent) {
                        contentHandler.characters(INDENT_LF, 0, 1);
                        contentHandler.characters(INDENT_2, 0, 2);
                    }

                    // Check that there are enough characters in the string
                    boolean truncated = fieldLengthTotal + fieldLength > flRecord.length();

                    AttributesImpl recordAttrs = EMPTY_ATTRIBS;

                    //If truncated then set the truncated attribute
                    if (truncated) {
                        recordAttrs = new AttributesImpl();
                        recordAttrs.addAttribute(XMLConstants.NULL_NS_URI, truncatedAttributeName,
                                truncatedAttributeName, "xs:boolean", Boolean.TRUE.toString());
                    }

                    contentHandler.startElement(XMLConstants.NULL_NS_URI, fieldName, StringUtils.EMPTY,
                            recordAttrs);

                    // If not truncated then set the element data
                    if (!truncated) {
                        if (stringFunctionExecutor == null) {
                            contentHandler.characters(recordChars, fieldLengthTotal, fieldLength);
                        } else {
                            String value = flRecord.substring(fieldLengthTotal, fieldLengthTotal + fieldLength);

                            value = stringFunctionExecutor.execute(value);

                            contentHandler.characters(value.toCharArray(), 0, value.length());
                        }
                    }

                    contentHandler.endElement(XMLConstants.NULL_NS_URI, fieldName, StringUtils.EMPTY);
                }

                fieldLengthTotal += fieldLength;
            }

            if (indent) {
                contentHandler.characters(INDENT_LF, 0, 1);
                contentHandler.characters(INDENT_1, 0, 1);
            }

            contentHandler.endElement(null, recordElementName, StringUtils.EMPTY);

        }

        if (indent) {
            contentHandler.characters(INDENT_LF, 0, 1);
        }

        // Close out the "fixedlength-set" root element and end the document..
        contentHandler.endElement(XMLConstants.NULL_NS_URI, rootElementName, StringUtils.EMPTY);
        contentHandler.endDocument();
    } finally {
        // These properties need to be reset for every execution (e.g. when reader is pooled).
        contentHandler = null;
        execContext = null;
    }
}