Example usage for javax.xml XMLConstants XML_NS_URI

List of usage examples for javax.xml XMLConstants XML_NS_URI

Introduction

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

Prototype

String XML_NS_URI

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

Click Source Link

Document

The official XML Namespace name URI.

Usage

From source file:de.pangaea.fixo3.xml.ProcessXmlFiles.java

private void run() throws FileNotFoundException, SAXException, IOException, ParserConfigurationException,
        XPathExpressionException {
    // src/test/resources/, src/main/resources/files
    File folder = new File("src/main/resources/files");
    File[] files = folder.listFiles(new FileFilter() {

        @Override/*from   ww w  .  j  a  va2  s  .  c om*/
        public boolean accept(File pathname) {
            if (pathname.getName().endsWith(".xml"))
                return true;

            return false;
        }
    });

    JsonArrayBuilder json = Json.createArrayBuilder();

    Document doc;
    String deviceLabel, deviceComment, deviceImage;

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);

    final Map<String, String> prefixToNS = new HashMap<>();
    prefixToNS.put(XMLConstants.XML_NS_PREFIX, XMLConstants.XML_NS_URI);
    prefixToNS.put(XMLConstants.XMLNS_ATTRIBUTE, XMLConstants.XMLNS_ATTRIBUTE_NS_URI);
    prefixToNS.put("sml", "http://www.opengis.net/sensorml/2.0");
    prefixToNS.put("gml", "http://www.opengis.net/gml/3.2");
    prefixToNS.put("gmd", "http://www.isotc211.org/2005/gmd");

    XPath x = XPathFactory.newInstance().newXPath();
    x.setNamespaceContext(new NamespaceContext() {
        @Override
        public String getNamespaceURI(String prefix) {
            Objects.requireNonNull(prefix, "Namespace prefix cannot be null");
            final String uri = prefixToNS.get(prefix);
            if (uri == null) {
                throw new IllegalArgumentException("Undeclared namespace prefix: " + prefix);
            }
            return uri;
        }

        @Override
        public String getPrefix(String namespaceURI) {
            throw new UnsupportedOperationException();
        }

        @Override
        public Iterator<?> getPrefixes(String namespaceURI) {
            throw new UnsupportedOperationException();
        }
    });

    XPathExpression exGmlName = x.compile("/sml:PhysicalSystem/gml:name");
    XPathExpression exGmlDescription = x.compile("/sml:PhysicalSystem/gml:description");
    XPathExpression exGmdUrl = x.compile(
            "/sml:PhysicalSystem/sml:documentation/sml:DocumentList/sml:document/gmd:CI_OnlineResource/gmd:linkage/gmd:URL");
    XPathExpression exTerm = x
            .compile("/sml:PhysicalSystem/sml:classification/sml:ClassifierList/sml:classifier/sml:Term");

    int m = 0;
    int n = 0;

    for (File file : files) {
        log.info(file.getName());
        doc = dbf.newDocumentBuilder().parse(new FileInputStream(file));

        deviceLabel = exGmlName.evaluate(doc).trim();
        deviceComment = exGmlDescription.evaluate(doc).trim();
        deviceImage = exGmdUrl.evaluate(doc).trim();
        NodeList terms = (NodeList) exTerm.evaluate(doc, XPathConstants.NODESET);

        JsonObjectBuilder jobDevice = Json.createObjectBuilder();

        jobDevice.add("name", toUri(deviceLabel));
        jobDevice.add("label", deviceLabel);
        jobDevice.add("comment", toAscii(deviceComment));
        jobDevice.add("image", deviceImage);

        JsonArrayBuilder jabSubClasses = Json.createArrayBuilder();

        for (int i = 0; i < terms.getLength(); i++) {
            Node term = terms.item(i);
            NodeList attributes = term.getChildNodes();

            String attributeLabel = null;
            String attributeValue = null;

            for (int j = 0; j < attributes.getLength(); j++) {
                Node attribute = attributes.item(j);
                String attributeName = attribute.getNodeName();

                if (attributeName.equals("sml:label")) {
                    attributeLabel = attribute.getTextContent();
                } else if (attributeName.equals("sml:value")) {
                    attributeValue = attribute.getTextContent();
                }
            }

            if (attributeLabel == null || attributeValue == null) {
                throw new RuntimeException("Attribute label or value cannot be null [attributeLabel = "
                        + attributeLabel + "; attributeValue = " + attributeValue + "]");
            }

            if (attributeLabel.equals("model")) {
                continue;
            }

            if (attributeLabel.equals("manufacturer")) {
                jobDevice.add("manufacturer", attributeValue);
                continue;
            }

            n++;

            Quantity quantity = getQuantity(attributeValue);

            if (quantity == null) {
                continue;
            }

            m++;

            JsonObjectBuilder jobSubClass = Json.createObjectBuilder();
            JsonObjectBuilder jobCapability = Json.createObjectBuilder();
            JsonObjectBuilder jobQuantity = Json.createObjectBuilder();

            String quantityLabel = getQuantityLabel(attributeLabel);
            String capabilityLabel = deviceLabel + " " + quantityLabel;

            jobCapability.add("label", capabilityLabel);

            jobQuantity.add("label", quantity.getLabel());

            if (quantity.getValue() != null) {
                jobQuantity.add("value", quantity.getValue());
            } else if (quantity.getMinValue() != null && quantity.getMaxValue() != null) {
                jobQuantity.add("minValue", quantity.getMinValue());
                jobQuantity.add("maxValue", quantity.getMaxValue());
            } else {
                throw new RuntimeException(
                        "Failed to determine quantity value [attributeValue = " + attributeValue + "]");
            }

            jobQuantity.add("unitCode", quantity.getUnitCode());
            jobQuantity.add("type", toUri(quantityLabel));

            jobCapability.add("quantity", jobQuantity);
            jobSubClass.add("capability", jobCapability);

            jabSubClasses.add(jobSubClass);
        }

        jobDevice.add("subClasses", jabSubClasses);

        json.add(jobDevice);
    }

    Map<String, Object> properties = new HashMap<>(1);
    properties.put(JsonGenerator.PRETTY_PRINTING, true);

    JsonWriterFactory jsonWriterFactory = Json.createWriterFactory(properties);
    JsonWriter jsonWriter = jsonWriterFactory.createWriter(new FileWriter(new File(jsonFileName)));
    jsonWriter.write(json.build());
    jsonWriter.close();

    System.out.println("Fraction of characteristics included: " + m + "/" + n);
}

