List of usage examples for org.apache.http.entity BasicHttpEntity BasicHttpEntity
public BasicHttpEntity()
From source file:org.apache.nifi.remote.util.SiteToSiteRestApiClient.java
/** * <p>//from ww w. ja va2s. c o m * Initiate a transaction for sending data. * </p> * * <p> * If a proxy server requires auth, the proxy server returns 407 response with available auth schema such as basic or digest. * Then client has to resend the same request with its credential added. * This mechanism is problematic for sending data from NiFi. * </p> * * <p> * In order to resend a POST request with auth param, * NiFi has to either read flow-file contents to send again, or keep the POST body somewhere. * If we store that in memory, it would causes OOM, or storing it on disk slows down performance. * Rolling back processing session would be overkill. * Reading flow-file contents only when it's ready to send in a streaming way is ideal. * </p> * * <p> * Additionally, the way proxy authentication is done is vary among Proxy server software. * Some requires 407 and resend cycle for every requests, while others keep a connection between a client and * the proxy server, then consecutive requests skip auth steps. * The problem is, that how should we behave is only told after sending a request to the proxy. * </p> * * In order to handle above concerns correctly and efficiently, this method do the followings: * * <ol> * <li>Send a GET request to controller resource, to initiate an HttpAsyncClient. The instance will be used for further requests. * This is not required by the Site-to-Site protocol, but it can setup proxy auth state safely.</li> * <li>Send a POST request to initiate a transaction. While doing so, it captures how a proxy server works. * If 407 and resend cycle occurs here, it implies that we need to do the same thing again when we actually send the data. * Because if the proxy keeps using the same connection and doesn't require an auth step, it doesn't do so here.</li> * <li>Then this method stores whether the final POST request should wait for the auth step. * So that {@link #openConnectionForSend} can determine when to produce contents.</li> * </ol> * * <p> * The above special sequence is only executed when a proxy instance is set, and its username is set. * </p> * * @param post a POST request to establish transaction * @return POST request response * @throws IOException thrown if the post request failed */ private HttpResponse initiateTransactionForSend(final HttpPost post) throws IOException { if (shouldCheckProxyAuth()) { final CloseableHttpAsyncClient asyncClient = getHttpAsyncClient(); final HttpGet get = createGetControllerRequest(); final Future<HttpResponse> getResult = asyncClient.execute(get, null); try { final HttpResponse getResponse = getResult.get(readTimeoutMillis, TimeUnit.MILLISECONDS); logger.debug("Proxy auth check has done. getResponse={}", getResponse.getStatusLine()); } catch (final ExecutionException e) { logger.debug("Something has happened at get controller requesting thread for proxy auth check. {}", e.getMessage()); throw toIOException(e); } catch (TimeoutException | InterruptedException e) { throw new IOException(e); } } final HttpAsyncRequestProducer asyncRequestProducer = new HttpAsyncRequestProducer() { private boolean requestHasBeenReset = false; @Override public HttpHost getTarget() { return URIUtils.extractHost(post.getURI()); } @Override public HttpRequest generateRequest() throws IOException, HttpException { final BasicHttpEntity entity = new BasicHttpEntity(); post.setEntity(entity); return post; } @Override public void produceContent(ContentEncoder encoder, IOControl ioctrl) throws IOException { encoder.complete(); if (shouldCheckProxyAuth() && requestHasBeenReset) { logger.debug("Produced content again, assuming the proxy server requires authentication."); proxyAuthRequiresResend.set(true); } } @Override public void requestCompleted(HttpContext context) { debugProxyAuthState(context); } @Override public void failed(Exception ex) { final String msg = String.format("Failed to create transaction for %s", post.getURI()); logger.error(msg, ex); eventReporter.reportEvent(Severity.WARNING, EVENT_CATEGORY, msg); } @Override public boolean isRepeatable() { return true; } @Override public void resetRequest() throws IOException { requestHasBeenReset = true; } @Override public void close() throws IOException { } }; final Future<HttpResponse> responseFuture = getHttpAsyncClient().execute(asyncRequestProducer, new BasicAsyncResponseConsumer(), null); final HttpResponse response; try { response = responseFuture.get(readTimeoutMillis, TimeUnit.MILLISECONDS); } catch (final ExecutionException e) { logger.debug("Something has happened at initiate transaction requesting thread. {}", e.getMessage()); throw toIOException(e); } catch (TimeoutException | InterruptedException e) { throw new IOException(e); } return response; }
From source file:com.tmount.business.cloopen.restAPI.RestAPI.java
/** * ??// ww w .ja va 2s .c o m * @param accountSid * @param authToken * @param appId * @param subAccountSid * @return * @throws NoSuchAlgorithmException * @throws KeyManagementException */ public String CloseSubAccount(String accountSid, String authToken, String appId, String subAccountSid) throws NoSuchAlgorithmException, KeyManagementException { // ? String result = ""; // HttpClient CcopHttpClient chc = new CcopHttpClient(); DefaultHttpClient httpclient = chc.registerSSL("app.cloopen.com", "TLS", 8883, "https"); try { // URL String timestamp = DateUtil.dateToStr(new Date(), DateUtil.DATE_TIME_NO_SLASH); // md5(Id +? + ) String sig = accountSid + authToken + timestamp; // MD5 EncryptUtil eu = new EncryptUtil(); String signature = eu.md5Digest(sig); String url = (new StringBuilder(hostname)).append("/").append(softVer).append("/Accounts/") .append(accountSid).append("/CloseSubAccount?sig=").append(signature).toString(); // HttpPost System.out.println("url:" + url); HttpPost httppost = new HttpPost(url); setHttpHeader(httppost); String src = accountSid + ":" + timestamp; // base64(Id + ? +) String auth = eu.base64Encoder(src); httppost.setHeader("Authorization", auth); String body = null; if (!JsonUtils.JSON_ENABLE) { // Body body = (new StringBuilder("<?xml version='1.0' encoding='utf-8'?><SubAccount>").append("<appId>")) .append(appId).append("</appId>") .append("<subAccountSid>" + subAccountSid + "</subAccountSid> </SubAccount>").toString(); } System.out.println("CloseSubAccount : request _" + body); BasicHttpEntity requestBody = new BasicHttpEntity(); requestBody.setContent(new ByteArrayInputStream(body.getBytes("UTF-8"))); requestBody.setContentLength(body.getBytes("UTF-8").length); httppost.setEntity(requestBody); // HttpResponse response = httpclient.execute(httppost); // ??? HttpEntity entity = response.getEntity(); if (entity != null) { result = EntityUtils.toString(entity, "UTF-8"); } // ?HTTP?? EntityUtils.consume(entity); } catch (Exception e) { e.printStackTrace(); } finally { // httpclient.getConnectionManager().shutdown(); } return result; }
From source file:org.restcomm.camelgateway.slee.CamelGatewaySbb.java
private void pushContent(HttpUriRequest request, String contentType, String contentEncoding, byte[] content) { // TODO: check other preconditions? if (contentType != null && content != null && request instanceof HttpEntityEnclosingRequest) { BasicHttpEntity entity = new BasicHttpEntity(); entity.setContent(new ByteArrayInputStream(content)); entity.setContentLength(content.length); entity.setChunked(false);/*from w w w . j a va 2 s .c o m*/ if (contentEncoding != null) entity.setContentEncoding(contentEncoding); entity.setContentType(contentType); HttpEntityEnclosingRequest rr = (HttpEntityEnclosingRequest) request; rr.setEntity(entity); } }
From source file:com.cloud.api.ApiServer.java
private void writeResponse(HttpResponse resp, final String responseText, final int statusCode, String responseType, String reasonPhrase) { try {//from ww w . j a v a 2s. co m resp.setStatusCode(statusCode); resp.setReasonPhrase(reasonPhrase); BasicHttpEntity body = new BasicHttpEntity(); if (BaseCmd.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) { // JSON response body.setContentType(jsonContentType); if (responseText == null) { body.setContent(new ByteArrayInputStream( "{ \"error\" : { \"description\" : \"Internal Server Error\" } }".getBytes("UTF-8"))); } } else { body.setContentType("text/xml"); if (responseText == null) { body.setContent( new ByteArrayInputStream("<error>Internal Server Error</error>".getBytes("UTF-8"))); } } if (responseText != null) { body.setContent(new ByteArrayInputStream(responseText.getBytes("UTF-8"))); } resp.setEntity(body); } catch (Exception ex) { s_logger.error("error!", ex); } }
From source file:org.apache.synapse.transport.nhttp.ClientHandler.java
/** * Perform processing of the received response though Axis2 * * @param conn HTTP connection to be processed * @param context HTTP context associated with the connection * @param response HTTP response associated with the connection *//*from w w w .jav a2s . c om*/ private void processResponse(final NHttpClientConnection conn, HttpContext context, HttpResponse response) { ContentInputBuffer inputBuffer = null; MessageContext outMsgContext = (MessageContext) context.getAttribute(OUTGOING_MESSAGE_CONTEXT); String endptPrefix = (String) context.getAttribute(NhttpConstants.ENDPOINT_PREFIX); String requestMethod = (String) context.getAttribute(NhttpConstants.HTTP_REQ_METHOD); int statusCode = response.getStatusLine().getStatusCode(); boolean expectEntityBody = false; if (!"HEAD".equals(requestMethod) && !"OPTIONS".equals(requestMethod) && statusCode >= HttpStatus.SC_OK && statusCode != HttpStatus.SC_NO_CONTENT && statusCode != HttpStatus.SC_NOT_MODIFIED && statusCode != HttpStatus.SC_RESET_CONTENT) { expectEntityBody = true; } else if (NhttpConstants.HTTP_HEAD.equals(requestMethod)) { // When invoking http HEAD request esb set content length as 0 to response header. Since there is no message // body content length cannot be calculated inside synapse. Hence additional two headers are added to // which contains content length of the backend response and the request method. These headers are removed // before submitting the actual response. response.addHeader(NhttpConstants.HTTP_REQUEST_METHOD, requestMethod); if (response.getFirstHeader(HTTP.CONTENT_LEN) != null) { response.addHeader(NhttpConstants.ORIGINAL_CONTENT_LEN, response.getFirstHeader(HTTP.CONTENT_LEN).getValue()); } } if (expectEntityBody) { inputBuffer = new SharedInputBuffer(cfg.getBufferSize(), conn, allocator); context.setAttribute(RESPONSE_SINK_BUFFER, inputBuffer); BasicHttpEntity entity = new BasicHttpEntity(); if (response.getStatusLine().getProtocolVersion().greaterEquals(HttpVersion.HTTP_1_1)) { entity.setChunked(true); } response.setEntity(entity); context.setAttribute(ExecutionContext.HTTP_RESPONSE, response); } else { conn.resetInput(); conn.resetOutput(); if (context.getAttribute(NhttpConstants.DISCARD_ON_COMPLETE) != null || !connStrategy.keepAlive(response, context)) { try { // this is a connection we should not re-use connpool.forget(conn); shutdownConnection(conn, false, null); context.removeAttribute(RESPONSE_SINK_BUFFER); context.removeAttribute(REQUEST_SOURCE_BUFFER); } catch (Exception ignore) { } } else { connpool.release(conn); } } workerPool .execute(new ClientWorker(cfgCtx, inputBuffer == null ? null : new ContentInputStream(inputBuffer), response, outMsgContext, endptPrefix)); }
From source file:org.jets3t.service.impl.rest.httpclient.RestStorageService.java
/** * Beware of high memory requirements when creating large S3 objects when the Content-Length * is not set in the object./*from w w w.j a v a 2 s . c om*/ */ @Override protected StorageObject putObjectImpl(String bucketName, StorageObject object) throws ServiceException { if (log.isDebugEnabled()) { log.debug("Creating Object with key " + object.getKey() + " in bucket " + bucketName); } HttpEntity requestEntity = null; if (object.getDataInputStream() != null) { if (object.containsMetadata(StorageObject.METADATA_HEADER_CONTENT_LENGTH)) { if (log.isDebugEnabled()) { log.debug("Uploading object data with Content-Length: " + object.getContentLength()); } requestEntity = new RepeatableRequestEntity(object.getKey(), object.getDataInputStream(), object.getContentType(), object.getContentLength(), this.jets3tProperties, isLiveMD5HashingRequired(object)); } else { // Use a BufferedHttpEntity for objects with an unknown content length, as the // entity will cache the results and doesn't need to know the data length in advance. if (log.isWarnEnabled()) { log.warn( "Content-Length of data stream not set, will automatically determine data length in memory"); } BasicHttpEntity basicHttpEntity = new BasicHttpEntity(); basicHttpEntity.setContent(object.getDataInputStream()); try { requestEntity = new BufferedHttpEntity(basicHttpEntity); } catch (IOException ioe) { throw new ServiceException("Unable to read data stream of unknown length", ioe); } } } putObjectWithRequestEntityImpl(bucketName, object, requestEntity, null); return object; }