Example usage for javax.xml.stream XMLStreamWriter writeDefaultNamespace

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

Introduction

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

Prototype

public void writeDefaultNamespace(String namespaceURI) throws XMLStreamException;

Source Link

Document

Writes the default namespace to the stream

Usage

From source file:ca.uhn.fhir.parser.XmlParser.java

@Override
public void encodeTagListToWriter(TagList theTagList, Writer theWriter) throws IOException {
    try {/*from w w  w .  j  av  a 2  s . c o m*/
        XMLStreamWriter eventWriter = createXmlWriter(theWriter);

        eventWriter.writeStartElement(TagList.ELEMENT_NAME_LC);
        eventWriter.writeDefaultNamespace(FHIR_NS);

        for (Tag next : theTagList) {
            eventWriter.writeStartElement(TagList.ATTR_CATEGORY);

            if (isNotBlank(next.getTerm())) {
                eventWriter.writeAttribute(Tag.ATTR_TERM, next.getTerm());
            }
            if (isNotBlank(next.getLabel())) {
                eventWriter.writeAttribute(Tag.ATTR_LABEL, next.getLabel());
            }
            if (isNotBlank(next.getScheme())) {
                eventWriter.writeAttribute(Tag.ATTR_SCHEME, next.getScheme());
            }

            eventWriter.writeEndElement();
        }

        eventWriter.writeEndElement();
        eventWriter.close();
    } catch (XMLStreamException e) {
        throw new ConfigurationException("Failed to initialize STaX event factory", e);
    }
}

From source file:ca.uhn.fhir.parser.XmlParser.java

private void encodeBundleToWriterDstu2(Bundle theBundle, XMLStreamWriter theEventWriter)
        throws XMLStreamException {
    theEventWriter.writeStartElement("Bundle");
    theEventWriter.writeDefaultNamespace(FHIR_NS);

    writeOptionalTagWithValue(theEventWriter, "id", theBundle.getId().getIdPart());

    InstantDt updated = (InstantDt) theBundle.getResourceMetadata().get(ResourceMetadataKeyEnum.UPDATED);
    IdDt bundleId = theBundle.getId();//from   ww w . j a  va  2  s.co m
    if (bundleId != null && isNotBlank(bundleId.getVersionIdPart())
            || (updated != null && !updated.isEmpty())) {
        theEventWriter.writeStartElement("meta");
        writeOptionalTagWithValue(theEventWriter, "versionId", bundleId.getVersionIdPart());
        if (updated != null) {
            writeOptionalTagWithValue(theEventWriter, "lastUpdated", updated.getValueAsString());
        }
        theEventWriter.writeEndElement();
    }

    writeOptionalTagWithValue(theEventWriter, "type", theBundle.getType().getValue());
    writeOptionalTagWithValue(theEventWriter, "total", theBundle.getTotalResults().getValueAsString());

    writeBundleResourceLink(theEventWriter, "first", theBundle.getLinkFirst());
    writeBundleResourceLink(theEventWriter, "previous", theBundle.getLinkPrevious());
    writeBundleResourceLink(theEventWriter, "next", theBundle.getLinkNext());
    writeBundleResourceLink(theEventWriter, "last", theBundle.getLinkLast());
    writeBundleResourceLink(theEventWriter, "self", theBundle.getLinkSelf());

    for (BundleEntry nextEntry : theBundle.getEntries()) {
        theEventWriter.writeStartElement("entry");

        boolean deleted = false;
        if (nextEntry.getDeletedAt() != null && nextEntry.getDeletedAt().isEmpty() == false) {
            deleted = true;
        }

        writeBundleResourceLink(theEventWriter, "alternate", nextEntry.getLinkAlternate());

        if (nextEntry.getResource() != null && nextEntry.getResource().getId().getBaseUrl() != null) {
            writeOptionalTagWithValue(theEventWriter, "fullUrl", nextEntry.getResource().getId().getValue());
        }

        IResource resource = nextEntry.getResource();
        if (resource != null && !resource.isEmpty() && !deleted) {
            theEventWriter.writeStartElement("resource");
            encodeResourceToXmlStreamWriter(resource, theEventWriter, false, true);
            theEventWriter.writeEndElement(); // content
        } else {
            ourLog.debug("Bundle entry contains null resource");
        }

        if (nextEntry.getSearchMode().isEmpty() == false || nextEntry.getScore().isEmpty() == false) {
            theEventWriter.writeStartElement("search");
            writeOptionalTagWithValue(theEventWriter, "mode", nextEntry.getSearchMode().getValueAsString());
            writeOptionalTagWithValue(theEventWriter, "score", nextEntry.getScore().getValueAsString());
            theEventWriter.writeEndElement();
            // IResource nextResource = nextEntry.getResource();
        }

        if (nextEntry.getTransactionMethod().isEmpty() == false
                || nextEntry.getLinkSearch().isEmpty() == false) {
            theEventWriter.writeStartElement("request");
            writeOptionalTagWithValue(theEventWriter, "method", nextEntry.getTransactionMethod().getValue());
            writeOptionalTagWithValue(theEventWriter, "url", nextEntry.getLinkSearch().getValue());
            theEventWriter.writeEndElement();
        }

        if (deleted) {
            theEventWriter.writeStartElement("deleted");
            writeOptionalTagWithValue(theEventWriter, "type", nextEntry.getId().getResourceType());
            writeOptionalTagWithValue(theEventWriter, "id", nextEntry.getId().getIdPart());
            writeOptionalTagWithValue(theEventWriter, "versionId", nextEntry.getId().getVersionIdPart());
            writeOptionalTagWithValue(theEventWriter, "instant", nextEntry.getDeletedAt().getValueAsString());
            theEventWriter.writeEndElement();
        }

        theEventWriter.writeEndElement(); // entry
    }

    theEventWriter.writeEndElement();
    theEventWriter.close();
}