From source file:InlineSchemaValidator.java

public String getNamespaceURI(String prefix) {
    if (prefix == null) {
        throw new IllegalArgumentException("Prefix cannot be null.");
    } else if (XMLConstants.XML_NS_PREFIX.equals(prefix)) {
        return XMLConstants.XML_NS_URI;
    } else if (XMLConstants.XMLNS_ATTRIBUTE.equals(prefix)) {
        return XMLConstants.XMLNS_ATTRIBUTE_NS_URI;
    } else if (fPrefixToURIMappings != null) {
        String uri = (String) fPrefixToURIMappings.get(prefix);
        if (uri != null) {
            return uri;
        }/*from w w  w  .  j a v  a 2s  .co  m*/
    }
    return XMLConstants.NULL_NS_URI;
}

From source file:InlineSchemaValidator.java

public String getPrefix(String namespaceURI) {
    if (namespaceURI == null) {
        throw new IllegalArgumentException("Namespace URI cannot be null.");
    } else if (XMLConstants.XML_NS_URI.equals(namespaceURI)) {
        return XMLConstants.XML_NS_PREFIX;
    } else if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(namespaceURI)) {
        return XMLConstants.XMLNS_ATTRIBUTE;
    } else if (fURIToPrefixMappings != null) {
        HashSet prefixes = (HashSet) fURIToPrefixMappings.get(namespaceURI);
        if (prefixes != null && prefixes.size() > 0) {
            return (String) prefixes.iterator().next();
        }// w  w w  .  ja va 2s  . c  o  m
    }
    return null;
}

From source file:InlineSchemaValidator.java

