List of usage examples for org.apache.http.entity ContentType APPLICATION_OCTET_STREAM
ContentType APPLICATION_OCTET_STREAM
To view the source code for org.apache.http.entity ContentType APPLICATION_OCTET_STREAM.
Click Source Link
From source file:com.joyent.manta.client.MantaClient.java
/** * Copies the supplied {@link File} to a remote Manta object at the specified path. * * @param rawPath The fully qualified path of the object. i.e. /user/stor/foo/bar/baz * @param file file to upload/*from w ww. j a v a2 s .co m*/ * @param headers optional HTTP headers to include when copying the object * @param metadata optional user-supplied metadata for object * @return Manta response object * @throws IOException when there is a problem sending the object over the network */ public MantaObjectResponse put(final String rawPath, final File file, final MantaHttpHeaders headers, final MantaMetadata metadata) throws IOException { Validate.notBlank(rawPath, "rawPath must not be blank"); Validate.notNull(file, "File must not be null"); final String path = formatPath(rawPath); if (!file.exists()) { String msg = String.format("File doesn't exist: %s", file.getPath()); throw new FileNotFoundException(msg); } if (!file.canRead()) { String msg = String.format("Can't access file for read: %s", file.getPath()); throw new IOException(msg); } final ContentType contentType = ContentTypeLookup.findOrDefaultContentType(headers, path, file, ContentType.APPLICATION_OCTET_STREAM); final HttpEntity entity = new FileEntity(file, contentType); return httpHelper.httpPut(path, headers, entity, metadata); }
From source file:com.joyent.manta.client.MantaClient.java
/** * Copies the supplied byte array to a remote Manta object at the specified path. * * @param rawPath The fully qualified path of the object. i.e. /user/stor/foo/bar/baz * @param bytes byte array to upload//from w w w. j a v a2 s .c o m * @param headers optional HTTP headers to include when copying the object * @param metadata optional user-supplied metadata for object * @return Manta response object * @throws IOException when there is a problem sending the object over the network */ public MantaObjectResponse put(final String rawPath, final byte[] bytes, final MantaHttpHeaders headers, final MantaMetadata metadata) throws IOException { Validate.notBlank(rawPath, "rawPath must not be blank"); Validate.notNull(bytes, "Byte array must not be null"); final String path = formatPath(rawPath); final ContentType contentType = ContentTypeLookup.findOrDefaultContentType(headers, path, ContentType.APPLICATION_OCTET_STREAM); final HttpEntity entity = new ExposedByteArrayEntity(bytes, contentType); return httpHelper.httpPut(path, headers, entity, metadata); }
From source file:org.exoplatform.outlook.OutlookServiceImpl.java
/** * Add nt:file node for given content stream and title. If a node with such name exists a new name will be * generated by adding a numerical index to the end. * // w ww.j a v a 2s .c o m * @param parent {@link Node} * @param title {@link String} * @param contentType {@link String} * @param content {@link InputStream} * @return {@link Node} * @throws RepositoryException when storage error */ protected Node addFile(Node parent, String title, String contentType, InputStream content) throws RepositoryException { Node file; String baseName = cleanName(title); String name = baseName; int siblingNumber = 0; do { try { file = parent.getNode(name); // such node already exists - find new name for the file (by adding sibling index to the end) siblingNumber++; int extIndex = baseName.lastIndexOf("."); if (extIndex > 0 && extIndex != baseName.length() - 1) { String jcrName = baseName.substring(0, extIndex); String jcrExt = baseName.substring(extIndex + 1); name = new StringBuilder(jcrName).append('-').append(siblingNumber).append('.').append(jcrExt) .toString(); } else { name = new StringBuilder(baseName).append('-').append(siblingNumber).toString(); } } catch (PathNotFoundException e) { // no such node exists, add it using internalName created by CD's cleanName() file = parent.addNode(name, "nt:file"); break; } } while (true); Node resource = file.addNode("jcr:content", "nt:resource"); resource.setProperty("jcr:mimeType", contentType != null ? contentType : ContentType.APPLICATION_OCTET_STREAM.getMimeType()); Calendar fileDate = Calendar.getInstance(); resource.setProperty("jcr:lastModified", fileDate); resource.setProperty("jcr:data", content); if (siblingNumber > 0) { int extIndex = title.lastIndexOf("."); if (extIndex > 0 && extIndex != title.length() - 1) { String titleName = title.substring(0, extIndex); String titleExt = title.substring(extIndex + 1); title = new StringBuilder(titleName).append(" (").append(siblingNumber).append(").") .append(titleExt).toString(); } else { title = new StringBuilder(title).append(" (").append(siblingNumber).append(')').toString(); } } if (!file.hasProperty(NodetypeConstant.EXO_TITLE)) { file.addMixin(NodetypeConstant.EXO_RSS_ENABLE); } file.setProperty(NodetypeConstant.EXO_TITLE, title); // file.setProperty("exo:summary", summary); try { file.setProperty(NodetypeConstant.EXO_NAME, title); } catch (ConstraintViolationException | ValueFormatException e) { LOG.warn("Cannot set exo:name property to '" + title + "' for file " + file.getPath() + ": " + e); } if (file.isNodeType(NodetypeConstant.EXO_DATETIME)) { file.setProperty(NodetypeConstant.EXO_DATE_CREATED, fileDate); file.setProperty(NodetypeConstant.EXO_DATE_MODIFIED, fileDate); } if (file.isNodeType(NodetypeConstant.EXO_MODIFY)) { file.setProperty(NodetypeConstant.EXO_LAST_MODIFIED_DATE, fileDate); file.setProperty(NodetypeConstant.EXO_LAST_MODIFIER, file.getSession().getUserID()); } // Added when upgraded to PLF 4.4 if (!file.isNodeType(NodetypeConstant.MIX_REFERENCEABLE)) { file.addMixin(NodetypeConstant.MIX_REFERENCEABLE); } if (!file.isNodeType(NodetypeConstant.MIX_COMMENTABLE)) { file.addMixin(NodetypeConstant.MIX_COMMENTABLE); } if (!file.isNodeType(NodetypeConstant.MIX_VOTABLE)) { file.addMixin(NodetypeConstant.MIX_VOTABLE); } if (!file.isNodeType(NodetypeConstant.MIX_I18N)) { file.addMixin(NodetypeConstant.MIX_I18N); } return file; }
From source file:org.dasein.cloud.openstack.nova.os.AbstractMethod.java
protected @Nullable String putStream(@Nonnull String authToken, @Nonnull String endpoint, @Nonnull String resource, @Nullable String md5Hash, @Nonnull InputStream stream) throws CloudException, InternalException { Logger std = NovaOpenStack.getLogger(NovaOpenStack.class, "std"); Logger wire = NovaOpenStack.getLogger(NovaOpenStack.class, "wire"); if (std.isTraceEnabled()) { std.trace("enter - " + AbstractMethod.class.getName() + ".putStream(" + authToken + "," + endpoint + "," + resource + "," + md5Hash + ",INPUTSTREAM)"); }/*from w ww .j av a 2 s . co m*/ if (wire.isDebugEnabled()) { wire.debug("---------------------------------------------------------------------------------" + endpoint + resource); wire.debug(""); } HttpClient client = null; try { client = getClient(); HttpPut put = new HttpPut(endpoint + resource); put.addHeader("Content-Type", "application/octet-stream"); put.addHeader("X-Auth-Token", authToken); if (md5Hash != null) { put.addHeader("ETag", md5Hash); } if (wire.isDebugEnabled()) { wire.debug(put.getRequestLine().toString()); for (Header header : put.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } put.setEntity(new InputStreamEntity(stream, -1, ContentType.APPLICATION_OCTET_STREAM)); wire.debug(" ---- BINARY DATA ---- "); wire.debug(""); HttpResponse response; try { APITrace.trace(provider, "PUT " + toAPIResource(resource)); response = client.execute(put); if (wire.isDebugEnabled()) { wire.debug(response.getStatusLine().toString()); for (Header header : response.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } } catch (IOException e) { std.error("I/O error from server communications: " + e.getMessage()); e.printStackTrace(); throw new InternalException(e); } int code = response.getStatusLine().getStatusCode(); std.debug("HTTP STATUS: " + code); String responseHash = null; for (Header h : put.getAllHeaders()) { if (h.getName().equalsIgnoreCase("ETag")) { responseHash = h.getValue(); } } if (responseHash != null && md5Hash != null && !responseHash.equals(md5Hash)) { throw new CloudException("MD5 hash values do not match, probably data corruption"); } if (code != HttpStatus.SC_CREATED && code != HttpStatus.SC_ACCEPTED && code != HttpStatus.SC_NO_CONTENT) { std.error("putStream(): Expected CREATED, ACCEPTED, or NO CONTENT for PUT request, got " + code); String data = null; try { HttpEntity entity = response.getEntity(); if (entity != null) { data = EntityUtils.toString(entity); if (wire.isDebugEnabled()) { wire.debug(data); wire.debug(""); } } } catch (IOException e) { std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); e.printStackTrace(); throw new CloudException(e); } NovaException.ExceptionItems items = NovaException.parseException(code, data); if (items == null) { items = new NovaException.ExceptionItems(); items.code = 404; items.type = CloudErrorType.COMMUNICATION; items.message = "itemNotFound"; items.details = "No such object: " + resource; } std.error("putStream(): [" + code + " : " + items.message + "] " + items.details); throw new NovaException(items); } else { if (code == HttpStatus.SC_ACCEPTED) { String data = null; try { HttpEntity entity = response.getEntity(); if (entity != null) { data = EntityUtils.toString(entity); if (wire.isDebugEnabled()) { wire.debug(data); wire.debug(""); } } } catch (IOException e) { std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); e.printStackTrace(); throw new CloudException(e); } if (data != null && !data.trim().equals("")) { return data; } } return null; } } finally { if (client != null) { client.getConnectionManager().shutdown(); } if (std.isTraceEnabled()) { std.trace("exit - " + NovaOpenStack.class.getName() + ".putStream()"); } if (wire.isDebugEnabled()) { wire.debug(""); wire.debug("---------------------------------------------------------------------------------" + endpoint + resource); } } }
From source file:com.infinities.skyport.openstack.nova.os.SkyportNovaMethod.java
@Override protected @Nullable String putStream(@Nonnull String authToken, @Nonnull String endpoint, @Nonnull String resource, @Nullable String md5Hash, @Nonnull InputStream stream) throws CloudException, InternalException { Logger std = NovaOpenStack.getLogger(NovaOpenStack.class, "std"); Logger wire = NovaOpenStack.getLogger(NovaOpenStack.class, "wire"); if (std.isTraceEnabled()) { std.trace("enter - " + AbstractMethod.class.getName() + ".putStream(" + authToken + "," + endpoint + "," + resource + "," + md5Hash + ",INPUTSTREAM)"); }/*from w w w .j a va 2 s. c om*/ if (wire.isDebugEnabled()) { wire.debug("---------------------------------------------------------------------------------" + endpoint + resource); wire.debug(""); } HttpClient client = null; try { client = getClient(); HttpPut put = new HttpPut(endpoint + resource); put.addHeader("Content-Type", "application/octet-stream"); put.addHeader("X-Auth-Token", authToken); if (md5Hash != null) { put.addHeader("ETag", md5Hash); } if (wire.isDebugEnabled()) { wire.debug(put.getRequestLine().toString()); for (Header header : put.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } put.setEntity(new InputStreamEntity(stream, -1, ContentType.APPLICATION_OCTET_STREAM)); wire.debug(" ---- BINARY DATA ---- "); wire.debug(""); HttpResponse response; try { APITrace.trace(provider, "PUT " + toAPIResource(resource)); response = client.execute(put); if (wire.isDebugEnabled()) { wire.debug(response.getStatusLine().toString()); for (Header header : response.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } } catch (IOException e) { std.error("I/O error from server communications: " + e.getMessage()); e.printStackTrace(); throw new InternalException(e); } int code = response.getStatusLine().getStatusCode(); std.debug("HTTP STATUS: " + code); String responseHash = null; for (Header h : put.getAllHeaders()) { if (h.getName().equalsIgnoreCase("ETag")) { responseHash = h.getValue(); } } if (responseHash != null && md5Hash != null && !responseHash.equals(md5Hash)) { throw new CloudException("MD5 hash values do not match, probably data corruption"); } if (code != HttpStatus.SC_CREATED && code != HttpStatus.SC_ACCEPTED && code != HttpStatus.SC_NO_CONTENT) { std.error("putStream(): Expected CREATED, ACCEPTED, or NO CONTENT for PUT request, got " + code); String data = null; try { HttpEntity entity = response.getEntity(); if (entity != null) { data = EntityUtils.toString(entity); if (wire.isDebugEnabled()) { wire.debug(data); wire.debug(""); } } } catch (IOException e) { std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); e.printStackTrace(); throw new CloudException(e); } NovaException.ExceptionItems items = NovaException.parseException(code, data); if (items == null) { items = new NovaException.ExceptionItems(); items.code = 404; items.type = CloudErrorType.COMMUNICATION; items.message = "itemNotFound"; items.details = "No such object: " + resource; } std.error("putStream(): [" + code + " : " + items.message + "] " + items.details); throw new NovaException(items); } else { if (code == HttpStatus.SC_ACCEPTED) { String data = null; try { HttpEntity entity = response.getEntity(); if (entity != null) { data = EntityUtils.toString(entity); if (wire.isDebugEnabled()) { wire.debug(data); wire.debug(""); } } } catch (IOException e) { std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); e.printStackTrace(); throw new CloudException(e); } if (data != null && !data.trim().equals("")) { return data; } } return null; } } finally { if (client != null) { client.getConnectionManager().shutdown(); } if (std.isTraceEnabled()) { std.trace("exit - " + NovaOpenStack.class.getName() + ".putStream()"); } if (wire.isDebugEnabled()) { wire.debug(""); wire.debug("---------------------------------------------------------------------------------" + endpoint + resource); } } }
From source file:net.ychron.unirestins.test.http.UnirestInstTest.java
@Test public void testMultipartInputStreamContentType() throws JSONException, InterruptedException, ExecutionException, URISyntaxException, UnirestException, FileNotFoundException { HttpResponse<JsonNode> jsonResponse = unirestInst.post("http://httpbin.org/post").field("name", "Mark") .field("file", new FileInputStream(new File(getClass().getResource("/image.jpg").toURI())), ContentType.APPLICATION_OCTET_STREAM, "image.jpg") .asJson();//from w w w . ja va 2 s . c o m assertTrue(jsonResponse.getHeaders().size() > 0); assertTrue(jsonResponse.getBody().toString().length() > 0); assertFalse(jsonResponse.getRawBody() == null); assertEquals(200, jsonResponse.getStatus()); JsonNode json = jsonResponse.getBody(); assertFalse(json.isArray()); assertNotNull(json.getObject()); assertNotNull(json.getArray()); assertEquals(1, json.getArray().length()); assertNotNull(json.getArray().get(0)); assertNotNull(json.getObject().getJSONObject("files")); assertTrue(json.getObject().getJSONObject("files").getString("file") .contains("data:application/octet-stream")); assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); }
From source file:net.ychron.unirestins.test.http.UnirestInstTest.java
@Test public void testMultipartInputStreamContentTypeAsync() throws JSONException, InterruptedException, ExecutionException, URISyntaxException, UnirestException, FileNotFoundException { unirestInst.post("http://httpbin.org/post").field("name", "Mark") .field("file", new FileInputStream(new File(getClass().getResource("/test").toURI())), ContentType.APPLICATION_OCTET_STREAM, "test") .asJsonAsync(new Callback<JsonNode>() { public void failed(UnirestException e) { fail();// www.j a v a 2 s.c om } public void completed(HttpResponse<JsonNode> response) { assertTrue(response.getHeaders().size() > 0); assertTrue(response.getBody().toString().length() > 0); assertFalse(response.getRawBody() == null); assertEquals(200, response.getStatus()); JsonNode json = response.getBody(); assertFalse(json.isArray()); assertNotNull(json.getObject()); assertNotNull(json.getArray()); assertEquals(1, json.getArray().length()); assertNotNull(json.getArray().get(0)); assertEquals("This is a test file", json.getObject().getJSONObject("files").getString("file")); assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); status = true; lock.countDown(); } public void cancelled() { fail(); } }); lock.await(10, TimeUnit.SECONDS); assertTrue(status); }
From source file:org.apache.sling.distribution.servlet.DistributionPackageExporterServlet.java
private void exportOnePackage(final SlingHttpServletRequest request, final SlingHttpServletResponse response, final boolean delete) throws ServletException, IOException { DistributionPackageExporter distributionPackageExporter = request.getResource() .adaptTo(DistributionPackageExporter.class); final long start = System.currentTimeMillis(); response.setContentType(ContentType.APPLICATION_OCTET_STREAM.toString()); DistributionRequest distributionRequest = RequestUtils.fromServletRequest(request); ResourceResolver resourceResolver = request.getResourceResolver(); final AtomicInteger fetched = new AtomicInteger(0); try {//from ww w . java2 s . c o m // get all items distributionPackageExporter.exportPackages(resourceResolver, distributionRequest, new DistributionPackageProcessor() { @Override public void process(DistributionPackage distributionPackage) { fetched.incrementAndGet(); InputStream inputStream = null; int bytesCopied = -1; try { inputStream = DistributionPackageUtils.createStreamWithHeader(distributionPackage); bytesCopied = IOUtils.copy(inputStream, response.getOutputStream()); } catch (IOException e) { log.error("cannot process package", e); } finally { IOUtils.closeQuietly(inputStream); } String packageId = distributionPackage.getId(); if (delete) { // delete the package permanently distributionPackage.delete(); } // everything ok response.setStatus(200); log.debug("exported package {} was sent (and deleted={}), bytes written {}", new Object[] { packageId, delete, bytesCopied }); } }); if (fetched.get() > 0) { long end = System.currentTimeMillis(); log.info("Processed distribution export request in {} ms: : fetched {}", new Object[] { end - start, fetched }); } else { response.setStatus(204); log.debug("nothing to fetch"); } } catch (Throwable e) { response.setStatus(503); log.error("error while exporting package", e); } }
From source file:org.apache.sling.distribution.transport.impl.SimpleHttpDistributionTransport.java
public void deliverPackage(@Nonnull ResourceResolver resourceResolver, @Nonnull DistributionPackage distributionPackage, @Nonnull DistributionTransportContext distributionContext) throws DistributionException { String hostAndPort = getHostAndPort(distributionEndpoint.getUri()); DistributionPackageInfo info = distributionPackage.getInfo(); URI packageOrigin = info.get(PACKAGE_INFO_PROPERTY_ORIGIN_URI, URI.class); if (packageOrigin != null && hostAndPort.equals(getHostAndPort(packageOrigin))) { log.debug("skipping distribution of package {}to same origin {}", distributionPackage.getId(), hostAndPort);/*from w w w . j av a2 s . co m*/ } else { try { Executor executor = getExecutor(distributionContext); Request req = Request.Post(distributionEndpoint.getUri()).useExpectContinue(); // add the message body digest, see https://tools.ietf.org/html/rfc3230#section-4.3.2 if (distributionPackage instanceof AbstractDistributionPackage) { AbstractDistributionPackage adb = (AbstractDistributionPackage) distributionPackage; if (adb.getDigestAlgorithm() != null && adb.getDigestMessage() != null) { req.addHeader(DIGEST_HEADER, String.format("%s=%s", adb.getDigestAlgorithm(), adb.getDigestMessage())); } } InputStream inputStream = null; try { inputStream = DistributionPackageUtils.createStreamWithHeader(distributionPackage); req = req.bodyStream(inputStream, ContentType.APPLICATION_OCTET_STREAM); Response response = executor.execute(req); response.returnContent(); // throws an error if HTTP status is >= 300 } finally { IOUtils.closeQuietly(inputStream); } log.debug("delivered packageId={}, endpoint={}", distributionPackage.getId(), distributionEndpoint.getUri()); } catch (HttpHostConnectException e) { throw new RecoverableDistributionException( "endpoint not available " + distributionEndpoint.getUri(), e); } catch (HttpResponseException e) { int statusCode = e.getStatusCode(); if (statusCode == 404 || statusCode == 401) { throw new RecoverableDistributionException( "not enough rights for " + distributionEndpoint.getUri(), e); } throw new DistributionException(e); } catch (Exception e) { throw new DistributionException(e); } } }
From source file:org.dasein.cloud.azure.AzureStorageMethod.java
public void putWithFile(@Nonnull String strMethod, @Nonnull String resource, Map<String, String> queries, File file, Map<String, String> headerMap, boolean authorization) throws CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace("enter - " + AzureStorageMethod.class.getName() + "." + strMethod + "(" + getStorageAccount() + "," + resource + ")"); }/*from w w w . j av a2 s .c om*/ String endpoint = getStorageEnpoint(); if (wire.isDebugEnabled()) { wire.debug(strMethod + "--------------------------------------------------------> " + endpoint + getStorageAccount() + resource); wire.debug(""); } long begin = System.currentTimeMillis(); try { HttpClient client = getClient(); String contentLength = null; if (file != null) { contentLength = String.valueOf(file.length()); } else { contentLength = "0"; } HttpRequestBase method = getMethod(strMethod, buildUrl(resource, queries), queries, headerMap, authorization); if (wire.isDebugEnabled()) { wire.debug(method.getRequestLine().toString()); for (Header header : method.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); if (file != null) { wire.debug(file); wire.debug(""); } } // If it is post or put if (method instanceof HttpEntityEnclosingRequestBase) { HttpEntityEnclosingRequestBase entityEnclosingMethod = (HttpEntityEnclosingRequestBase) method; if (file != null) { entityEnclosingMethod.setEntity(new FileEntity(file, ContentType.APPLICATION_OCTET_STREAM)); } } HttpResponse response; StatusLine status; try { response = client.execute(method); status = response.getStatusLine(); } catch (IOException e) { logger.error("post(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage()); if (logger.isTraceEnabled()) { e.printStackTrace(); } long end = System.currentTimeMillis(); logger.debug("Totoal time -> " + (end - begin)); throw new CloudException(e); } if (logger.isDebugEnabled()) { logger.debug("post(): HTTP Status " + status); } Header[] headers = response.getAllHeaders(); if (wire.isDebugEnabled()) { wire.debug(status.toString()); for (Header h : headers) { if (h.getValue() != null) { wire.debug(h.getName() + ": " + h.getValue().trim()); } else { wire.debug(h.getName() + ":"); } } wire.debug(""); } if ((status.getStatusCode() != HttpServletResponse.SC_CREATED && status.getStatusCode() != HttpServletResponse.SC_ACCEPTED && status.getStatusCode() != HttpServletResponse.SC_OK) && status.getStatusCode() != HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION) { logger.error( strMethod + "(): Expected OK for " + strMethod + "request, got " + status.getStatusCode()); HttpEntity entity = response.getEntity(); String result; if (entity == null) { throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), "An error was returned without explanation"); } try { result = EntityUtils.toString(entity); } catch (IOException e) { throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } if (wire.isDebugEnabled()) { wire.debug(result); } wire.debug(""); AzureException.ExceptionItems items = AzureException.parseException(status.getStatusCode(), result); logger.error(strMethod + "(): [" + status.getStatusCode() + " : " + items.message + "] " + items.details); throw new AzureException(items); } } finally { if (logger.isTraceEnabled()) { logger.trace("exit - " + AzureMethod.class.getName() + ".getStream()"); } if (wire.isDebugEnabled()) { wire.debug(""); wire.debug("--------------------------------------------------------> "); } } }