Example usage for javax.xml.stream XMLStreamWriter writeNamespace

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

Introduction

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

Prototype

public void writeNamespace(String prefix, String namespaceURI) throws XMLStreamException;

Source Link

Document

Writes a namespace to the output stream If the prefix argument to this method is the empty string, "xmlns", or null this method will delegate to writeDefaultNamespace

Usage

From source file:edu.jhu.pha.vospace.node.Node.java

public String getXmlMetadata(Detail detail) {

    StringWriter jobWriter = new StringWriter();
    try {/*  ww w .  j a v  a 2 s  .c  o  m*/
        XMLStreamWriter xsw = XMLOutputFactory.newInstance().createXMLStreamWriter(jobWriter);
        xsw.writeStartDocument();

        xsw.setDefaultNamespace(VOS_NAMESPACE);

        xsw.writeStartElement("node");
        xsw.writeNamespace("xsi", XSI_NAMESPACE);
        xsw.writeNamespace(null, VOS_NAMESPACE);
        xsw.writeAttribute("xsi:type", this.getType().getTypeName());
        xsw.writeAttribute("uri", this.getUri().toString());

        if (detail == Detail.max) {
            xsw.writeStartElement("properties");
            Map<String, String> properties = this.getMetastore().getProperties(this.getUri());
            properties.put(LENGTH_PROPERTY, Long.toString(getNodeInfo().getSize()));
            properties.put(DATE_PROPERTY, dropboxDateFormat.format(getNodeInfo().getMtime()));
            if (this.getType() == NodeType.DATA_NODE || this.getType() == NodeType.STRUCTURED_DATA_NODE
                    || this.getType() == NodeType.UNSTRUCTURED_DATA_NODE) {
                properties.put(CONTENTTYPE_PROPERTY, getNodeInfo().getContentType());
            }

            for (String propUri : properties.keySet()) {
                xsw.writeStartElement("property");
                xsw.writeAttribute("uri", propUri);
                xsw.writeCharacters(properties.get(propUri));
                xsw.writeEndElement();
            }

            xsw.writeEndElement();

            xsw.writeStartElement("accepts");
            xsw.writeEndElement();

            xsw.writeStartElement("provides");
            xsw.writeEndElement();

            xsw.writeStartElement("capabilities");
            xsw.writeEndElement();

            if (this.getType() == NodeType.CONTAINER_NODE) {
                NodesList childrenList = ((ContainerNode) this).getDirectChildren(false, 0, -1);
                List<Node> children = childrenList.getNodesList();

                xsw.writeStartElement("nodes");
                for (Node childNode : children) {
                    xsw.writeStartElement("node");
                    xsw.writeAttribute("uri", childNode.getUri().getId().toString());
                    xsw.writeEndElement();
                }
                xsw.writeEndElement();

            }

        }

        xsw.writeEndElement();

        xsw.writeEndDocument();
        xsw.close();
    } catch (XMLStreamException e) {
        e.printStackTrace();
        throw new InternalServerErrorException(e);
    }
    return jobWriter.getBuffer().toString();
}

From source file:de.shadowhunt.subversion.internal.AbstractPropfindOperation.java