public Iterator getPrefixes(String namespaceURI) {
    if (namespaceURI == null) {
        throw new IllegalArgumentException("Namespace URI cannot be null.");
    } else if (XMLConstants.XML_NS_URI.equals(namespaceURI)) {
        return new Iterator() {
            boolean more = true;

            public boolean hasNext() {
                return more;
            }//from   w  w w.  java 2  s .co m

            public Object next() {
                if (!hasNext()) {
                    throw new NoSuchElementException();
                }
                more = false;
                return XMLConstants.XML_NS_PREFIX;
            }

            public void remove() {
                throw new UnsupportedOperationException();
            }
        };
    } else if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(namespaceURI)) {
        return new Iterator() {
            boolean more = true;

            public boolean hasNext() {
                return more;
            }

            public Object next() {
                if (!hasNext()) {
                    throw new NoSuchElementException();
                }
                more = false;
                return XMLConstants.XMLNS_ATTRIBUTE;
            }

            public void remove() {
                throw new UnsupportedOperationException();
            }
        };
    } else if (fURIToPrefixMappings != null) {
        HashSet prefixes = (HashSet) fURIToPrefixMappings.get(namespaceURI);
        if (prefixes != null && prefixes.size() > 0) {
            return prefixes.iterator();
        }
    }
    return Collections.EMPTY_LIST.iterator();
}

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  w  w . j  a v  a 2 s. co 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: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.olingo.client.core.serialization.AbstractAtomDealer.java

protected void namespaces(final XMLStreamWriter writer) throws XMLStreamException {
    writer.writeNamespace(StringUtils.EMPTY, Constants.NS_ATOM);
    writer.writeNamespace(XMLConstants.XML_NS_PREFIX, XMLConstants.XML_NS_URI);
    writer.writeNamespace(Constants.PREFIX_METADATA, Constants.NS_METADATA);
    writer.writeNamespace(Constants.PREFIX_DATASERVICES, Constants.NS_DATASERVICES);
    writer.writeNamespace(Constants.PREFIX_GML, Constants.NS_GML);
    writer.writeNamespace(Constants.PREFIX_GEORSS, Constants.NS_GEORSS);
}

From source file:org.apache.olingo.client.core.serialization.AtomSerializer.java

private void entity(final XMLStreamWriter writer, final Entity entity)
        throws XMLStreamException, EdmPrimitiveTypeException {
    if (entity.getBaseURI() != null) {
        writer.writeAttribute(XMLConstants.XML_NS_URI, Constants.ATTR_XML_BASE,
                entity.getBaseURI().toASCIIString());
    }//w ww. j a va2  s  . c om

    if (serverMode && StringUtils.isNotBlank(entity.getETag())) {
        writer.writeAttribute(namespaceMetadata, Constants.ATOM_ATTR_ETAG, entity.getETag());
    }

    if (entity.getId() != null) {
        writer.writeStartElement(Constants.ATOM_ELEM_ID);
        writer.writeCharacters(entity.getId().toASCIIString());
        writer.writeEndElement();
    }

    writer.writeStartElement(Constants.ATOM_ELEM_CATEGORY);
    writer.writeAttribute(Constants.ATOM_ATTR_SCHEME, Constants.NS_SCHEME);
    if (StringUtils.isNotBlank(entity.getType())) {
        writer.writeAttribute(Constants.ATOM_ATTR_TERM,
                new EdmTypeInfo.Builder().setTypeExpression(entity.getType()).build().external());
    }
    writer.writeEndElement();

    common(writer, entity);

    if (serverMode) {
        if (entity.getEditLink() != null) {
            links(writer, Collections.singletonList(entity.getEditLink()));
        }

        if (entity.getSelfLink() != null) {
            links(writer, Collections.singletonList(entity.getSelfLink()));
        }
    }

    links(writer, entity.getAssociationLinks());
    if (serverMode) {
        links(writer, entity.getNavigationLinks());
    } else {
        writeNavigationLinks(writer, entity.getNavigationLinks());
        writeNavigationLinks(writer, entity.getNavigationBindings());
    }
    links(writer, entity.getMediaEditLinks());

    if (serverMode) {
        for (Operation operation : entity.getOperations()) {
            writer.writeStartElement(namespaceMetadata, Constants.ATOM_ELEM_ACTION);
            writer.writeAttribute(Constants.ATTR_METADATA, operation.getMetadataAnchor());
            writer.writeAttribute(Constants.ATTR_TITLE, operation.getTitle());
            writer.writeAttribute(Constants.ATTR_TARGET, operation.getTarget().toASCIIString());
            writer.writeEndElement();
        }
    }

    writer.writeStartElement(Constants.ATOM_ELEM_CONTENT);
    if (entity.isMediaEntity()) {
        if (StringUtils.isNotBlank(entity.getMediaContentType())) {
            writer.writeAttribute(Constants.ATTR_TYPE, entity.getMediaContentType());
        }
        if (entity.getMediaContentSource() != null) {
            writer.writeAttribute(Constants.ATOM_ATTR_SRC, entity.getMediaContentSource().toASCIIString());
        }
        writer.writeEndElement();

        writer.writeStartElement(namespaceMetadata, Constants.PROPERTIES);
        properties(writer, entity.getProperties());
    } else {
        writer.writeAttribute(Constants.ATTR_TYPE, ContentType.APPLICATION_XML.toContentTypeString());
        writer.writeStartElement(namespaceMetadata, Constants.PROPERTIES);
        properties(writer, entity.getProperties());
        writer.writeEndElement();
    }
    writer.writeEndElement();

    for (Annotation annotation : entity.getAnnotations()) {
        annotation(writer, annotation, null);
    }
}

