Example usage for javax.xml.stream XMLStreamWriter writeStartDocument

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

Introduction

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

Prototype

public void writeStartDocument() throws XMLStreamException;

Source Link

Document

Write the XML Declaration.

Usage

From source file:org.gaul.s3proxy.S3ProxyHandler.java

private void handleListMultipartUploads(HttpServletRequest request, HttpServletResponse response,
        BlobStore blobStore, String container) throws IOException, S3Exception {
    if (request.getParameter("delimiter") != null || request.getParameter("prefix") != null
            || request.getParameter("max-uploads") != null || request.getParameter("key-marker") != null
            || request.getParameter("upload-id-marker") != null) {
        throw new UnsupportedOperationException();
    }//from  w ww. jav a2s  .c  om

    List<MultipartUpload> uploads = blobStore.listMultipartUploads(container);

    try (Writer writer = response.getWriter()) {
        XMLStreamWriter xml = xmlOutputFactory.createXMLStreamWriter(writer);
        xml.writeStartDocument();
        xml.writeStartElement("ListMultipartUploadsResult");
        xml.writeDefaultNamespace(AWS_XMLNS);

        writeSimpleElement(xml, "Bucket", container);

        // TODO: bogus values
        xml.writeEmptyElement("KeyMarker");
        xml.writeEmptyElement("UploadIdMarker");
        xml.writeEmptyElement("NextKeyMarker");
        xml.writeEmptyElement("NextUploadIdMarker");
        xml.writeEmptyElement("Delimiter");
        xml.writeEmptyElement("Prefix");
        writeSimpleElement(xml, "MaxUploads", "1000");
        writeSimpleElement(xml, "IsTruncated", "false");

        for (MultipartUpload upload : uploads) {
            xml.writeStartElement("Upload");

            writeSimpleElement(xml, "Key", upload.blobName());
            writeSimpleElement(xml, "UploadId", upload.id());
            writeInitiatorStanza(xml);
            writeOwnerStanza(xml);
            writeSimpleElement(xml, "StorageClass", "STANDARD");

            // TODO: bogus value
            writeSimpleElement(xml, "Initiated",
                    blobStore.getContext().utils().date().iso8601DateFormat(new Date()));

            xml.writeEndElement();
        }

        // TODO: CommonPrefixes

        xml.writeEndElement();

        xml.flush();
    } catch (XMLStreamException xse) {
        throw new IOException(xse);
    }
}

From source file:org.gaul.s3proxy.S3ProxyHandler.java

