List of usage examples for javax.xml.stream XMLStreamWriter flush
public void flush() throws XMLStreamException;
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 w ww.jav a 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); } }
From source file:jp.zippyzip.impl.GeneratorServiceImpl.java
public void storeX0401Zip() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); long timestamp = getLzhDao().getZipInfo().getTimestamp().getTime(); ZipOutputStream out = new ZipOutputStream(baos); Collection<Pref> prefs = getPrefs(); ZipEntry tsv = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0401_utf8.txt"); ZipEntry csv = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0401_sjis.csv"); ZipEntry json = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0401_utf8.json"); ZipEntry xml = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0401_utf8.xml"); tsv.setTime(timestamp);/* w w w. j a v a 2s . c o m*/ csv.setTime(timestamp); json.setTime(timestamp); xml.setTime(timestamp); try { out.putNextEntry(tsv); for (Pref pref : prefs) { out.write(new String(pref.getCode() + "\t" + pref.getName() + "\t" + pref.getYomi() + CRLF) .getBytes("UTF-8")); } out.closeEntry(); out.putNextEntry(csv); for (Pref pref : prefs) { out.write(new String(pref.getCode() + "," + pref.getName() + "," + pref.getYomi() + CRLF) .getBytes("MS932")); } out.closeEntry(); out.putNextEntry(json); OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8"); JSONWriter jwriter = new JSONWriter(writer); jwriter.array(); for (Pref pref : prefs) { jwriter.object().key("code").value(pref.getCode()).key("name").value(pref.getName()).key("yomi") .value(pref.getYomi()).endObject(); } jwriter.endArray(); writer.flush(); out.closeEntry(); out.putNextEntry(xml); XMLStreamWriter xwriter = XMLOutputFactory.newInstance() .createXMLStreamWriter(new OutputStreamWriter(out, "UTF-8")); xwriter.writeStartDocument("UTF-8", "1.0"); xwriter.writeStartElement("x0401s"); for (Pref pref : prefs) { xwriter.writeStartElement("x0401"); xwriter.writeAttribute("code", pref.getCode()); xwriter.writeAttribute("name", pref.getName()); xwriter.writeAttribute("yomi", pref.getYomi()); xwriter.writeEndElement(); } xwriter.writeEndElement(); xwriter.writeEndDocument(); xwriter.flush(); out.closeEntry(); out.finish(); baos.flush(); getRawDao().store(baos.toByteArray(), "x0401.zip"); log.info("prefs: " + prefs.size()); } catch (JSONException e) { log.log(Level.WARNING, "", e); } catch (XMLStreamException e) { log.log(Level.WARNING, "", e); } catch (FactoryConfigurationError e) { log.log(Level.WARNING, "", e); } catch (IOException e) { log.log(Level.WARNING, "", e); } }
From source file:org.gaul.s3proxy.S3ProxyHandler.java
protected final void sendSimpleErrorResponse(HttpServletRequest request, HttpServletResponse response, S3ErrorCode code, String message, Map<String, String> elements) throws IOException { logger.debug("{} {}", code, elements); response.setStatus(code.getHttpStatusCode()); if (request.getMethod().equals("HEAD")) { // The HEAD method is identical to GET except that the server MUST // NOT return a message-body in the response. return;/*from w w w . ja v a 2 s . c om*/ } try (Writer writer = response.getWriter()) { XMLStreamWriter xml = xmlOutputFactory.createXMLStreamWriter(writer); xml.writeStartDocument(); xml.writeStartElement("Error"); writeSimpleElement(xml, "Code", code.getErrorCode()); writeSimpleElement(xml, "Message", message); for (Map.Entry<String, String> entry : elements.entrySet()) { writeSimpleElement(xml, entry.getKey(), entry.getValue()); } writeSimpleElement(xml, "RequestId", FAKE_REQUEST_ID); xml.writeEndElement(); xml.flush(); } catch (XMLStreamException xse) { throw new IOException(xse); } }
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 av a 2 s. c o m 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:jp.zippyzip.impl.GeneratorServiceImpl.java
public void storeX0402Zip() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); long timestamp = getLzhDao().getZipInfo().getTimestamp().getTime(); ZipOutputStream out = new ZipOutputStream(baos); Collection<City> cities = getCities(); ZipEntry tsv = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0402_utf8.txt"); ZipEntry csv = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0402_sjis.csv"); ZipEntry json = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0402_utf8.json"); ZipEntry xml = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_x0402_utf8.xml"); tsv.setTime(timestamp);/*from w ww . j av a 2 s.c om*/ csv.setTime(timestamp); json.setTime(timestamp); xml.setTime(timestamp); try { out.putNextEntry(tsv); for (City city : cities) { out.write(new String(city.getCode() + "\t" + city.getName() + "\t" + city.getYomi() + "\t" + ((city.getExpiration().getTime() < new Date().getTime()) ? "" : "") + CRLF) .getBytes("UTF-8")); } out.closeEntry(); out.putNextEntry(csv); for (City city : cities) { out.write(new String(city.getCode() + "," + city.getName() + "," + city.getYomi() + "," + ((city.getExpiration().getTime() < new Date().getTime()) ? "" : "") + CRLF) .getBytes("MS932")); } out.closeEntry(); out.putNextEntry(json); OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8"); JSONWriter jwriter = new JSONWriter(writer); jwriter.array(); for (City city : cities) { jwriter.object().key("code").value(city.getCode()).key("name").value(city.getName()).key("yomi") .value(city.getYomi()).key("expired") .value((city.getExpiration().getTime() < new Date().getTime()) ? "true" : "false") .endObject(); } jwriter.endArray(); writer.flush(); out.closeEntry(); out.putNextEntry(xml); XMLStreamWriter xwriter = XMLOutputFactory.newInstance() .createXMLStreamWriter(new OutputStreamWriter(out, "UTF-8")); xwriter.writeStartDocument("UTF-8", "1.0"); xwriter.writeStartElement("x0402s"); for (City city : cities) { xwriter.writeStartElement("x0402"); xwriter.writeAttribute("code", city.getCode()); xwriter.writeAttribute("name", city.getName()); xwriter.writeAttribute("yomi", city.getYomi()); xwriter.writeAttribute("expired", (city.getExpiration().getTime() < new Date().getTime()) ? "true" : "false"); xwriter.writeEndElement(); } xwriter.writeEndElement(); xwriter.writeEndDocument(); xwriter.flush(); out.closeEntry(); out.finish(); baos.flush(); getRawDao().store(baos.toByteArray(), "x0402.zip"); log.info("cities: " + cities.size()); } catch (JSONException e) { log.log(Level.WARNING, "", e); } catch (XMLStreamException e) { log.log(Level.WARNING, "", e); } catch (FactoryConfigurationError e) { log.log(Level.WARNING, "", e); } catch (IOException e) { log.log(Level.WARNING, "", e); } }
From source file:com.norconex.collector.http.client.impl.GenericHttpClientFactory.java
@Override public void saveToXML(Writer out) throws IOException { XMLOutputFactory factory = XMLOutputFactory.newInstance(); try {//from w ww. ja va2s. c o m XMLStreamWriter writer = factory.createXMLStreamWriter(out); writer.writeStartElement("httpClientFactory"); writer.writeAttribute("class", getClass().getCanonicalName()); writeBoolElement(writer, "cookiesDisabled", cookiesDisabled); writeStringElement(writer, "authMethod", authMethod); writeStringElement(writer, "authUsername", authUsername); writeStringElement(writer, "authPassword", authPassword); writeStringElement(writer, "authUsernameField", authUsernameField); writeStringElement(writer, "authPasswordField", authPasswordField); writeStringElement(writer, "authURL", authURL); writeStringElement(writer, "authHostname", authHostname); writeIntElement(writer, "authPort", authPort); writeStringElement(writer, "authFormCharset", authFormCharset); writeStringElement(writer, "authWorkstation", authWorkstation); writeStringElement(writer, "authDomain", authDomain); writeStringElement(writer, "authRealm", authRealm); writeStringElement(writer, "proxyHost", proxyHost); writeIntElement(writer, "proxyPort", proxyPort); writeStringElement(writer, "proxyScheme", proxyScheme); writeStringElement(writer, "proxyUsername", proxyUsername); writeStringElement(writer, "proxyPassword", proxyPassword); writeStringElement(writer, "proxyRealm", proxyRealm); writer.writeEndElement(); writeIntElement(writer, "connectionTimeout", connectionTimeout); writeIntElement(writer, "socketTimeout", socketTimeout); writeIntElement(writer, "connectionRequestTimeout", connectionRequestTimeout); writeStringElement(writer, "connectionCharset", connectionCharset); writeBoolElement(writer, "expectContinueEnabled", expectContinueEnabled); writeIntElement(writer, "maxRedirects", maxRedirects); writeStringElement(writer, "localAddress", localAddress); writeBoolElement(writer, "staleConnectionCheckDisabled", staleConnectionCheckDisabled); writeIntElement(writer, "maxConnections", maxConnections); writer.flush(); writer.close(); } catch (XMLStreamException e) { throw new IOException("Cannot save as XML.", e); } }
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();// www . j av a2s . 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:jp.zippyzip.impl.GeneratorServiceImpl.java
/** * XML ??/*from w w w . j a va 2s . c o m*/ * * @param name "area" / "corp" * @param suffix "" / "c" */ void storeXml(String name, String suffix) { long timestamp = getLzhDao().getZipInfo().getTimestamp().getTime(); Collection<City> cities = getCities(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(baos); ZipEntry entry = new ZipEntry(FILENAME_DATE_FORMAT.format(new Date(timestamp)) + "_" + name + "_utf8.xml"); entry.setTime(timestamp); int cnt = 0; try { zos.putNextEntry(entry); OutputStreamWriter writer = new OutputStreamWriter(zos, "UTF-8"); XMLStreamWriter xwriter = XMLOutputFactory.newInstance().createXMLStreamWriter(writer); xwriter.writeStartDocument("UTF-8", "1.0"); xwriter.writeStartElement("zips"); xwriter.writeAttribute("type", name); for (City city : cities) { ParentChild pc = getParentChildDao().get(city.getCode() + suffix); if (pc == null) { continue; } for (String json : pc.getChildren()) { Zip zip = Zip.fromJson(json); xwriter.writeStartElement("zip"); xwriter.writeAttribute("zip", zip.getCode()); xwriter.writeAttribute("x0402", zip.getX0402()); xwriter.writeAttribute("add1", zip.getAdd1()); xwriter.writeAttribute("add2", zip.getAdd2()); xwriter.writeAttribute("corp", zip.getCorp()); xwriter.writeAttribute("add1Yomi", zip.getAdd1Yomi()); xwriter.writeAttribute("add2Yomi", zip.getAdd2Yomi()); xwriter.writeAttribute("corpYomi", zip.getCorpYomi()); xwriter.writeAttribute("note", zip.getNote()); xwriter.writeEndElement(); ++cnt; } } xwriter.writeEndElement(); xwriter.writeEndDocument(); xwriter.flush(); zos.closeEntry(); zos.finish(); getRawDao().store(baos.toByteArray(), name + "_utf8_xml.zip"); log.info("count: " + cnt); } catch (XMLStreamException e) { log.log(Level.WARNING, "", e); } catch (FactoryConfigurationError e) { log.log(Level.WARNING, "", e); } catch (IOException e) { log.log(Level.WARNING, "", e); } }
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(); }/*w w w. ja va 2 s. c o 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 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();//from w w w . j a v a 2 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); } }