From source file:org.apache.olingo.client.core.serialization.AtomSerializer.java

private void entitySet(final XMLStreamWriter writer, final EntityCollection entitySet)
        throws XMLStreamException, EdmPrimitiveTypeException {
    if (entitySet.getBaseURI() != null) {
        writer.writeAttribute(XMLConstants.XML_NS_URI, Constants.ATTR_XML_BASE,
                entitySet.getBaseURI().toASCIIString());
    }//from w  w w  .ja va2  s .  c  om

    if (entitySet.getCount() != null) {
        writer.writeStartElement(namespaceMetadata, Constants.ATOM_ELEM_COUNT);
        writer.writeCharacters(Integer.toString(entitySet.getCount()));
        writer.writeEndElement();
    }

    if (entitySet.getId() != null) {
        writer.writeStartElement(Constants.ATOM_ELEM_ID);
        writer.writeCharacters(entitySet.getId().toASCIIString());
        writer.writeEndElement();
    }

    common(writer, entitySet);

    for (Entity entity : entitySet) {
        if (entity.getType() == null && entity.getProperties().isEmpty()) {
            entityRef(writer, entity);
        } else {
            writer.writeStartElement(Constants.ATOM_ELEM_ENTRY);
            entity(writer, entity);
            writer.writeEndElement();
        }
    }

    if (serverMode) {
        if (entitySet.getNext() != null) {
            final Link next = new Link();
            next.setRel(Constants.NEXT_LINK_REL);
            next.setHref(entitySet.getNext().toASCIIString());

            links(writer, Collections.<Link>singletonList(next));
        }
        if (entitySet.getDeltaLink() != null) {
            final Link next = new Link();
            next.setRel(Constants.NS_DELTA_LINK_REL);
            next.setHref(entitySet.getDeltaLink().toASCIIString());

            links(writer, Collections.<Link>singletonList(next));
        }
    }
}

From source file:org.apache.olingo.commons.core.data.AbstractAtomDealer.java

protected void namespaces(final XMLStreamWriter writer) throws XMLStreamException {
    writer.writeNamespace(StringUtils.EMPTY, Constants.NS_ATOM);
    writer.writeNamespace(XMLConstants.XML_NS_PREFIX, XMLConstants.XML_NS_URI);
    writer.writeNamespace(Constants.PREFIX_METADATA,
            version.getNamespaceMap().get(ODataServiceVersion.NS_METADATA));
    writer.writeNamespace(Constants.PREFIX_DATASERVICES,
            version.getNamespaceMap().get(ODataServiceVersion.NS_DATASERVICES));
    writer.writeNamespace(Constants.PREFIX_GML, Constants.NS_GML);
    writer.writeNamespace(Constants.PREFIX_GEORSS, Constants.NS_GEORSS);
}