private void handleCopyBlob(HttpServletRequest request, HttpServletResponse response, InputStream is,
        BlobStore blobStore, String destContainerName, String destBlobName) throws IOException, S3Exception {
    String copySourceHeader = request.getHeader("x-amz-copy-source");
    copySourceHeader = URLDecoder.decode(copySourceHeader, "UTF-8");
    if (copySourceHeader.startsWith("/")) {
        // Some clients like boto do not include the leading slash
        copySourceHeader = copySourceHeader.substring(1);
    }//from  www .j a  v a2  s  . c  o m
    String[] path = copySourceHeader.split("/", 2);
    if (path.length != 2) {
        throw new S3Exception(S3ErrorCode.INVALID_REQUEST);
    }
    String sourceContainerName = path[0];
    String sourceBlobName = path[1];
    boolean replaceMetadata = "REPLACE".equalsIgnoreCase(request.getHeader("x-amz-metadata-directive"));

    if (sourceContainerName.equals(destContainerName) && sourceBlobName.equals(destBlobName)
            && !replaceMetadata) {
        throw new S3Exception(S3ErrorCode.INVALID_REQUEST);
    }

    CopyOptions.Builder options = CopyOptions.builder();

    String ifMatch = request.getHeader("x-amz-copy-source-if-match");
    if (ifMatch != null) {
        options.ifMatch(ifMatch);
    }
    String ifNoneMatch = request.getHeader("x-amz-copy-source-if-none-match");
    if (ifNoneMatch != null) {
        options.ifNoneMatch(ifNoneMatch);
    }
    long ifModifiedSince = request.getDateHeader("x-amz-copy-source-if-modified-since");
    if (ifModifiedSince != -1) {
        options.ifModifiedSince(new Date(ifModifiedSince));
    }
    long ifUnmodifiedSince = request.getDateHeader("x-amz-copy-source-if-unmodified-since");
    if (ifUnmodifiedSince != -1) {
        options.ifUnmodifiedSince(new Date(ifUnmodifiedSince));
    }

    if (replaceMetadata) {
        ContentMetadataBuilder contentMetadata = ContentMetadataBuilder.create();
        ImmutableMap.Builder<String, String> userMetadata = ImmutableMap.builder();
        for (String headerName : Collections.list(request.getHeaderNames())) {
            String headerValue = Strings.nullToEmpty(request.getHeader(headerName));
            if (headerName.equalsIgnoreCase(HttpHeaders.CACHE_CONTROL)) {
                contentMetadata.cacheControl(headerValue);
            } else if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_DISPOSITION)) {
                contentMetadata.contentDisposition(headerValue);
            } else if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_ENCODING)) {
                contentMetadata.contentEncoding(headerValue);
            } else if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_LANGUAGE)) {
                contentMetadata.contentLanguage(headerValue);
            } else if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_TYPE)) {
                contentMetadata.contentType(headerValue);
            } else if (startsWithIgnoreCase(headerName, USER_METADATA_PREFIX)) {
                userMetadata.put(headerName.substring(USER_METADATA_PREFIX.length()), headerValue);
            }
            // TODO: Expires
        }
        options.contentMetadata(contentMetadata.build());
        options.userMetadata(userMetadata.build());
    }

    String eTag;
    try {
        eTag = blobStore.copyBlob(sourceContainerName, sourceBlobName, destContainerName, destBlobName,
                options.build());
    } catch (KeyNotFoundException knfe) {
        throw new S3Exception(S3ErrorCode.NO_SUCH_KEY, knfe);
    }

    // TODO: jclouds should include this in CopyOptions
    String cannedAcl = request.getHeader("x-amz-acl");
    if (cannedAcl != null && !cannedAcl.equalsIgnoreCase("private")) {
        handleSetBlobAcl(request, response, is, blobStore, destContainerName, destBlobName);
    }

    BlobMetadata blobMetadata = blobStore.blobMetadata(destContainerName, destBlobName);
    try (Writer writer = response.getWriter()) {
        XMLStreamWriter xml = xmlOutputFactory.createXMLStreamWriter(writer);
        xml.writeStartDocument();
        xml.writeStartElement("CopyObjectResult");
        xml.writeDefaultNamespace(AWS_XMLNS);

        writeSimpleElement(xml, "LastModified", formatDate(blobMetadata.getLastModified()));
        writeSimpleElement(xml, "ETag", maybeQuoteETag(eTag));

        xml.writeEndElement();
        xml.flush();
    } catch (XMLStreamException xse) {
        throw new IOException(xse);
    }
}

From source file:edu.ucsd.library.dams.api.DAMSAPIServlet.java

private void sparqlQuery(String sparql, TripleStore ts, Map<String, String[]> params, String pathInfo,
        HttpServletResponse res) throws Exception {
    if (sparql == null) {
        Map err = error(SC_BAD_REQUEST, "No query specified.", null);
        output(err, params, pathInfo, res);
        return;/*from w w w. java2 s  . co m*/
    } else {
        log.info("sparql: " + sparql);
    }

    // sparql query
    BindingIterator objs = ts.sparqlSelect(sparql);

    // start output
    String sparqlNS = "http://www.w3.org/2005/sparql-results#";
    res.setContentType("application/sparql-results+xml");
    OutputStream out = res.getOutputStream();
    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    XMLStreamWriter stream = factory.createXMLStreamWriter(out);
    stream.setDefaultNamespace(sparqlNS);
    stream.writeStartDocument();
    stream.writeStartElement("sparql");

    // output bindings
    boolean headerWritten = false;
    while (objs.hasNext()) {
        Map<String, String> binding = objs.nextBinding();

        // write header on first binding
        if (!headerWritten) {
            Iterator<String> it = binding.keySet().iterator();
            stream.writeStartElement("head");
            while (it.hasNext()) {
                String k = it.next();
                stream.writeStartElement("variable");
                stream.writeAttribute("name", k);
                stream.writeEndElement();
            }
            stream.writeEndElement();
            stream.writeStartElement("results"); // ordered='false' distinct='false'
            headerWritten = true;
        }

        stream.writeStartElement("result");
        Iterator<String> it = binding.keySet().iterator();
        while (it.hasNext()) {
            String k = it.next();
            String v = binding.get(k);
            stream.writeStartElement("binding");
            stream.writeAttribute("name", k);
            String type = null;
            if (v.startsWith("\"") && v.endsWith("\"")) {
                type = "literal";
                v = v.substring(1, v.length() - 1);
            } else if (v.startsWith("_:")) {
                type = "bnode";
                v = v.substring(2);
            } else {
                type = "uri";
            }
            stream.writeStartElement(type);
            stream.writeCharacters(v);
            stream.writeEndElement();
            stream.writeEndElement();
        }
        stream.writeEndElement();
    }

    // finish output
    stream.writeEndElement();
    stream.writeEndDocument();
    stream.flush();
    stream.close();
}