@Override
protected HttpUriRequest createRequest() {
    final URI uri = URIUtils.createURI(repository, resource);
    final DavTemplateRequest request = new DavTemplateRequest("PROPFIND", uri);
    request.addHeader("Depth", depth.value);

    final Writer body = new StringBuilderWriter();
    try {//from w w w .  j ava 2 s .  c o m
        final XMLStreamWriter writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(body);
        writer.writeStartDocument(XmlConstants.ENCODING, XmlConstants.VERSION_1_0);
        writer.writeStartElement("propfind");
        writer.writeDefaultNamespace(XmlConstants.DAV_NAMESPACE);
        if (requestedProperties == null) {
            writer.writeEmptyElement("prop");
        } else {
            if (requestedProperties.length == 0) {
                writer.writeEmptyElement("allprop");
            } else {
                writer.writeStartElement("prop");
                if (contains(XmlConstants.SUBVERSION_DAV_NAMESPACE)) {
                    writer.writeNamespace(XmlConstants.SUBVERSION_DAV_PREFIX,
                            XmlConstants.SUBVERSION_DAV_NAMESPACE);
                    writer.setPrefix(XmlConstants.SUBVERSION_DAV_PREFIX, XmlConstants.SUBVERSION_DAV_NAMESPACE);
                }
                if (contains(XmlConstants.SUBVERSION_SVN_NAMESPACE)) {
                    writer.writeNamespace(XmlConstants.SUBVERSION_SVN_PREFIX,
                            XmlConstants.SUBVERSION_SVN_NAMESPACE);
                    writer.setPrefix(XmlConstants.SUBVERSION_SVN_PREFIX, XmlConstants.SUBVERSION_SVN_NAMESPACE);
                }
                for (final ResourceProperty.Key requestedProperty : requestedProperties) {
                    writer.writeEmptyElement(requestedProperty.getType().getPrefix(),
                            requestedProperty.getName());
                }
                writer.writeEndElement(); // prop
            }
        }
        writer.writeEndElement(); // propfind
        writer.writeEndDocument();
        writer.close();
    } catch (final XMLStreamException e) {
        throw new SubversionException("could not create request body", e);
    }

    request.setEntity(new StringEntity(body.toString(), CONTENT_TYPE_XML));
    return request;
}

From source file:org.maodian.flyingcat.xmpp.state.StreamState.java

private void doHandle(XmppContext context, XMLStreamReader xmlsr, XMLStreamWriter xmlsw)
        throws XMLStreamException {
    xmlsr.nextTag();// www. j  a va 2s.  c om
    QName qname = new QName(XmppNamespace.STREAM, "stream");
    if (!xmlsr.getName().equals(qname)) {
        throw new XmppException(StreamError.INVALID_NAMESPACE).set("QName", xmlsr.getName());
    }

    // throw exception if client version > 1.0
    BigDecimal version = new BigDecimal(xmlsr.getAttributeValue("", "version"));
    if (version.compareTo(SUPPORTED_VERSION) > 0) {
        throw new XmppException(StreamError.UNSUPPORTED_VERSION);
    }

    xmlsw.writeStartDocument();
    xmlsw.writeStartElement("stream", "stream", XmppNamespace.STREAM);
    xmlsw.writeNamespace("stream", XmppNamespace.STREAM);
    xmlsw.writeDefaultNamespace(XmppNamespace.CLIENT_CONTENT);

    xmlsw.writeAttribute("id", RandomStringUtils.randomAlphabetic(32));
    xmlsw.writeAttribute("version", "1.0");
    xmlsw.writeAttribute("from", "localhost");
    xmlsw.writeAttribute(XMLConstants.XML_NS_PREFIX, XMLConstants.XML_NS_URI, "lang", "en");
    String from = xmlsr.getAttributeValue(null, "from");
    if (from != null) {
        xmlsw.writeAttribute("to", from);
    }

    // features
    xmlsw.writeStartElement(XmppNamespace.STREAM, "features");
    writeFeatures(xmlsw);
    xmlsw.writeEndElement();
}

From source file:de.qucosa.webapi.v1.SearchResource.java

private ResponseEntity<String> scrollAndBuildResultList(SearchResponse searchResponse)
        throws XMLStreamException, ParseException {
    StringWriter sw = new StringWriter();
    XMLStreamWriter w = xmlOutputFactory.createXMLStreamWriter(sw);

    SearchHits searchHits = searchResponse.getHits();

    w.writeStartDocument("UTF-8", "1.0");
    w.writeStartElement("Opus");
    {/* w w  w  . j a va2 s.c  o m*/
        w.writeStartElement("SearchResult");
        {
            w.writeStartElement("Search");
            w.writeAttribute("hits", String.valueOf(searchHits.getTotalHits()));
            w.writeEndElement();
            w.writeStartElement("ResultList");
            w.writeNamespace(XLINK_NAMESPACE_PREFIX, XLINK_NAMESPACE);

            SearchResponse scrollResponse = searchResponse;
            int hitcount = 0;
            while (true) {
                hitcount = writeResultElements(w, searchHits, hitcount);
                scrollResponse = elasticSearchClient.prepareSearchScroll(scrollResponse.getScrollId())
                        .setScroll(new TimeValue(60, TimeUnit.SECONDS)).execute().actionGet();
                searchHits = scrollResponse.getHits();
                if (searchHits.getHits().length == 0) {
                    log.debug("Stop scrolling at hitcount: {}", hitcount);
                    break;
                }
            }

            w.writeEndElement();
        }
        w.writeEndElement();
    }
    w.writeEndElement();
    w.writeEndDocument();
    w.flush();

    log.debug(sw.toString());

    return new ResponseEntity<>(sw.toString(), HttpStatus.OK);
}

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

