List of usage examples for org.apache.http.entity InputStreamEntity InputStreamEntity
public InputStreamEntity(InputStream inputStream, ContentType contentType)
From source file:com.emc.esu.api.rest.EsuRestApiApache.java
private HttpResponse restPut(URL url, Map<String, String> headers, InputStream in, long contentLength) throws URISyntaxException, ClientProtocolException, IOException { HttpPut put = new HttpPut(url.toURI()); setHeaders(put, headers);/*from w w w . j a va 2 s . co m*/ if (in != null) { put.setEntity(new InputStreamEntity(in, contentLength)); } else { put.setEntity(new ByteArrayEntity(new byte[0])); } return httpClient.execute(put); }
From source file:com.rackspacecloud.client.cloudfiles.FilesClient.java
/** * //from w ww .jav a2 s . c o m * * @param container * * @param data * * @param contentType * MIME * @param name * * @param metadata * * @param callback * NULL * * @throws IOException * IO * @throws HttpException * Http * @throws FilesExcepiton * * */ public String storeStreamedObject(String container, InputStream data, String contentType, String name, Map<String, String> metadata) throws IOException, HttpException, FilesException { if (this.isLoggedin()) { String objName = name; if (isValidContainerName(container) && isValidObjectName(objName)) { HttpPut method = new HttpPut( storageURL + "/" + sanitizeForURI(container) + "/" + sanitizeForURI(objName)); method.getParams().setIntParameter("http.socket.timeout", connectionTimeOut); method.setHeader(FilesConstants.X_AUTH_TOKEN, authToken); InputStreamEntity entity = new InputStreamEntity(data, -1); entity.setChunked(true); entity.setContentType(contentType); method.setEntity(entity); for (String key : metadata.keySet()) { // logger.warn("Key:" + key + ":" + // sanitizeForURI(metadata.get(key))); method.setHeader(FilesConstants.X_OBJECT_META + key, sanitizeForURI(metadata.get(key))); } method.removeHeaders("Content-Length"); try { FilesResponse response = new FilesResponse(client.execute(method)); if (response.getStatusCode() == HttpStatus.SC_CREATED) { return response.getResponseHeader(FilesConstants.E_TAG).getValue(); } else { logger.error(response.getStatusLine()); throw new FilesException("Unexpected result", response.getResponseHeaders(), response.getStatusLine()); } } finally { method.abort(); } } else { if (!isValidObjectName(objName)) { throw new FilesInvalidNameException(objName); } else { throw new FilesInvalidNameException(container); } } } else { throw new FilesAuthorizationException("You must be logged in", null, null); } }
From source file:API.amazon.mws.feeds.service.MarketplaceWebServiceClient.java
@SuppressWarnings("serial") private <T, U> T invoke(Class<T> clazz, Map<String, String> parameters, U request) throws MarketplaceWebServiceException { String actionName = parameters.get("Action"); T response = null;/*from ww w . j a v a2 s . com*/ String responseBodyString = null; ResponseHeaderMetadata responseHeaderMetadata = null; Method responseHeaderMetadataSetter = null; HttpPost method = null; try { responseHeaderMetadataSetter = clazz.getMethod("setResponseHeaderMetadata", ResponseHeaderMetadata.class); if (!config.isSetServiceURL()) { throw new MarketplaceWebServiceException( "Missing serviceUrl configuration value. You may obtain a list of valid MWS URLs by consulting the MWS Developer's Guide, or reviewing the sample code published along side this library.", -1, "InvalidServiceUrl", "Sender", null, null, null) { }; } // SubmitFeed will be the only MWS API function that will stream requests to the server. if (request instanceof SubmitFeedRequest) { // For SubmitFeed, HTTP body is reserved for the Feed Content and the function parameters // are contained within the HTTP header SubmitFeedRequest sfr = (SubmitFeedRequest) request; method = new HttpPost(config.getServiceURL() + "?" + getSubmitFeedUrlParameters(parameters)); method.setEntity(new InputStreamEntity(sfr.getFeedContent(), -1)); String contentMD5 = sfr.getContentMD5(); if (contentMD5 != null) { method.addHeader(new BasicHeader("Content-MD5", contentMD5)); } /* Set content type and encoding - encoding and charset are ignored right now because * octet-stream is the only supported transport of MWS feeds. */ method.addHeader(new BasicHeader("Content-Type", sfr.getContentType().toString())); } else { method = new HttpPost(config.getServiceURL()); log.debug("Adding required parameters..."); addRequiredParametersToRequest(method, parameters); /* Set content type and encoding */ log.debug("Setting content-type to application/x-www-form-urlencoded; charset=" + DEFAULT_ENCODING.toLowerCase()); method.addHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=" + DEFAULT_ENCODING.toLowerCase())); log.debug("Done adding additional required parameters. Parameters now: " + parameters); } for (Header head : defaultHeaders) { method.addHeader(head); } } catch (Throwable t) { throw new MarketplaceWebServiceException(t); } int status = -1; log.debug("Invoking" + actionName + " request. Current parameters: " + parameters); try { boolean shouldRetry = true; int retries = 0; do { log.debug("Sending Request to host: " + config.getServiceURL()); try { /* Submit request */ HttpResponse postResponse; postResponse = httpClient.execute(method, httpContext); status = postResponse.getStatusLine().getStatusCode(); responseHeaderMetadata = getResponseHeaderMetadata(postResponse); // GetFeedSubmissionResult and GetReport will be the only MWS API functions that will stream // server responses. boolean isStreamingResponse = (request instanceof GetFeedSubmissionResultRequest || request instanceof GetReportRequest); if (!isStreamingResponse) { // SubmitFeed responseBodyString = getResponsBodyAsString(postResponse.getEntity().getContent()); assert (responseBodyString != null); } /* Successful response. Attempting to unmarshal into the <Action>Response type */ if (status == HttpStatus.SC_OK && responseBodyString != null) { shouldRetry = false; log.debug("Received Response. Status: " + status + ". " + "Response Body: " + responseBodyString); log.debug("Attempting to unmarshal into the " + actionName + "Response type..."); response = clazz.cast(getUnmarshaller() .unmarshal(new StreamSource(new StringReader(responseBodyString)))); responseHeaderMetadataSetter.invoke(response, responseHeaderMetadata); log.debug("Unmarshalled response into " + actionName + "Response type."); } else if (status == HttpStatus.SC_OK && isStreamingResponse) { Method outputStreamGetter = null; for (Method m : request.getClass().getMethods()) { if (m.getName().matches("get.+OutputStream$")) { outputStreamGetter = m; } } OutputStream originalOs = (OutputStream) outputStreamGetter.invoke(request, new Object[0]); MessageDigest messageDigest = MessageDigest.getInstance("MD5"); DigestOutputStream os = new DigestOutputStream(originalOs, messageDigest); // Streaming-response-as-unnamed-body responses from MWS // must carry the generated unique request id as a HTTP // header (x-amz-request-id) as it cannot be passed in a // wrapper to the XML response. String requestIdFromHeader = null; { requestIdFromHeader = getFirstHeader(postResponse, "x-amz-request-id").getValue(); // Avoid use of the JDK-1.6-only isEmpty() call. if (requestIdFromHeader == null || requestIdFromHeader.length() == 0) { throw new MarketplaceWebServiceException( "no request id returned in the x-amz-request-id HTTP header " + "for a streaming response call - please contact Amazon"); } } String returnedContentMD5 = null; returnedContentMD5 = getFirstHeader(postResponse, "Content-MD5").getValue(); copyResponseToOutputStream(postResponse.getEntity().getContent(), os); // Streaming-response-as-unnamed-body responses from MWS // must also carry a Content-MD5 header and it must // match the calculated MD5 for the body. String calculatedContentMD5 = new String(Base64.encodeBase64(messageDigest.digest()), "UTF-8"); if (!calculatedContentMD5.equals(returnedContentMD5)) { throw new MarketplaceWebServiceException( "Content-MD5 HTTP header transmitted by MWS (" + returnedContentMD5 + ") " + "does not match the calculated MD5 (" + calculatedContentMD5 + ") " + "in request id " + requestIdFromHeader + " - please contact Amazon"); } response = clazz.newInstance(); responseHeaderMetadataSetter.invoke(response, responseHeaderMetadata); if (clazz == GetFeedSubmissionResultResponse.class) { GetFeedSubmissionResultResponse r = (GetFeedSubmissionResultResponse) response; r.setGetFeedSubmissionResultResult( new GetFeedSubmissionResultResult(returnedContentMD5)); r.setResponseMetadata(new ResponseMetadata(requestIdFromHeader)); } else if (clazz == GetReportResponse.class) { GetReportResponse r = (GetReportResponse) response; r.setGetReportResult(new GetReportResult(returnedContentMD5)); r.setResponseMetadata(new ResponseMetadata(requestIdFromHeader)); } else { throw new MarketplaceWebServiceException("unexpected streaming-response class " + clazz.getName() + " - please contact Amazon"); } shouldRetry = false; log.debug("Received streaming response."); } else { /* Unsucessful response. Attempting to unmarshall into ErrorResponse type */ if (isStreamingResponse) { // Response body contains error message. responseBodyString = getResponsBodyAsString(postResponse.getEntity().getContent()); } log.debug("Received Response. Status: " + status + "."); if (status == HttpStatus.SC_INTERNAL_SERVER_ERROR && !(request instanceof SubmitFeedRequest) && pauseIfRetryNeeded(++retries)) { shouldRetry = true; } else { log.debug("Attempting to unmarshal into the ErrorResponse type..."); ErrorResponse errorResponse = (ErrorResponse) getUnmarshaller() .unmarshal(new StreamSource(new StringReader(responseBodyString))); log.debug("Unmarshalled response into the ErrorResponse type."); API.amazon.mws.feeds.model.Error error = errorResponse.getError().get(0); if (status == HttpStatus.SC_SERVICE_UNAVAILABLE && !(error.getCode().equals("RequestThrottled")) && !(request instanceof SubmitFeedRequest) && pauseIfRetryNeeded(++retries)) { shouldRetry = true; } else { shouldRetry = false; throw new MarketplaceWebServiceException((((request instanceof SubmitFeedRequest) && (error.getType().equals("Receiver"))) ? error.getMessage() + " [Cannot retry SubmitFeed request: must reset InputStream to retry.]" : error.getMessage()), status, error.getCode(), error.getType(), errorResponse.getRequestId(), errorResponse.toXML(), responseHeaderMetadata); } } } } catch (JAXBException je) { /* Response cannot be unmarshalled neither as <Action>Response or ErrorResponse types. Checking for other possible errors. */ log.debug("Caught JAXBException", je); log.debug("Response cannot be unmarshalled neither as " + actionName + "Response or ErrorResponse types." + "Checking for other possible errors."); MarketplaceWebServiceException awse = processErrors(responseBodyString, status, responseHeaderMetadata); throw awse; } catch (IOException ioe) { log.error("Caught IOException exception", ioe); throw new MarketplaceWebServiceException("Internal Error", ioe); } catch (Exception e) { log.error("Caught Exception", e); throw new MarketplaceWebServiceException(e); } finally { method.releaseConnection(); } } while (shouldRetry); } catch (MarketplaceWebServiceException se) { log.error("Caught MarketplaceWebServiceException", se); throw se; } catch (Throwable t) { log.error("Caught Exception", t); throw new MarketplaceWebServiceException(t); } return response; }
From source file:com.amazonaws.mws.MarketplaceWebServiceClient.java
@SuppressWarnings("serial") private <T, U> T invoke(Class<T> clazz, Map<String, String> parameters, U request) throws MarketplaceWebServiceException { String actionName = parameters.get("Action"); T response = null;/*from w w w . ja v a 2 s . co m*/ String responseBodyString = null; ResponseHeaderMetadata responseHeaderMetadata = null; Method responseHeaderMetadataSetter = null; HttpPost method = null; try { responseHeaderMetadataSetter = clazz.getMethod("setResponseHeaderMetadata", ResponseHeaderMetadata.class); if (!config.isSetServiceURL()) { throw new MarketplaceWebServiceException( "Missing serviceUrl configuration value. You may obtain a list of valid MWS URLs by consulting the MWS Developer's Guide, or reviewing the sample code published along side this library.", -1, "InvalidServiceUrl", "Sender", null, null, null) { }; } // SubmitFeed will be the only MWS API function that will stream requests to the server. if (request instanceof SubmitFeedRequest) { // For SubmitFeed, HTTP body is reserved for the Feed Content and the function parameters // are contained within the HTTP header SubmitFeedRequest sfr = (SubmitFeedRequest) request; method = new HttpPost(config.getServiceURL() + "?" + getSubmitFeedUrlParameters(parameters)); method.setEntity(new InputStreamEntity(sfr.getFeedContent(), -1)); /* Set content type and encoding - encoding and charset are ignored right now because * octet-stream is the only supported transport of MWS feeds. */ method.addHeader(new BasicHeader("Content-Type", sfr.getContentType().toString())); } else { method = new HttpPost(config.getServiceURL()); log.debug("Adding required parameters..."); addRequiredParametersToRequest(method, parameters); /* Set content type and encoding */ log.debug("Setting content-type to application/x-www-form-urlencoded; charset=" + DEFAULT_ENCODING.toLowerCase()); method.addHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=" + DEFAULT_ENCODING.toLowerCase())); log.debug("Done adding additional required parameters. Parameters now: " + parameters); } for (Header head : defaultHeaders) { method.addHeader(head); } } catch (Throwable t) { throw new MarketplaceWebServiceException(t); } int status = -1; log.debug("Invoking" + actionName + " request. Current parameters: " + parameters); try { boolean shouldRetry = true; int retries = 0; do { log.debug("Sending Request to host: " + config.getServiceURL()); try { /* Submit request */ HttpResponse postResponse; postResponse = httpClient.execute(method, httpContext); status = postResponse.getStatusLine().getStatusCode(); responseHeaderMetadata = getResponseHeaderMetadata(postResponse); // GetFeedSubmissionResult and GetReport will be the only MWS API functions that will stream // server responses. boolean isStreamingResponse = (request instanceof GetFeedSubmissionResultRequest || request instanceof GetReportRequest); if (!isStreamingResponse) { // SubmitFeed responseBodyString = getResponsBodyAsString(postResponse.getEntity().getContent()); assert (responseBodyString != null); } /* Successful response. Attempting to unmarshal into the <Action>Response type */ if (status == HttpStatus.SC_OK && responseBodyString != null) { shouldRetry = false; log.debug("Received Response. Status: " + status + ". " + "Response Body: " + responseBodyString); log.debug("Attempting to unmarshal into the " + actionName + "Response type..."); response = clazz.cast(getUnmarshaller() .unmarshal(new StreamSource(new StringReader(responseBodyString)))); responseHeaderMetadataSetter.invoke(response, responseHeaderMetadata); log.debug("Unmarshalled response into " + actionName + "Response type."); } else if (status == HttpStatus.SC_OK && isStreamingResponse) { Method outputStreamGetter = null; for (Method m : request.getClass().getMethods()) { if (m.getName().matches("get.+OutputStream$")) { outputStreamGetter = m; } } OutputStream originalOs = (OutputStream) outputStreamGetter.invoke(request, new Object[0]); MessageDigest messageDigest = MessageDigest.getInstance("MD5"); DigestOutputStream os = new DigestOutputStream(originalOs, messageDigest); // Streaming-response-as-unnamed-body responses from MWS // must carry the generated unique request id as a HTTP // header (x-amz-request-id) as it cannot be passed in a // wrapper to the XML response. String requestIdFromHeader = null; { requestIdFromHeader = getFirstHeader(postResponse, "x-amz-request-id").getValue(); // Avoid use of the JDK-1.6-only isEmpty() call. if (requestIdFromHeader == null || requestIdFromHeader.length() == 0) { throw new MarketplaceWebServiceException( "no request id returned in the x-amz-request-id HTTP header " + "for a streaming response call - please contact Amazon"); } } String returnedContentMD5 = null; returnedContentMD5 = getFirstHeader(postResponse, "Content-MD5").getValue(); copyResponseToOutputStream(postResponse.getEntity().getContent(), os); // Streaming-response-as-unnamed-body responses from MWS // must also carry a Content-MD5 header and it must // match the calculated MD5 for the body. String calculatedContentMD5 = new String(Base64.encodeBase64(messageDigest.digest()), "UTF-8"); if (!calculatedContentMD5.equals(returnedContentMD5)) { throw new MarketplaceWebServiceException( "Content-MD5 HTTP header transmitted by MWS (" + returnedContentMD5 + ") " + "does not match the calculated MD5 (" + calculatedContentMD5 + ") " + "in request id " + requestIdFromHeader + " - please contact Amazon"); } response = clazz.newInstance(); responseHeaderMetadataSetter.invoke(response, responseHeaderMetadata); if (clazz == GetFeedSubmissionResultResponse.class) { GetFeedSubmissionResultResponse r = (GetFeedSubmissionResultResponse) response; r.setGetFeedSubmissionResultResult( new GetFeedSubmissionResultResult(returnedContentMD5)); r.setResponseMetadata(new ResponseMetadata(requestIdFromHeader)); } else if (clazz == GetReportResponse.class) { GetReportResponse r = (GetReportResponse) response; r.setGetReportResult(new GetReportResult(returnedContentMD5)); r.setResponseMetadata(new ResponseMetadata(requestIdFromHeader)); } else { throw new MarketplaceWebServiceException("unexpected streaming-response class " + clazz.getName() + " - please contact Amazon"); } shouldRetry = false; log.debug("Received streaming response."); } else { /* Unsucessful response. Attempting to unmarshall into ErrorResponse type */ if (isStreamingResponse) { // Response body contains error message. responseBodyString = getResponsBodyAsString(postResponse.getEntity().getContent()); } log.debug("Received Response. Status: " + status + "."); if (status == HttpStatus.SC_INTERNAL_SERVER_ERROR && !(request instanceof SubmitFeedRequest) && pauseIfRetryNeeded(++retries)) { shouldRetry = true; } else { log.debug("Attempting to unmarshal into the ErrorResponse type..."); ErrorResponse errorResponse = (ErrorResponse) getUnmarshaller() .unmarshal(new StreamSource(new StringReader(responseBodyString))); log.debug("Unmarshalled response into the ErrorResponse type."); com.amazonaws.mws.model.Error error = errorResponse.getError().get(0); if (status == HttpStatus.SC_SERVICE_UNAVAILABLE && !(error.getCode().equals("RequestThrottled")) && !(request instanceof SubmitFeedRequest) && pauseIfRetryNeeded(++retries)) { shouldRetry = true; } else { shouldRetry = false; throw new MarketplaceWebServiceException((((request instanceof SubmitFeedRequest) && (error.getType().equals("Receiver"))) ? error.getMessage() + " [Cannot retry SubmitFeed request: must reset InputStream to retry.]" : error.getMessage()), status, error.getCode(), error.getType(), errorResponse.getRequestId(), errorResponse.toXML(), responseHeaderMetadata); } } } } catch (JAXBException je) { /* Response cannot be unmarshalled neither as <Action>Response or ErrorResponse types. Checking for other possible errors. */ log.debug("Caught JAXBException", je); log.debug("Response cannot be unmarshalled neither as " + actionName + "Response or ErrorResponse types." + "Checking for other possible errors."); MarketplaceWebServiceException awse = processErrors(responseBodyString, status, responseHeaderMetadata); throw awse; } catch (IOException ioe) { log.error("Caught IOException exception", ioe); if (config.isSetProxyHost() && config.isSetProxyPort() && ioe instanceof javax.net.ssl.SSLPeerUnverifiedException) { String error = "\n*****\n* Perhaps you are attempting to use https protocol to communicate with the proxy that does not support it.\n* If so either enable https on the proxy, or configure the client to use http communications with the proxy.\n* See MarketplaceWebServiceClientConfig.setProxyProtocol for details.\n*****"; log.error(error); } throw new MarketplaceWebServiceException("Internal Error", ioe); } catch (Exception e) { log.error("Caught Exception", e); throw new MarketplaceWebServiceException(e); } finally { method.releaseConnection(); } } while (shouldRetry); } catch (MarketplaceWebServiceException se) { log.error("Caught MarketplaceWebServiceException", se); throw se; } catch (Throwable t) { log.error("Caught Exception", t); throw new MarketplaceWebServiceException(t); } return response; }
From source file:org.dasein.cloud.openstack.nova.os.AbstractMethod.java
@SuppressWarnings("unused") protected @Nullable String postStream(@Nonnull String authToken, @Nonnull String endpoint, @Nonnull String resource, @Nonnull 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() + ".postStream(" + authToken + "," + endpoint + "," + resource + "," + md5Hash + ",INPUTSTREAM)"); }//from ww w.j a va 2 s .com if (wire.isDebugEnabled()) { wire.debug("---------------------------------------------------------------------------------" + endpoint + resource); wire.debug(""); } HttpClient client = null; try { client = getClient(); HttpPost post = new HttpPost(endpoint + resource); post.addHeader("Content-Type", "application/octet-stream"); post.addHeader("X-Auth-Token", authToken); if (wire.isDebugEnabled()) { wire.debug(post.getRequestLine().toString()); for (Header header : post.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } post.setEntity(new InputStreamEntity(stream, -1)); wire.debug(" ---- BINARY DATA ---- "); wire.debug(""); HttpResponse response; try { APITrace.trace(provider, "POST " + toAPIResource(resource)); response = client.execute(post); 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 : post.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_ACCEPTED && code != HttpStatus.SC_NO_CONTENT) { std.error("postStream(): Expected ACCEPTED or NO CONTENT for POST 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("postString(): [" + code + " : " + items.message + "] " + items.details); throw new NovaException(items); } else { wire.debug(""); 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 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() + ".postStream()"); } if (wire.isDebugEnabled()) { wire.debug(""); wire.debug("---------------------------------------------------------------------------------" + endpoint + resource); } } }
From source file:com.infinities.skyport.openstack.nova.os.SkyportNovaMethod.java
@Override @SuppressWarnings("unused") protected @Nullable String postStream(@Nonnull String authToken, @Nonnull String endpoint, @Nonnull String resource, @Nonnull 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() + ".postStream(" + authToken + "," + endpoint + "," + resource + "," + md5Hash + ",INPUTSTREAM)"); }//from w ww . j a va 2s .c om if (wire.isDebugEnabled()) { wire.debug("---------------------------------------------------------------------------------" + endpoint + resource); wire.debug(""); } HttpClient client = null; try { client = getClient(); HttpPost post = new HttpPost(endpoint + resource); post.addHeader("Content-Type", "application/octet-stream"); post.addHeader("X-Auth-Token", authToken); if (wire.isDebugEnabled()) { wire.debug(post.getRequestLine().toString()); for (Header header : post.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } post.setEntity(new InputStreamEntity(stream, -1)); wire.debug(" ---- BINARY DATA ---- "); wire.debug(""); HttpResponse response; try { APITrace.trace(provider, "POST " + toAPIResource(resource)); response = client.execute(post); 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 : post.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_ACCEPTED && code != HttpStatus.SC_NO_CONTENT) { std.error("postStream(): Expected ACCEPTED or NO CONTENT for POST 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("postString(): [" + code + " : " + items.message + "] " + items.details); throw new NovaException(items); } else { wire.debug(""); 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 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() + ".postStream()"); } if (wire.isDebugEnabled()) { wire.debug(""); wire.debug("---------------------------------------------------------------------------------" + endpoint + resource); } } }
From source file:com.dropbox.client2.DropboxAPI.java
/** * Creates a request to upload an {@link InputStream} to a Dropbox file. * You can then {@code upload()} or {@code abort()} this request. This is * the advanced version, which you should only use if you really need the * flexibility of uploading using an {@link InputStream}. * * @param path the full Dropbox path where to put the file, including * directories and filename.// w w w . java 2 s . c o m * @param is the {@link InputStream} from which to upload. * @param length the amount of bytes to read from the {@link InputStream}. * @param overwrite whether to overwrite the file if it already exists. If * true, any existing file will always be overwritten. If false, * files will be overwritten only if the {@code parentRev} matches * the current rev on the server. Otherwise, there is a conflict, * which is resolved by the behavior specified by autorename. * @param parentRev the rev of the file at which the user started editing * it (obtained from a metadata call), or null if this is a new * upload. If null, or if it does not match the latest rev on the * server, a copy of the file will be created and you'll receive * the new metadata upon executing the request. * @param autoRename If False, conflicts produce a DropboxServerException. * If True, a conflicted copy of the file will be created and you * will get the new file's metadata {@link Entry}. * @param listener an optional {@link ProgressListener} to receive upload * progress updates, or null. * * @return an {@link UploadRequest}. * * @throws IllegalArgumentException if {@code newFilename} is null or * empty. * @throws DropboxUnlinkedException if you have not set an access token * pair on the session, or if the user has revoked access. * @throws DropboxFileSizeException if the file is bigger than the * maximum allowed by the API. See * {@code DropboxAPI.MAX_UPLOAD_SIZE}. * @throws DropboxException for any other unknown errors. This is also a * superclass of all other Dropbox exceptions, so you may want to * only catch this exception which signals that some kind of error * occurred. */ private UploadRequest putFileRequest(String path, InputStream is, long length, boolean overwrite, String parentRev, boolean autoRename, ProgressListener listener) throws DropboxException { if (path == null || path.equals("")) { throw new IllegalArgumentException("path is null or empty."); } assertAuthenticated(); if (!path.startsWith("/")) { path = "/" + path; } String target = "/files_put/" + session.getAccessType() + path; if (parentRev == null) { parentRev = ""; } String[] params = new String[] { "overwrite", String.valueOf(overwrite), "parent_rev", parentRev, "autorename", String.valueOf(autoRename), "locale", session.getLocale().toString() }; String url = RESTUtility.buildURL(session.getContentServer(), VERSION, target, params); HttpPut req = new HttpPut(url); session.sign(req); InputStreamEntity isEntity = new InputStreamEntity(is, length); isEntity.setContentEncoding("application/octet-stream"); isEntity.setChunked(false); HttpEntity entity = isEntity; if (listener != null) { entity = new ProgressHttpEntity(entity, listener); } req.setEntity(entity); return new BasicUploadRequest(req, session); }
From source file:net.www_eee.portal.channels.ProxyChannel.java
/** * Construct the {@link HttpUriRequest} that will be used to {@linkplain #doProxyRequest(Page.Request, Channel.Mode) * proxy} content while fulfilling the specified <code>pageRequest</code>. This method will * {@linkplain #getProxiedFileURL(Page.Request, Channel.Mode, boolean) calculate} the proxied file URL, * {@linkplain #createProxyRequestObject(Page.Request, Channel.Mode, URL) create} the appropriate type of request * object, set it's {@linkplain HttpUriRequest#setHeader(String, String) headers}, and, if this channel is * {@linkplain net.www_eee.portal.Page.Request#isMaximized(Channel) maximized}, set any * {@linkplain HttpEntityEnclosingRequest#setEntity(HttpEntity) entity} that was * {@linkplain net.www_eee.portal.Page.Request#getEntity() provided} by the <code>pageRequest</code>. * /* www . ja va 2 s . c o m*/ * @param pageRequest The {@link net.www_eee.portal.Page.Request Request} currently being processed. * @param mode The {@link net.www_eee.portal.Channel.Mode Mode} of the request. * @param proxyClient The {@link #createProxyClient(Page.Request) HttpClient} performing the proxy request. * @return The proxy {@link HttpUriRequest} object. * @throws WWWEEEPortal.Exception If a problem occurred while determining the result. * @throws WebApplicationException If a problem occurred while determining the result. * @see #doProxyRequest(Page.Request, Channel.Mode) * @see #PROXY_REQUEST_HOOK */ protected HttpRequestBase createProxyRequest(final Page.Request pageRequest, final Mode mode, final CloseableHttpClient proxyClient) throws WWWEEEPortal.Exception, WebApplicationException { final URL proxiedFileURL = getProxiedFileURL(pageRequest, mode, true); final Object[] context = new Object[] { mode, proxiedFileURL }; HttpRequestBase proxyRequest = PROXY_REQUEST_HOOK.value(plugins, context, pageRequest); if (proxyRequest == null) { proxyRequest = createProxyRequestObject(pageRequest, mode, proxiedFileURL); final String userAgent = getProxyRequestUserAgentHeader(pageRequest, mode, proxyClient, proxiedFileURL, proxyRequest); if (userAgent != null) proxyRequest.setHeader("User-Agent", userAgent); final String acceptLanguage = getProxyRequestAcceptLanguageHeader(pageRequest, mode, proxyClient, proxiedFileURL, proxyRequest); if (acceptLanguage != null) proxyRequest.setHeader("Accept-Language", acceptLanguage); final String accept = getProxyRequestAcceptHeader(pageRequest, mode, proxyClient, proxiedFileURL, proxyRequest); if (accept != null) proxyRequest.setHeader("Accept", accept); final String authorization = getProxyRequestAuthorizationHeader(pageRequest, mode, proxyClient, proxiedFileURL, proxyRequest); if (authorization != null) proxyRequest.setHeader("Authorization", authorization); if (Mode.RESOURCE.equals(mode)) { final Optional<String> ifMatch = RESTUtil.getFirstHeaderValue(pageRequest.getHttpHeaders(), "If-Match", Function.identity()); if (ifMatch.isPresent()) proxyRequest.setHeader("If-Match", ifMatch.get()); final Optional<String> ifModifiedSince = RESTUtil.getFirstHeaderValue(pageRequest.getHttpHeaders(), "If-Modified-Since", Function.identity()); if (ifModifiedSince.isPresent()) proxyRequest.setHeader("If-Modified-Since", ifModifiedSince.get()); final Optional<String> ifNoneMatch = RESTUtil.getFirstHeaderValue(pageRequest.getHttpHeaders(), "If-None-Match", Function.identity()); if (ifNoneMatch.isPresent()) proxyRequest.setHeader("If-None-Match", ifNoneMatch.get()); final Optional<String> ifUnmodifiedSince = RESTUtil.getFirstHeaderValue( pageRequest.getHttpHeaders(), "If-Unmodified-Since", Function.identity()); if (ifUnmodifiedSince.isPresent()) proxyRequest.setHeader("If-Unmodified-Since", ifUnmodifiedSince.get()); } if (!isCacheControlClientDirectivesDisabled(pageRequest)) { final Optional<CacheControl> cacheControl = RESTUtil .getFirstHeaderValue(pageRequest.getHttpHeaders(), "Cache-Control", CacheControl::valueOf); if (cacheControl.isPresent()) proxyRequest.setHeader("Cache-Control", cacheControl.get().toString()); } if (pageRequest.isMaximized(this)) { final MediaType contentType = pageRequest.getHttpHeaders().getMediaType(); if (contentType != null) proxyRequest.setHeader("Content-Type", contentType.toString()); final DataSource entity = pageRequest.getEntity(); if ((entity != null) && (proxyRequest instanceof HttpEntityEnclosingRequest)) { try { final Optional<String> contentLengthString = RESTUtil.getFirstHeaderValue( pageRequest.getHttpHeaders(), "Content-Length", Function.identity()); final HttpEntity httpEntity = new InputStreamEntity(entity.getInputStream(), (contentLengthString.isPresent()) ? Long.parseLong(contentLengthString.get()) : -1); ((HttpEntityEnclosingRequest) proxyRequest).setEntity(httpEntity); } catch (NumberFormatException nfe) { throw new WebApplicationException(nfe, Response.Status.INTERNAL_SERVER_ERROR); } catch (IOException ioe) { throw new WWWEEEPortal.OperationalException(ioe); } } } // if (pageRequest.isMaximized(this)) } // if (proxyRequest == null) proxyRequest = PROXY_REQUEST_HOOK .requireFilteredResult(PROXY_REQUEST_HOOK.filter(plugins, context, pageRequest, proxyRequest)); return proxyRequest; }