From source file:ca.uhn.fhir.parser.XmlParser.java

private void encodeBundleToWriterDstu1(Bundle theBundle, XMLStreamWriter eventWriter)
        throws XMLStreamException {
    eventWriter.writeStartElement("feed");
    eventWriter.writeDefaultNamespace(ATOM_NS);

    writeTagWithTextNode(eventWriter, "title", theBundle.getTitle());
    writeTagWithTextNode(eventWriter, "id", theBundle.getBundleId());

    writeAtomLink(eventWriter, Constants.LINK_SELF, theBundle.getLinkSelf());
    writeAtomLink(eventWriter, Constants.LINK_FIRST, theBundle.getLinkFirst());
    writeAtomLink(eventWriter, Constants.LINK_PREVIOUS, theBundle.getLinkPrevious());
    writeAtomLink(eventWriter, Constants.LINK_NEXT, theBundle.getLinkNext());
    writeAtomLink(eventWriter, Constants.LINK_LAST, theBundle.getLinkLast());
    writeAtomLink(eventWriter, Constants.LINK_FHIR_BASE, theBundle.getLinkBase());

    if (theBundle.getTotalResults().getValue() != null) {
        eventWriter.writeStartElement("os", "totalResults", OPENSEARCH_NS);
        eventWriter.writeNamespace("os", OPENSEARCH_NS);
        eventWriter.writeCharacters(theBundle.getTotalResults().getValue().toString());
        eventWriter.writeEndElement();//from   w w w.  j  ava2  s .  com
    }

    writeOptionalTagWithTextNode(eventWriter, "updated", theBundle.getUpdated());

    writeAuthor(eventWriter, theBundle);

    writeCategories(eventWriter, theBundle.getCategories());

    for (BundleEntry nextEntry : theBundle.getEntries()) {
        boolean deleted = false;
        if (nextEntry.getDeletedAt() != null && nextEntry.getDeletedAt().isEmpty() == false) {
            deleted = true;
            eventWriter.writeStartElement("at", "deleted-entry", TOMBSTONES_NS);
            eventWriter.writeNamespace("at", TOMBSTONES_NS);

            if (nextEntry.getDeletedResourceId().isEmpty()) {
                writeOptionalAttribute(eventWriter, "ref", nextEntry.getId().getValueAsString());
            } else {
                writeOptionalAttribute(eventWriter, "ref", nextEntry.getDeletedResourceId().getValueAsString());
            }

            writeOptionalAttribute(eventWriter, "when", nextEntry.getDeletedAt().getValueAsString());
            if (nextEntry.getDeletedByEmail().isEmpty() == false
                    || nextEntry.getDeletedByName().isEmpty() == false) {
                eventWriter.writeStartElement(TOMBSTONES_NS, "by");
                if (nextEntry.getDeletedByName().isEmpty() == false) {
                    eventWriter.writeStartElement(TOMBSTONES_NS, "name");
                    eventWriter.writeCharacters(nextEntry.getDeletedByName().getValue());
                    eventWriter.writeEndElement();
                }
                if (nextEntry.getDeletedByEmail().isEmpty() == false) {
                    eventWriter.writeStartElement(TOMBSTONES_NS, "email");
                    eventWriter.writeCharacters(nextEntry.getDeletedByEmail().getValue());
                    eventWriter.writeEndElement();
                }
                eventWriter.writeEndElement();
            }
            if (nextEntry.getDeletedComment().isEmpty() == false) {
                eventWriter.writeStartElement(TOMBSTONES_NS, "comment");
                eventWriter.writeCharacters(nextEntry.getDeletedComment().getValue());
                eventWriter.writeEndElement();
            }
        } else {
            eventWriter.writeStartElement("entry");
        }

        writeOptionalTagWithTextNode(eventWriter, "title", nextEntry.getTitle());
        if (!deleted) {
            if (nextEntry.getId().isEmpty() == false) {
                writeTagWithTextNode(eventWriter, "id", nextEntry.getId());
            } else {
                writeTagWithTextNode(eventWriter, "id", nextEntry.getResource().getId());
            }
        }
        writeOptionalTagWithTextNode(eventWriter, "updated", nextEntry.getUpdated());
        writeOptionalTagWithTextNode(eventWriter, "published", nextEntry.getPublished());

        writeAuthor(eventWriter, nextEntry);

        writeCategories(eventWriter, nextEntry.getCategories());

        if (!nextEntry.getLinkSelf().isEmpty()) {
            writeAtomLink(eventWriter, "self", nextEntry.getLinkSelf());
        }

        if (!nextEntry.getLinkAlternate().isEmpty()) {
            writeAtomLink(eventWriter, "alternate", nextEntry.getLinkAlternate());
        }

        if (!nextEntry.getLinkSearch().isEmpty()) {
            writeAtomLink(eventWriter, "search", nextEntry.getLinkSearch());
        }

        IResource resource = nextEntry.getResource();
        if (resource != null && !resource.isEmpty() && !deleted) {
            eventWriter.writeStartElement("content");
            eventWriter.writeAttribute("type", "text/xml");
            encodeResourceToXmlStreamWriter(resource, eventWriter, false, true);
            eventWriter.writeEndElement(); // content
        } else {
            ourLog.debug("Bundle entry contains null resource");
        }

        if (!nextEntry.getSummary().isEmpty()) {
            eventWriter.writeStartElement("summary");
            eventWriter.writeAttribute("type", "xhtml");
            encodeXhtml(nextEntry.getSummary(), eventWriter);
            eventWriter.writeEndElement();
        }

        eventWriter.writeEndElement(); // entry
    }

    eventWriter.writeEndElement();
    eventWriter.close();
}