/**
 * @param element DOM element//from  ww  w .  j a v  a  2  s.c  o  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:com.microsoft.windowsazure.storage.table.TableParser.java

/**
 * Reserved for internal use. Writes an entity to the stream as an AtomPub Entry Resource, leaving the stream open
 * for additional writing.//from  ww w .  j  a  v a 2  s.c om
 * 
 * @param entity
 *            The instance implementing {@link TableEntity} to write to the output stream.
 * @param isTableEntry
 *            A flag indicating the entity is a reference to a table at the top level of the storage service when
 *            <code>true<code> and a reference to an entity within a table when <code>false</code>.
 * @param xmlw
 *            The <code>XMLStreamWriter</code> to write the entity to.
 * @param opContext
 *            An {@link OperationContext} object used to track the execution of the operation.
 * 
 * @throws XMLStreamException
 *             if an error occurs accessing the stream.
 * @throws StorageException
 *             if a Storage service error occurs.
 */
private static void writeAtomEntity(final TableEntity entity, final boolean isTableEntry,
        final XMLStreamWriter xmlw, final OperationContext opContext)
        throws XMLStreamException, StorageException {
    HashMap<String, EntityProperty> properties = entity.writeEntity(opContext);
    if (properties == null) {
        properties = new HashMap<String, EntityProperty>();
    }

    if (!isTableEntry) {
        Utility.assertNotNull(TableConstants.PARTITION_KEY, entity.getPartitionKey());
        Utility.assertNotNull(TableConstants.ROW_KEY, entity.getRowKey());
        Utility.assertNotNull(TableConstants.TIMESTAMP, entity.getTimestamp());
    }

    // Begin entry
    xmlw.writeStartElement("entry");
    xmlw.writeNamespace("d", ODataConstants.DATA_SERVICES_NS);
    xmlw.writeNamespace("m", ODataConstants.DATA_SERVICES_METADATA_NS);

    // default namespace
    xmlw.writeNamespace(null, ODataConstants.ATOM_NS);

    // Content
    xmlw.writeStartElement(ODataConstants.CONTENT);
    xmlw.writeAttribute(ODataConstants.TYPE, ODataConstants.ODATA_CONTENT_TYPE);

    // m:properties
    xmlw.writeStartElement("m", ODataConstants.PROPERTIES, ODataConstants.DATA_SERVICES_METADATA_NS);

    if (!isTableEntry) {
        // d:PartitionKey
        xmlw.writeStartElement("d", TableConstants.PARTITION_KEY, ODataConstants.DATA_SERVICES_NS);
        xmlw.writeAttribute("xml", "xml", "space", "preserve");
        xmlw.writeCharacters(entity.getPartitionKey());
        xmlw.writeEndElement();

        // d:RowKey
        xmlw.writeStartElement("d", TableConstants.ROW_KEY, ODataConstants.DATA_SERVICES_NS);
        xmlw.writeAttribute("xml", "xml", "space", "preserve");
        xmlw.writeCharacters(entity.getRowKey());
        xmlw.writeEndElement();

        // d:Timestamp
        if (entity.getTimestamp() == null) {
            entity.setTimestamp(new Date());
        }

        xmlw.writeStartElement("d", TableConstants.TIMESTAMP, ODataConstants.DATA_SERVICES_NS);
        xmlw.writeAttribute("m", ODataConstants.DATA_SERVICES_METADATA_NS, ODataConstants.TYPE,
                EdmType.DATE_TIME.toString());
        xmlw.writeCharacters(Utility.getTimeByZoneAndFormat(entity.getTimestamp(), Utility.UTC_ZONE,
                Utility.ISO8061_LONG_PATTERN));
        xmlw.writeEndElement();
    }

    for (final Entry<String, EntityProperty> ent : properties.entrySet()) {
        if (ent.getKey().equals(TableConstants.PARTITION_KEY) || ent.getKey().equals(TableConstants.ROW_KEY)
                || ent.getKey().equals(TableConstants.TIMESTAMP) || ent.getKey().equals("Etag")) {
            continue;
        }

        EntityProperty currProp = ent.getValue();

        // d:PropName
        xmlw.writeStartElement("d", ent.getKey(), ODataConstants.DATA_SERVICES_NS);

        if (currProp.getEdmType() == EdmType.STRING) {
            xmlw.writeAttribute("xml", "xml", "space", "preserve");
        } else if (currProp.getEdmType().toString().length() != 0) {
            String edmTypeString = currProp.getEdmType().toString();
            if (edmTypeString.length() != 0) {
                xmlw.writeAttribute("m", ODataConstants.DATA_SERVICES_METADATA_NS, ODataConstants.TYPE,
                        edmTypeString);
            }
        }

        if (currProp.getIsNull()) {
            xmlw.writeAttribute("m", ODataConstants.DATA_SERVICES_METADATA_NS, ODataConstants.NULL,
                    Constants.TRUE);
        }

        // Write Value
        xmlw.writeCharacters(currProp.getValueAsString());
        // End d:PropName
        xmlw.writeEndElement();
    }

    // End m:properties
    xmlw.writeEndElement();

    // End content
    xmlw.writeEndElement();

    // End entry
    xmlw.writeEndElement();
}