From source file:nl.nn.adapterframework.extensions.svn.ScanTibcoSolutionPipe.java

public PipeRunResult doPipe(Object input, IPipeLineSession session) throws PipeRunException {
    StringWriter stringWriter = new StringWriter();
    XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
    XMLStreamWriter xmlStreamWriter;
    try {// w w  w  .j  av  a2  s .c om
        xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(stringWriter);
        xmlStreamWriter.writeStartDocument();
        xmlStreamWriter.writeStartElement("root");
        xmlStreamWriter.writeAttribute("url", getUrl());
        // xmlStreamWriter.writeAttribute("level",
        // String.valueOf(getLevel()));
        process(xmlStreamWriter, getUrl(), getLevel());
        xmlStreamWriter.writeEndDocument();
        xmlStreamWriter.flush();
        xmlStreamWriter.close();
    } catch (XMLStreamException e) {
        throw new PipeRunException(this, "XMLStreamException", e);
    } catch (DomBuilderException e) {
        throw new PipeRunException(this, "DomBuilderException", e);
    } catch (XPathExpressionException e) {
        throw new PipeRunException(this, "XPathExpressionException", e);
    }

    return new PipeRunResult(getForward(), stringWriter.getBuffer().toString());
}

From source file:org.apache.axis2.fastinfoset.FastInfosetPOXMessageFormatter.java

/**
 * Retrieves the raw bytes from the SOAP envelop.
 * //w  w  w .j  a va  2 s .  com
 * @see org.apache.axis2.transport.MessageFormatter#getBytes(org.apache.axis2.context.MessageContext, org.apache.axiom.om.OMOutputFormat)
 */
public byte[] getBytes(MessageContext messageContext, OMOutputFormat format) throws AxisFault {
    //For POX drop the SOAP envelope and use the message body
    OMElement element = messageContext.getEnvelope().getBody().getFirstElement();
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();

    try {
        //Creates StAX document serializer which actually implements the XMLStreamWriter
        XMLStreamWriter streamWriter = new StAXDocumentSerializer(outStream);
        //Since we drop the SOAP envelop we have to manually write the start document and the end document events
        streamWriter.writeStartDocument();
        element.serializeAndConsume(streamWriter);
        streamWriter.writeEndDocument();

        return outStream.toByteArray();

    } catch (XMLStreamException xmlse) {
        logger.error(xmlse.getMessage());
        throw new AxisFault(xmlse.getMessage(), xmlse);
    }
}

From source file:org.apache.axis2.fastinfoset.FastInfosetPOXMessageFormatter.java

/**
 * Write the SOAP envelop to the given OutputStream.
 * //from   ww  w.j  a  v a 2 s .c o  m
 * @see org.apache.axis2.transport.MessageFormatter#writeTo(org.apache.axis2.context.MessageContext, org.apache.axiom.om.OMOutputFormat, java.io.OutputStream, boolean)
 */
public void writeTo(MessageContext messageContext, OMOutputFormat format, OutputStream outputStream,
        boolean preserve) throws AxisFault {
    //For POX drop the SOAP envelope and use the message body
    OMElement element = messageContext.getEnvelope().getBody().getFirstElement();

    try {
        //Create the StAX document serializer
        XMLStreamWriter streamWriter = new StAXDocumentSerializer(outputStream);
        //Since we drop the SOAP envelop we have to manually write the start document and the end document events         
        streamWriter.writeStartDocument();
        if (preserve) {
            element.serialize(streamWriter);
        } else {
            element.serializeAndConsume(streamWriter);
        }
        streamWriter.writeEndDocument();
    } catch (XMLStreamException xmlse) {
        logger.error(xmlse.getMessage());
        throw new AxisFault(xmlse.getMessage(), xmlse);
    }
}

From source file:org.apache.flex.compiler.config.Configuration.java

/**
 * @return Metadata XML string./*from ww  w  . j  a va 2s  .co m*/
 */