From source file:ca.uhn.fhir.parser.XmlParser.java

private void encodeResourceToXmlStreamWriter(IBaseResource theResource, XMLStreamWriter theEventWriter,
        boolean theContainedResource, IIdType theResourceId) throws XMLStreamException {
    if (!theContainedResource) {
        super.containResourcesForEncoding(theResource);
    }//from   w w  w  . j  av  a 2  s .  co m

    RuntimeResourceDefinition resDef = myContext.getResourceDefinition(theResource);
    if (resDef == null) {
        throw new ConfigurationException("Unknown resource type: " + theResource.getClass());
    }

    theEventWriter.writeStartElement(resDef.getName());
    theEventWriter.writeDefaultNamespace(FHIR_NS);

    if (theResource instanceof IAnyResource) {

        // HL7.org Structures
        if (theResourceId != null) {
            writeCommentsPre(theEventWriter, theResourceId);
            writeOptionalTagWithValue(theEventWriter, "id", theResourceId.getIdPart());
            writeCommentsPost(theEventWriter, theResourceId);
        }

        encodeCompositeElementToStreamWriter(theResource, theResource, theEventWriter, theContainedResource,
                new CompositeChildElement(resDef));

    } else {

        if (myContext.getVersion().getVersion().isNewerThan(FhirVersionEnum.DSTU1)) {

            // DSTU2+

            IResource resource = (IResource) theResource;
            if (theResourceId != null) {
                writeCommentsPre(theEventWriter, theResourceId);
                writeOptionalTagWithValue(theEventWriter, "id", theResourceId.getIdPart());
                writeCommentsPost(theEventWriter, theResourceId);
            }

            InstantDt updated = (InstantDt) resource.getResourceMetadata().get(ResourceMetadataKeyEnum.UPDATED);
            IdDt resourceId = resource.getId();
            String versionIdPart = resourceId.getVersionIdPart();
            if (isBlank(versionIdPart)) {
                versionIdPart = ResourceMetadataKeyEnum.VERSION.get(resource);
            }
            List<BaseCodingDt> securityLabels = extractMetadataListNotNull(resource,
                    ResourceMetadataKeyEnum.SECURITY_LABELS);
            List<? extends IIdType> profiles = extractMetadataListNotNull(resource,
                    ResourceMetadataKeyEnum.PROFILES);
            profiles = super.getProfileTagsForEncoding(resource, profiles);

            TagList tags = getMetaTagsForEncoding((resource));

            if (super.shouldEncodeResourceMeta(resource)
                    && ElementUtil.isEmpty(versionIdPart, updated, securityLabels, tags, profiles) == false) {
                theEventWriter.writeStartElement("meta");
                writeOptionalTagWithValue(theEventWriter, "versionId", versionIdPart);
                if (updated != null) {
                    writeOptionalTagWithValue(theEventWriter, "lastUpdated", updated.getValueAsString());
                }

                for (IIdType profile : profiles) {
                    theEventWriter.writeStartElement("profile");
                    theEventWriter.writeAttribute("value", profile.getValue());
                    theEventWriter.writeEndElement();
                }
                for (BaseCodingDt securityLabel : securityLabels) {
                    theEventWriter.writeStartElement("security");
                    encodeCompositeElementToStreamWriter(resource, securityLabel, theEventWriter,
                            theContainedResource, null);
                    theEventWriter.writeEndElement();
                }
                if (tags != null) {
                    for (Tag tag : tags) {
                        if (tag.isEmpty()) {
                            continue;
                        }
                        theEventWriter.writeStartElement("tag");
                        writeOptionalTagWithValue(theEventWriter, "system", tag.getScheme());
                        writeOptionalTagWithValue(theEventWriter, "code", tag.getTerm());
                        writeOptionalTagWithValue(theEventWriter, "display", tag.getLabel());
                        theEventWriter.writeEndElement();
                    }
                }
                theEventWriter.writeEndElement();
            }

            if (theResource instanceof IBaseBinary) {
                IBaseBinary bin = (IBaseBinary) theResource;
                writeOptionalTagWithValue(theEventWriter, "contentType", bin.getContentType());
                writeOptionalTagWithValue(theEventWriter, "content", bin.getContentAsBase64());
            } else {
                encodeCompositeElementToStreamWriter(theResource, theResource, theEventWriter,
                        theContainedResource, new CompositeChildElement(resDef));
            }

        } else {

            // DSTU1
            if (theResourceId != null && theContainedResource && theResourceId.hasIdPart()) {
                theEventWriter.writeAttribute("id", theResourceId.getIdPart());
            }

            if (theResource instanceof IBaseBinary) {
                IBaseBinary bin = (IBaseBinary) theResource;
                if (bin.getContentType() != null) {
                    theEventWriter.writeAttribute("contentType", bin.getContentType());
                }
                theEventWriter.writeCharacters(bin.getContentAsBase64());
            } else {
                encodeCompositeElementToStreamWriter(theResource, theResource, theEventWriter,
                        theContainedResource, new CompositeChildElement(resDef));
            }

        }

    }

    theEventWriter.writeEndElement();
}

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