From source file:de.qucosa.webapi.v1.DocumentResource.java

private String getDocumentCreatedResponse(String id) throws XMLStreamException {
    StringWriter sw = new StringWriter();
    XMLStreamWriter w = xmlOutputFactory.createXMLStreamWriter(sw);
    w.writeStartDocument("UTF-8", "1.0");
    w.writeStartElement("Opus");
    w.writeStartElement("Opus_Document");
    w.writeNamespace(XLINK_NAMESPACE_PREFIX, XLINK_NAMESPACE);
    w.writeAttribute(XLINK_NAMESPACE, "href", getHrefLink(id));
    w.writeAttribute("id", id);
    w.writeEndElement();// w ww.j  a  v  a2 s .c om
    w.writeEndElement();
    w.writeEndDocument();
    w.flush();
    return sw.toString();
}

From source file:de.qucosa.webapi.v1.DocumentResource.java

@RequestMapping(value = "/document", method = RequestMethod.GET)
public ResponseEntity<String> listAll() throws IOException, FedoraClientException, XMLStreamException {
    List<String> pids = fedoraRepository.getPIDsByPattern("^qucosa:");

    StringWriter sw = new StringWriter();
    XMLStreamWriter w = xmlOutputFactory.createXMLStreamWriter(sw);
    w.writeStartDocument("UTF-8", "1.0");
    w.writeStartElement("Opus");
    w.writeAttribute("version", "2.0");
    w.writeStartElement("DocumentList");
    w.writeNamespace("xlink", "http://www.w3.org/1999/xlink");
    for (String pid : pids) {
        String nr = pid.substring(pid.lastIndexOf(':') + 1);
        String href = getHrefLink(nr);
        w.writeEmptyElement("Document");
        w.writeAttribute("xlink:href", href);
        w.writeAttribute("xlink:nr", nr);
        w.writeAttribute("xlink:type", "simple");
    }/*from w ww .j  a va 2s .c om*/
    w.writeEndElement();
    w.writeEndElement();
    w.writeEndDocument();
    w.flush();

    return new ResponseEntity<>(sw.toString(), HttpStatus.OK);
}

From source file:de.shadowhunt.subversion.internal.MergeOperation.java