private final String generateMetadata() {
    final XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
    assert xmlOutputFactory != null : "Expect XMLOutputFactory implementation.";
    final StringWriter stringWriter = new StringWriter();
    XMLStreamWriter xmlWriter = null;

    try {
        xmlWriter = new XMLFormatter(xmlOutputFactory.createXMLStreamWriter(stringWriter));
        xmlWriter.writeStartDocument();

        xmlWriter.writeStartElement("rdf", "RDF", RDF_URI);
        xmlWriter.setPrefix("rdf", RDF_URI);
        xmlWriter.writeNamespace("rdf", RDF_URI);

        // write rdf:Description
        xmlWriter.writeStartElement(RDF_URI, "Description");
        xmlWriter.setPrefix("dc", DC_URI);
        xmlWriter.setPrefix(VersionInfo.COMPILER_NAMESPACE_PREFIX, VersionInfo.COMPILER_NAMESPACE_URI);
        xmlWriter.writeNamespace("dc", DC_URI);
        xmlWriter.writeNamespace(VersionInfo.COMPILER_NAMESPACE_PREFIX, VersionInfo.COMPILER_NAMESPACE_URI);

        // write dc:format
        xmlWriter.writeStartElement(DC_URI, "format");
        xmlWriter.writeCharacters("application/x-shockwave-flash");
        xmlWriter.writeEndElement();

        if (isFlex()) {
            // write localizedTitles
            writeMap(xmlWriter, DC_URI, "description", localizedDescriptions);

            // write localizedDescription
            writeMap(xmlWriter, DC_URI, "title", localizedTitles);

            // write publisher
            writeCollection(xmlWriter, DC_URI, "publisher", publishers);

            // write creators
            writeCollection(xmlWriter, DC_URI, "creator", creators);

            // write contributor
            writeCollection(xmlWriter, DC_URI, "contributor", contributors);

            // write language
            writeCollection(xmlWriter, DC_URI, "language", langs);

            // write date
            writeDate(xmlWriter);
        }

        // write compiledBy
        writeCompiledBy(xmlWriter);

        // write
        xmlWriter.writeEndElement(); // Description
        xmlWriter.writeEndDocument();
    } catch (XMLStreamException e) {
        return "";
    }

    return stringWriter.toString();
}

From source file:org.apache.nifi.authorization.FileAccessPolicyProvider.java

@Override
public String getFingerprint() throws AuthorizationAccessException {
    final List<AccessPolicy> policies = new ArrayList<>(getAccessPolicies());
    Collections.sort(policies, Comparator.comparing(AccessPolicy::getIdentifier));

    XMLStreamWriter writer = null;
    final StringWriter out = new StringWriter();
    try {//from  w  w  w.j  a va  2  s .  c o  m
        writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(out);
        writer.writeStartDocument();
        writer.writeStartElement("accessPolicies");

        for (AccessPolicy policy : policies) {
            writePolicy(writer, policy);
        }

        writer.writeEndElement();
        writer.writeEndDocument();
        writer.flush();
    } catch (XMLStreamException e) {
        throw new AuthorizationAccessException("Unable to generate fingerprint", e);
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (XMLStreamException e) {
                // nothing to do here
            }
        }
    }

    return out.toString();
}

From source file:org.apache.nifi.authorization.FileUserGroupProvider.java

@Override
public String getFingerprint() throws AuthorizationAccessException {
    final UserGroupHolder usersAndGroups = userGroupHolder.get();

    final List<User> users = new ArrayList<>(usersAndGroups.getAllUsers());
    Collections.sort(users, Comparator.comparing(User::getIdentifier));

    final List<Group> groups = new ArrayList<>(usersAndGroups.getAllGroups());
    Collections.sort(groups, Comparator.comparing(Group::getIdentifier));

    XMLStreamWriter writer = null;
    final StringWriter out = new StringWriter();
    try {/*from ww  w.  j  a  v a 2  s . c  o m*/
        writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(out);
        writer.writeStartDocument();
        writer.writeStartElement("tenants");

        for (User user : users) {
            writeUser(writer, user);
        }
        for (Group group : groups) {
            writeGroup(writer, group);
        }

        writer.writeEndElement();
        writer.writeEndDocument();
        writer.flush();
    } catch (XMLStreamException e) {
        throw new AuthorizationAccessException("Unable to generate fingerprint", e);
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (XMLStreamException e) {
                // nothing to do here
            }
        }
    }

    return out.toString();
}