private void handleMultiBlobRemove(HttpServletResponse response, InputStream is, BlobStore blobStore,
        String containerName) throws IOException {
    DeleteMultipleObjectsRequest dmor = new XmlMapper().readValue(is, DeleteMultipleObjectsRequest.class);
    Collection<String> blobNames = new ArrayList<>();
    for (DeleteMultipleObjectsRequest.S3Object s3Object : dmor.objects) {
        blobNames.add(s3Object.key);
    }/*from w ww. j a  va 2s .c om*/

    blobStore.removeBlobs(containerName, blobNames);

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

        if (!dmor.quiet) {
            for (String blobName : blobNames) {
                xml.writeStartElement("Deleted");

                writeSimpleElement(xml, "Key", blobName);

                xml.writeEndElement();
            }
        }

        // TODO: emit error stanza
        xml.writeEndElement();
        xml.flush();
    } catch (XMLStreamException xse) {
        throw new IOException(xse);
    }
}

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

private void handleContainerList(HttpServletResponse response, BlobStore blobStore) throws IOException {
    PageSet<? extends StorageMetadata> buckets = blobStore.list();

    try (Writer writer = response.getWriter()) {
        XMLStreamWriter xml = xmlOutputFactory.createXMLStreamWriter(writer);
        xml.writeStartDocument();//from w w w  .j  av a2 s.c  om
        xml.writeStartElement("ListAllMyBucketsResult");
        xml.writeDefaultNamespace(AWS_XMLNS);

        writeOwnerStanza(xml);

        xml.writeStartElement("Buckets");
        for (StorageMetadata metadata : buckets) {
            xml.writeStartElement("Bucket");

            writeSimpleElement(xml, "Name", metadata.getName());

            Date creationDate = metadata.getCreationDate();
            if (creationDate == null) {
                // Some providers, e.g., Swift, do not provide container
                // creation date.  Emit a bogus one to satisfy clients like
                // s3cmd which require one.
                creationDate = new Date(0);
            }
            writeSimpleElement(xml, "CreationDate",
                    blobStore.getContext().utils().date().iso8601DateFormat(creationDate).trim());

            xml.writeEndElement();
        }
        xml.writeEndElement();

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

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

private void handleGetContainerAcl(HttpServletResponse response, BlobStore blobStore, String containerName)
        throws IOException {
    ContainerAccess access = blobStore.getContainerAccess(containerName);

    try (Writer writer = response.getWriter()) {
        XMLStreamWriter xml = xmlOutputFactory.createXMLStreamWriter(writer);
        xml.writeStartDocument();/*www.j a v  a  2 s  .  co  m*/
        xml.writeStartElement("AccessControlPolicy");
        xml.writeDefaultNamespace(AWS_XMLNS);

        writeOwnerStanza(xml);

        xml.writeStartElement("AccessControlList");

        xml.writeStartElement("Grant");

        xml.writeStartElement("Grantee");
        xml.writeNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        xml.writeAttribute("xsi:type", "CanonicalUser");

        writeSimpleElement(xml, "ID", FAKE_OWNER_ID);
        writeSimpleElement(xml, "DisplayName", FAKE_OWNER_DISPLAY_NAME);

        xml.writeEndElement();

        writeSimpleElement(xml, "Permission", "FULL_CONTROL");

        xml.writeEndElement();

        if (access == ContainerAccess.PUBLIC_READ) {
            xml.writeStartElement("Grant");

            xml.writeStartElement("Grantee");
            xml.writeNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
            xml.writeAttribute("xsi:type", "Group");

            writeSimpleElement(xml, "URI", "http://acs.amazonaws.com/groups/global/AllUsers");

            xml.writeEndElement();

            writeSimpleElement(xml, "Permission", "READ");

            xml.writeEndElement();
        }

        xml.writeEndElement();

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

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

private void handleGetBlobAcl(HttpServletResponse response, BlobStore blobStore, String containerName,
        String blobName) throws IOException {
    BlobAccess access = blobStore.getBlobAccess(containerName, blobName);

    try (Writer writer = response.getWriter()) {
        XMLStreamWriter xml = xmlOutputFactory.createXMLStreamWriter(writer);
        xml.writeStartDocument();/*  ww w .jav  a2  s  . c o m*/
        xml.writeStartElement("AccessControlPolicy");
        xml.writeDefaultNamespace(AWS_XMLNS);

        writeOwnerStanza(xml);

        xml.writeStartElement("AccessControlList");

        xml.writeStartElement("Grant");

        xml.writeStartElement("Grantee");
        xml.writeNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        xml.writeAttribute("xsi:type", "CanonicalUser");

        writeSimpleElement(xml, "ID", FAKE_OWNER_ID);
        writeSimpleElement(xml, "DisplayName", FAKE_OWNER_DISPLAY_NAME);

        xml.writeEndElement();

        writeSimpleElement(xml, "Permission", "FULL_CONTROL");

        xml.writeEndElement();

        if (access == BlobAccess.PUBLIC_READ) {
            xml.writeStartElement("Grant");

            xml.writeStartElement("Grantee");
            xml.writeNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
            xml.writeAttribute("xsi:type", "Group");

            writeSimpleElement(xml, "URI", "http://acs.amazonaws.com/groups/global/AllUsers");

            xml.writeEndElement();

            writeSimpleElement(xml, "Permission", "READ");

            xml.writeEndElement();
        }

        xml.writeEndElement();

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

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();
    }//  ww w .  ja v  a2 s.  co m

    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);
    }/* ww w .j  a va 2 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);
    }
}