com.ning.http.client.AsyncHttpClient.BoundRequestBuilder Java Examples
The following examples show how to use
com.ning.http.client.AsyncHttpClient.BoundRequestBuilder.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AgentManager.java From Baragon with Apache License 2.0 | 6 votes |
private AsyncHttpClient.BoundRequestBuilder buildAgentRequest(String url, AgentRequestType requestType) { final BoundRequestBuilder builder; switch (requestType) { case APPLY: builder = asyncHttpClient.preparePost(url); break; case REVERT: case CANCEL: builder = asyncHttpClient.prepareDelete(url); break; default: throw new RuntimeException("Don't know how to send requests for " + requestType); } if (baragonAuthKey.isPresent()) { builder.addQueryParam("authkey", baragonAuthKey.get()); } return builder; }
Example #2
Source File: PlexConnector.java From openhab1-addons with Eclipse Public License 2.0 | 6 votes |
private void internalSendCommand(String machineIdentifier, String url) throws IOException { logger.debug("Calling url {}", url); BoundRequestBuilder builder = client.prepareGet(url).setHeaders(getDefaultHeaders()) .setHeader("X-Plex-Target-Client-Identifier", machineIdentifier); builder.execute(new AsyncCompletionHandler<Response>() { @Override public Response onCompleted(Response response) throws Exception { if (response.getStatusCode() != 200) { logger.error("Error while sending command to Plex: {}\r\n{}", response.getStatusText(), response.getResponseBody()); } return response; } @Override public void onThrowable(Throwable t) { logger.error("Error sending command to Plex", t); } }); }
Example #3
Source File: LoadBalancerClientImpl.java From Singularity with Apache License 2.0 | 6 votes |
@Override public SingularityLoadBalancerUpdate cancel( LoadBalancerRequestId loadBalancerRequestId ) { final String uri = getLoadBalancerUri(loadBalancerRequestId); final BoundRequestBuilder requestBuilder = httpClient.prepareDelete(uri); if (loadBalancerQueryParams.isPresent()) { addAllQueryParams(requestBuilder, loadBalancerQueryParams.get()); } return sendRequestWrapper( loadBalancerRequestId, LoadBalancerMethod.CANCEL, requestBuilder.build(), BaragonRequestState.UNKNOWN ); }
Example #4
Source File: LoadBalancerClientImpl.java From Singularity with Apache License 2.0 | 6 votes |
@Override public SingularityLoadBalancerUpdate getState( LoadBalancerRequestId loadBalancerRequestId ) { final String uri = getLoadBalancerUri(loadBalancerRequestId); final BoundRequestBuilder requestBuilder = httpClient.prepareGet(uri); if (loadBalancerQueryParams.isPresent()) { addAllQueryParams(requestBuilder, loadBalancerQueryParams.get()); } return sendRequestWrapper( loadBalancerRequestId, LoadBalancerMethod.CHECK_STATE, requestBuilder.build(), BaragonRequestState.UNKNOWN ); }
Example #5
Source File: AbstractLeaderAwareResource.java From Singularity with Apache License 2.0 | 6 votes |
private void copyHeadersAndParams( BoundRequestBuilder requestBuilder, HttpServletRequest request ) { Enumeration<String> headerNames = request.getHeaderNames(); if (headerNames != null) { while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); requestBuilder.addHeader(headerName, request.getHeader(headerName)); LOG.trace("Copied header {}:{}", headerName, request.getHeader(headerName)); } } Enumeration<String> parameterNames = request.getParameterNames(); if (parameterNames != null) { while (parameterNames.hasMoreElements()) { String parameterName = parameterNames.nextElement(); requestBuilder.addQueryParam(parameterName, request.getParameter(parameterName)); LOG.trace( "Copied query param {}={}", parameterName, request.getParameter(parameterName) ); } } }
Example #6
Source File: MyHttpUtils.java From restcommander with Apache License 2.0 | 6 votes |
public static void addDynamicHeaders(BoundRequestBuilder builder, String httpHeaderType) { if (builder != null && httpHeaderType != null) { /** * TODO: for further extension */ // if (httpHeaderType.equalsIgnoreCase(MyHttpUtils.TBC) // ){ // builder.addHeader("DynamicHeaderKey", HeaderUtils.addDynamicHeader(arg)); // } } else { models.utils.LogUtils.printLogError ("Failed to build request; builder is null, unknown method in createRequest()"); } }
Example #7
Source File: MyHttpUtils.java From restcommander with Apache License 2.0 | 6 votes |
/** * 20131215 * Called in httpWorker * @param builder * @param protocol */ public static void addAllHeadersFromHeaderMetadataMap(BoundRequestBuilder builder, String httpHeaderType) { if (builder != null && httpHeaderType != null) { AgentDataProvider adp = AgentDataProvider.getInstance(); HttpHeaderMetadata httpHeaderMetadata = adp.headerMetadataMap.get(httpHeaderType); addHeaders(builder, httpHeaderMetadata.getHeaderMap()); // add dynamic headers addDynamicHeaders(builder, httpHeaderType); } else { models.utils.LogUtils.printLogError ("Failed to build request; builder is null, unknown method in createRequest()"); } }
Example #8
Source File: MyHttpUtils.java From restcommander with Apache License 2.0 | 5 votes |
public static void addHeaders(BoundRequestBuilder builder, Map<String, String> headerMap) { for (Entry<String, String> entry : headerMap.entrySet()) { String name = entry.getKey(); String value = entry.getValue(); builder.addHeader(name, value); } }
Example #9
Source File: AgentManager.java From Baragon with Apache License 2.0 | 5 votes |
private AsyncHttpClient.BoundRequestBuilder buildAgentBatchRequest(String url, List<BaragonRequestBatchItem> batch) throws JsonProcessingException { final BoundRequestBuilder builder = asyncHttpClient.preparePost(url); if (baragonAuthKey.isPresent()) { builder.addQueryParam("authkey", baragonAuthKey.get()); } builder.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); builder.setBody(objectMapper.writeValueAsBytes(batch)); return builder; }
Example #10
Source File: SingularityWebhookSender.java From Singularity with Apache License 2.0 | 5 votes |
private <T> CompletableFuture<Response> executeWebhookAsync( String uri, Object payload, AbstractSingularityWebhookAsyncHandler<T> handler ) { LOG.trace("Sending {} to {}", payload, uri); BoundRequestBuilder postRequest = http.preparePost(uri); postRequest.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); try { postRequest.setBody(objectMapper.writeValueAsBytes(payload)); } catch (JsonProcessingException e) { throw new RuntimeException(e); } CompletableFuture<Response> webhookFuture = new CompletableFuture<>(); try { handler.setCompletableFuture(webhookFuture); postRequest.execute(handler); } catch (Throwable t) { LOG.warn("Couldn't execute webhook to {}", uri, t); if (handler.shouldDeleteUpdateDueToQueueAboveCapacity()) { handler.deleteWebhookUpdate(); } webhookFuture.completeExceptionally(t); } return webhookFuture; }
Example #11
Source File: LoadBalancerClientImpl.java From Singularity with Apache License 2.0 | 5 votes |
private SingularityLoadBalancerUpdate sendLoadBalancerRequest( LoadBalancerRequestId loadBalancerRequestId, BaragonRequest loadBalancerRequest, LoadBalancerMethod method ) { try { LOG.trace("Preparing to send request {}", loadBalancerRequest); final BoundRequestBuilder requestBuilder = httpClient .preparePost(loadBalancerUri) .addHeader(HEADER_CONTENT_TYPE, CONTENT_TYPE_JSON) .setBody(objectMapper.writeValueAsBytes(loadBalancerRequest)); if (loadBalancerQueryParams.isPresent()) { addAllQueryParams(requestBuilder, loadBalancerQueryParams.get()); } return sendRequestWrapper( loadBalancerRequestId, method, requestBuilder.build(), BaragonRequestState.FAILED ); } catch (IOException e) { return new SingularityLoadBalancerUpdate( BaragonRequestState.UNKNOWN, loadBalancerRequestId, Optional.of(e.getMessage()), System.currentTimeMillis(), method, Optional.of(loadBalancerUri) ); } }
Example #12
Source File: LoadBalancerClientImpl.java From Singularity with Apache License 2.0 | 5 votes |
private void addAllQueryParams( BoundRequestBuilder boundRequestBuilder, Map<String, String> queryParams ) { for (Map.Entry<String, String> entry : queryParams.entrySet()) { boundRequestBuilder.addQueryParam(entry.getKey(), entry.getValue()); } }
Example #13
Source File: LoadBalancerClientImpl.java From Singularity with Apache License 2.0 | 5 votes |
public SingularityCheckingUpstreamsUpdate getLoadBalancerServiceStateForRequest( String singularityRequestId ) throws IOException, InterruptedException, ExecutionException, TimeoutException { final String loadBalancerStateUri = getLoadBalancerStateUri(singularityRequestId); final BoundRequestBuilder requestBuilder = httpClient.prepareGet( loadBalancerStateUri ); final Request request = requestBuilder.build(); LOG.debug( "Sending load balancer {} request for {} to {}", request.getMethod(), singularityRequestId, request.getUrl() ); ListenableFuture<Response> future = httpClient.executeRequest(request); Response response = future.get(loadBalancerTimeoutMillis, TimeUnit.MILLISECONDS); LOG.debug( "Load balancer {} request {} returned with code {}", request.getMethod(), singularityRequestId, response.getStatusCode() ); Optional<BaragonServiceState> maybeBaragonServiceState = Optional.ofNullable( objectMapper.readValue(response.getResponseBodyAsBytes(), BaragonServiceState.class) ); return new SingularityCheckingUpstreamsUpdate( maybeBaragonServiceState, singularityRequestId ); }
Example #14
Source File: WSAsync.java From restcommander with Apache License 2.0 | 5 votes |
private Promise<HttpResponse> execute(BoundRequestBuilder builder) { try { final Promise<HttpResponse> smartFuture = new Promise<HttpResponse>(); prepare(builder).execute(new AsyncCompletionHandler<HttpResponse>() { @Override public HttpResponse onCompleted(Response response) throws Exception { HttpResponse httpResponse = new HttpAsyncResponse(response); smartFuture.invoke(httpResponse); return httpResponse; } @Override public void onThrowable(Throwable t) { // An error happened - must "forward" the exception to the one waiting for the result smartFuture.invokeWithException(t); } }); return smartFuture; } catch (Exception e) { throw new RuntimeException(e); } }
Example #15
Source File: PcHttpUtils.java From parallec with Apache License 2.0 | 5 votes |
/** * Adds the headers. * * @param builder * the builder * @param headerMap * the header map */ public static void addHeaders(BoundRequestBuilder builder, Map<String, String> headerMap) { for (Entry<String, String> entry : headerMap.entrySet()) { String name = entry.getKey(); String value = entry.getValue(); builder.addHeader(name, value); } }
Example #16
Source File: WSAsync.java From restcommander with Apache License 2.0 | 5 votes |
private BoundRequestBuilder prepare(BoundRequestBuilder builder) { if (this.username != null && this.password != null && this.scheme != null) { AuthScheme authScheme; switch (this.scheme) { case DIGEST: authScheme = AuthScheme.DIGEST; break; case NTLM: authScheme = AuthScheme.NTLM; break; case KERBEROS: authScheme = AuthScheme.KERBEROS; break; case SPNEGO: authScheme = AuthScheme.SPNEGO; break; case BASIC: authScheme = AuthScheme.BASIC; break; default: throw new RuntimeException("Scheme " + this.scheme + " not supported by the UrlFetch WS backend."); } builder.setRealm( (new RealmBuilder()) .setScheme(authScheme) .setPrincipal(this.username) .setPassword(this.password) .setUsePreemptiveAuth(true) .build() ); } for (String key: this.headers.keySet()) { builder.addHeader(key, headers.get(key)); } builder.setFollowRedirects(this.followRedirects); PerRequestConfig perRequestConfig = new PerRequestConfig(); perRequestConfig.setRequestTimeoutInMs(this.timeout * 1000); builder.setPerRequestConfig(perRequestConfig); return builder; }
Example #17
Source File: WSAsync.java From restcommander with Apache License 2.0 | 4 votes |
public BoundRequestBuilder prepareHead() { return prepareAll(httpClient.prepareHead(getUrlWithoutQueryString())); }
Example #18
Source File: HttpWorker.java From parallec with Apache License 2.0 | 4 votes |
/** * Creates the request. * * @return the bound request builder * @throws HttpRequestCreateException * the http request create exception */ public BoundRequestBuilder createRequest() throws HttpRequestCreateException { BoundRequestBuilder builder = null; getLogger().debug("AHC completeUrl " + requestUrl); try { switch (httpMethod) { case GET: builder = client.prepareGet(requestUrl); break; case POST: builder = client.preparePost(requestUrl); break; case PUT: builder = client.preparePut(requestUrl); break; case HEAD: builder = client.prepareHead(requestUrl); break; case OPTIONS: builder = client.prepareOptions(requestUrl); break; case DELETE: builder = client.prepareDelete(requestUrl); break; default: break; } PcHttpUtils.addHeaders(builder, this.httpHeaderMap); if (!Strings.isNullOrEmpty(postData)) { builder.setBody(postData); String charset = ""; if (null!=this.httpHeaderMap) { charset = this.httpHeaderMap.get("charset"); } if(!Strings.isNullOrEmpty(charset)) { builder.setBodyEncoding(charset); } } } catch (Exception t) { throw new HttpRequestCreateException( "Error in creating request in Httpworker. " + " If BoundRequestBuilder is null. Then fail to create.", t); } return builder; }
Example #19
Source File: HttpWorker.java From parallec with Apache License 2.0 | 4 votes |
@Override public void onReceive(Object message) throws Exception { try { if (message instanceof RequestWorkerMsgType) { switch ((RequestWorkerMsgType) message) { case PROCESS_REQUEST: tryCount++; if (tryCount == 1) { sender = getSender(); BoundRequestBuilder request = createRequest(); // 20150229: create the future and make sure future is // killed when timeout. responseFuture = request.execute(new HttpAsyncHandler( this)); timeoutDuration = Duration.create( actorMaxOperationTimeoutSec, TimeUnit.SECONDS); // To handle cases where nio response never comes back, // we // schedule a 'timeout' message to be sent to us 2 // seconds // after NIO's SO_TIMEOUT timeoutMessageCancellable = getContext() .system() .scheduler() .scheduleOnce( timeoutDuration, getSelf(), RequestWorkerMsgType.PROCESS_ON_TIMEOUT, getContext().system().dispatcher(), getSelf()); } else { getLogger().error( "duplicated PROCESS_REQUEST msg. ignore..."); } break; case CANCEL: getLogger().info( "Request was CANCELLED.................{}", requestUrl); cancelCancellable(); if (sender == null) sender = getSender(); reply(null, true, PcConstants.REQUEST_CANCELED, PcConstants.REQUEST_CANCELED, PcConstants.NA, PcConstants.NA_INT, null); break; case PROCESS_ON_EXCEPTION: String errorSummary = PcErrorMsgUtils.replaceErrorMsg(cause .toString()); String stackTrace = PcStringUtils.printStackTrace(cause); cancelCancellable(); reply(null, true, errorSummary, stackTrace, PcConstants.NA, PcConstants.NA_INT, null); break; case PROCESS_ON_TIMEOUT: getLogger().error("PROCESS_ON_TIMEOUT.................{}", requestUrl); cancelCancellable(); String errorMsg = String .format("HttpWorker Timedout after %d SEC (no response but no exception catched). Check URL: may be very slow or stuck.", actorMaxOperationTimeoutSec); reply(null, true, errorMsg, errorMsg, PcConstants.NA, PcConstants.NA_INT, null); break; case CHECK_FUTURE_STATE: default: this.cause = new ActorMessageTypeInvalidException( "ActorMessageTypeInvalidException error for url " + this.requestUrl); getSelf().tell(RequestWorkerMsgType.PROCESS_ON_EXCEPTION, getSelf()); break; } } else { unhandled(message); this.cause = new ActorMessageTypeInvalidException( "ActorMessageTypeInvalidException error for url " + this.requestUrl); getSelf().tell(RequestWorkerMsgType.PROCESS_ON_EXCEPTION, getSelf()); } } catch (Exception e) { this.cause = e; getSelf() .tell(RequestWorkerMsgType.PROCESS_ON_EXCEPTION, getSelf()); } }
Example #20
Source File: ArtifactoryInformation.java From artifactory_ssh_proxy with Apache License 2.0 | 4 votes |
@Override public BoundRequestBuilder getBoundRequestBuilder(BoundRequestBuilder boundRequestBuilder) { return boundRequestBuilder; }
Example #21
Source File: WSAsync.java From restcommander with Apache License 2.0 | 4 votes |
/** * Adds the queryString-part of the url to the BoundRequestBuilder */ protected void addQueryString(BoundRequestBuilder requestBuilder) { // AsyncHttpClient is by default encoding everything in utf-8 so for us to be able to use // different encoding we have configured AHC to use raw urls. When using raw urls, // AHC does not encode url and QueryParam with utf-8 - but there is another problem: // If we send raw (none-encoded) url (with queryString) to AHC, it does not url-encode it, // but transform all illegal chars to '?'. // If we pre-encoded the url with QueryString before sending it to AHC, ahc will decode it, and then // later break it with '?'. // This method basically does the same as RequestBuilderBase.buildUrl() except from destroying the // pre-encoding // does url contain query_string? int i = url.indexOf('?'); if ( i > 0) { try { // extract query-string-part String queryPart = url.substring(i+1); // parse queryPart - and decode it... (it is going to be re-encoded later) for( String param : queryPart.split("&")) { i = param.indexOf('='); String name; String value = null; if ( i<=0) { // only a flag name = URLDecoder.decode(param, encoding); } else { name = URLDecoder.decode(param.substring(0,i), encoding); value = URLDecoder.decode(param.substring(i+1), encoding); } if (value == null) { requestBuilder.addQueryParameter(URLEncoder.encode(name, encoding), null); } else { requestBuilder.addQueryParameter(URLEncoder.encode(name, encoding), URLEncoder.encode(value, encoding)); } } } catch (UnsupportedEncodingException e) { throw new RuntimeException("Error parsing query-part of url",e); } } }
Example #22
Source File: WSAsync.java From restcommander with Apache License 2.0 | 4 votes |
private BoundRequestBuilder prepareAll(BoundRequestBuilder requestBuilder) { checkFileBody(requestBuilder); addQueryString(requestBuilder); addGeneratedContentType(requestBuilder); return requestBuilder; }
Example #23
Source File: WSAsync.java From restcommander with Apache License 2.0 | 4 votes |
public BoundRequestBuilder prepareGet() { return prepareAll(httpClient.prepareGet(getUrlWithoutQueryString())); }
Example #24
Source File: WSAsync.java From restcommander with Apache License 2.0 | 4 votes |
public BoundRequestBuilder prepareOptions() { return prepareAll(httpClient.prepareOptions(getUrlWithoutQueryString())); }
Example #25
Source File: WSAsync.java From restcommander with Apache License 2.0 | 4 votes |
public BoundRequestBuilder preparePost() { return prepareAll(httpClient.preparePost(getUrlWithoutQueryString())); }
Example #26
Source File: TaskResource.java From Singularity with Apache License 2.0 | 4 votes |
public NingOutputToJaxRsStreamingOutputWrapper(BoundRequestBuilder requestBuilder) { this.requestBuilder = requestBuilder; }
Example #27
Source File: HttpWorker.java From restcommander with Apache License 2.0 | 4 votes |
@Override public void onReceive(Object message) throws Exception { try { if (message instanceof MessageType) { switch ((MessageType) message) { case PROCESS_REQUEST: tryCount++; if (tryCount == 1) { sender = getSender(); // Construct and submit NING Request BoundRequestBuilder request = createRequest(); // String targetUrl = request.build().getUrl(); request.execute(new HttpAsyncHandler(this)); timeoutDuration = Duration .create(VarUtils.ACTOR_MAX_OPERATION_TIME_SECONDS_DEFAULT, TimeUnit.SECONDS); } // To handle cases where nio response never comes back, we // schedule a 'timeout' message to be sent to us 2 seconds // after NIO's SO_TIMEOUT timeoutMessageCancellable = getContext() .system() .scheduler() .scheduleOnce(timeoutDuration, getSelf(), MessageType.PROCESS_ON_TIMEOUT, getContext().system().dispatcher()); break; case CANCEL: cancelCancellable(); reply(null, true, "RequestCanceled", null, VarUtils.NA); break; case PROCESS_ON_EXCEPTION: final StringWriter sw = new StringWriter(); final PrintWriter pw = new PrintWriter(sw); cause.printStackTrace(pw); String displayError = ErrorMsgUtils.replaceErrorMsg(cause .toString()); // 20130522: get details of error message out. String detailErrorMsgWithStackTrace = displayError + " Details: " + sw.toString(); cancelCancellable(); reply(null, true, detailErrorMsgWithStackTrace, sw.toString(), VarUtils.NA); break; case PROCESS_ON_TIMEOUT: models.utils.LogUtils.printLogError ("!!!Inside PROCESS_ON_TIMEOUT................." + requestUrl + "......... at " + DateUtils.getNowDateTimeStrSdsm()); cancelCancellable(); // 20130801 To match this: // PATTERN_EXTRACT_EXCEPTION_SUMMARY_FROM_ERROR_MSG to get // the regular // expression. String errorMsg = String .format("HttpWorker Timedout after %d SEC (no response but no exception catched). Check URL: may be very slow or stuck. Details more info", VarUtils.ACTOR_MAX_OPERATION_TIME_SECONDS_DEFAULT); reply(null, true, errorMsg, errorMsg, VarUtils.NA); break; case PROCESS_ON_RESPONSE_DATA: models.utils.LogUtils.printLogNormal ("Inside PROCESS_ON_RESPONSE_DATA UnsupportedOperation................."); cancelCancellable(); reply(null, true, "UnsupportedOperation", null, VarUtils.NA); break; } } else { unhandled(message); } } catch (Exception e) { tryCount = maxTries; this.cause = e; getSelf().tell(MessageType.PROCESS_ON_EXCEPTION, getSelf()); } }
Example #28
Source File: HttpWorker.java From restcommander with Apache License 2.0 | 4 votes |
public BoundRequestBuilder createRequest() { BoundRequestBuilder builder = null; try { String completeUrl = requestUrl; if (VarUtils.IN_DETAIL_DEBUG) { models.utils.LogUtils.printLogError("NING completeUrl " + completeUrl); } switch (httpMethod) { case GET: builder = client.prepareGet(completeUrl); break; case POST: builder = client.preparePost(completeUrl); break; case PUT: builder = client.preparePut(completeUrl); break; case DELETE: builder = client.prepareDelete(completeUrl); break; default: break; } if (builder != null) { //MyHttpUtils.addAllHeaders(builder, protocol); MyHttpUtils.addAllHeadersFromHeaderMetadataMap(builder, httpHeaderType); // // if (httpHeaderTypeNum == OperationWorker.HTTP_HEADER_TYPE_CMS) { // builder.addHeader("Authorization", VarUtils.AUTH_CMS_AGENT); // } if (!StringUtils.isNullOrEmpty(postData)) { builder.setBody(postData); } } else { models.utils.LogUtils.printLogError ("Failed to build request; builder is null, unknown method in createRequest()"); } } catch (Throwable t) { models.utils.LogUtils.printLogError("Error in createRequest at " + DateUtils.getNowDateTimeStrSdsm()); t.printStackTrace(); } return builder; }
Example #29
Source File: WSAsync.java From restcommander with Apache License 2.0 | 4 votes |
public BoundRequestBuilder preparePut() { return prepareAll(httpClient.preparePut(getUrlWithoutQueryString())); }
Example #30
Source File: WSAsync.java From restcommander with Apache License 2.0 | 4 votes |
public BoundRequestBuilder prepareDelete() { return prepareAll(httpClient.prepareDelete(getUrlWithoutQueryString())); }