@Override
protected HttpUriRequest createRequest() {
    final DavTemplateRequest request = new DavTemplateRequest("MERGE", repository);
    request.addHeader("X-SVN-Options", "release-locks");

    final Writer body = new StringBuilderWriter();
    try {//  w  ww. jav a 2  s.c  o m
        final XMLStreamWriter writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(body);
        writer.writeStartDocument(XmlConstants.ENCODING, XmlConstants.VERSION_1_0);
        writer.writeStartElement("merge");
        writer.writeDefaultNamespace(XmlConstants.DAV_NAMESPACE);
        writer.writeStartElement("source");
        writer.writeStartElement("href");
        writer.writeCData(repository.getPath() + resource.getValue());
        writer.writeEndElement(); // href
        writer.writeEndElement(); // source
        writer.writeEmptyElement("no-auto-merge");
        writer.writeEmptyElement("no-checkout");
        writer.writeStartElement("prop");
        writer.writeEmptyElement("checked-in");
        writer.writeEmptyElement("version-name");
        writer.writeEmptyElement("resourcetype");
        writer.writeEmptyElement("creationdate");
        writer.writeEmptyElement("creator-displayname");
        writer.writeEndElement(); // prop
        if (!infoSet.isEmpty()) {
            writer.setPrefix(XmlConstants.SVN_PREFIX, XmlConstants.SVN_NAMESPACE);
            writer.writeStartElement(XmlConstants.SVN_NAMESPACE, "lock-token-list");
            writer.writeNamespace(XmlConstants.SVN_PREFIX, XmlConstants.SVN_NAMESPACE);
            for (final Info info : infoSet) {
                final String lockToken = info.getLockToken();
                assert (lockToken != null) : "must not be null";
                final Resource infoResource = info.getResource();

                writer.writeStartElement(XmlConstants.SVN_NAMESPACE, "lock");
                writer.writeStartElement(XmlConstants.SVN_NAMESPACE, "lock-path");
                writer.writeCData(infoResource.getValueWithoutLeadingSeparator());
                writer.writeEndElement(); // lock-path
                writer.writeStartElement(XmlConstants.SVN_NAMESPACE, "lock-token");
                writer.writeCharacters(lockToken);
                writer.writeEndElement(); // lock-token
                writer.writeEndElement(); // lock
            }
            writer.writeEndElement(); // lock-token-list
        }
        writer.writeEndElement(); // merge
        writer.writeEndDocument();
        writer.close();
    } catch (final XMLStreamException e) {
        throw new SubversionException("could not create request body", e);
    }

    request.setEntity(new StringEntity(body.toString(), CONTENT_TYPE_XML));
    return request;
}

From source file:eionet.cr.util.odp.ODPDatasetsPacker.java

/**
 * @param writer//  w w w  . ja va  2 s  .com
 * @throws XMLStreamException
 */
private void writeManifestHeader(XMLStreamWriter writer) throws XMLStreamException {

    // Start the XML document
    writer.writeStartDocument(ENCODING, "1.0");

    // Register all relevant namespaces.
    registerNamespaces(MANIFEST_FILE_NAMESPACES, writer);

    // Write root element start tag (i.e. <ecodp:manifest>)
    writer.writeStartElement(Namespace.ECODP.getUri(), "manifest");

    // Write namespace prefixes in the root element start tag.
    for (Namespace namespace : MANIFEST_FILE_NAMESPACES) {
        writer.writeNamespace(namespace.getPrefix(), namespace.getUri());
    }

    // It's ok to instantiate SimpleDateFormat every time here, since this method gets called once per package generation.
    String packageId = PACKAGE_ID_PREFIX + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());

    String generationDateTime = Util.virtuosoDateToString(new Date());
    writer.writeAttribute(Namespace.ECODP.getUri(), "creation-date-time", generationDateTime);
    writer.writeAttribute(Namespace.ECODP.getUri(), "package-id", packageId);
    writer.writeAttribute(Namespace.ECODP.getUri(), "priority", "normal");
    writer.writeAttribute(Namespace.ECODP.getUri(), "publisher",
            "http://publications.europa.eu/resource/authority/corporate-body/CNECT");
    writer.writeAttribute(Namespace.ECODP.getUri(), "version", "1.0");
    writer.writeAttribute(Namespace.XSI.getUri(), "schemaLocation",
            "http://open-data.europa.eu/ontologies/protocol-v1.0/odp-protocol.xsd");
}