@Test() public void uploadImage() { Response result = null; File file = new File("psyduck.jpg"); MimetypesFileTypeMap fileTypeMap = new MimetypesFileTypeMap(); AsyncHttpClient client = new AsyncHttpClient(new AsyncHttpClientConfig.Builder().build()); AsyncHttpClient.BoundRequestBuilder builder = client.preparePost("http://localhost:8080/"); builder.setHeader("Content-Type", "multipart/form-data"); builder.addBodyPart(new FilePart("image", file, fileTypeMap.getContentType(file), "UTF-8")); try { result = builder.execute().get(); System.out.println(result.getResponseBody()); } catch (Exception e) { e.printStackTrace(); } }
protected void handleDelete(URL requestUrl) throws ExecutionException, InterruptedException, KubernetesClientException, IOException { AsyncHttpClient.BoundRequestBuilder requestBuilder = getClient().getHttpClient().prepareDelete(requestUrl.toString()); Future<Response> f = requestBuilder.execute(); Response r = f.get(); assertResponseCode(r, 200); }
protected <T> T handleReplace(T updated, Class<T> type) throws ExecutionException, InterruptedException, KubernetesClientException, IOException { AsyncHttpClient.BoundRequestBuilder requestBuilder = getClient() .getHttpClient() .preparePut(getResourceUrl(checkNamespace(updated), checkName(updated)).toString()); requestBuilder.setBody(OBJECT_MAPPER.writer().writeValueAsString(updated)); return handleResponse(requestBuilder, 200, type); }
protected <T, I> T handleCreate(I resource, Class<T> outputType) throws ExecutionException, InterruptedException, KubernetesClientException, IOException { AsyncHttpClient.BoundRequestBuilder requestBuilder = getClient() .getHttpClient() .preparePost(getNamespacedUrl(checkNamespace(resource)).toString()); requestBuilder.setBody(OBJECT_MAPPER.writer().writeValueAsString(resource)); return handleResponse(requestBuilder, 201, outputType); }
@Test(groups = "standalone") public void basicAuthNegativeTest() throws IOException, ExecutionException, TimeoutException, InterruptedException { AsyncHttpClient client = new AsyncHttpClient(); AsyncHttpClient.BoundRequestBuilder r = client .prepareGet("http://127.0.0.1:" + port1 + "/") .setRealm((new Realm.RealmBuilder()).setPrincipal("fake").setPassword(admin).build()); Future<Response> f = r.execute(); Response resp = f.get(3, TimeUnit.SECONDS); assertNotNull(resp); assertEquals(resp.getStatusCode(), 401); }
protected <T> T handleResponse( AsyncHttpClient.BoundRequestBuilder requestBuilder, int successStatusCode, Class<T> type) throws ExecutionException, InterruptedException, KubernetesClientException, IOException { Future<Response> f = requestBuilder.execute(); Response r = f.get(); assertResponseCode(r, successStatusCode); return OBJECT_MAPPER.readValue(r.getResponseBodyAsStream(), type); }
@SuppressWarnings("deprecation") public Optional<MesosFileChunkObject> read( String slaveHostname, String fullPath, Optional<Long> offset, Optional<Long> length) throws SlaveNotFoundException { try { final AsyncHttpClient.BoundRequestBuilder builder = asyncHttpClient .prepareGet(String.format("http://%s:5051/files/read.json", slaveHostname)) .addQueryParameter("path", fullPath); PerRequestConfig timeoutConfig = new PerRequestConfig(); timeoutConfig.setRequestTimeoutInMs((int) configuration.getSandboxHttpTimeoutMillis()); builder.setPerRequestConfig(timeoutConfig); if (offset.isPresent()) { builder.addQueryParameter("offset", offset.get().toString()); } if (length.isPresent()) { builder.addQueryParameter("length", length.get().toString()); } final Response response = builder.execute().get(); if (response.getStatusCode() == 404) { return Optional.absent(); } if (response.getStatusCode() != 200) { throw new RuntimeException( String.format("Got HTTP %s from Mesos slave", response.getStatusCode())); } return Optional.of( objectMapper.readValue(response.getResponseBodyAsStream(), MesosFileChunkObject.class)); } catch (ConnectException ce) { throw new SlaveNotFoundException(ce); } catch (Exception e) { throw Throwables.propagate(e); } }
public Request apply(HttpRequest request) { for (HttpRequestFilter filter : request.getFilters()) { filter.filter(request); } AsyncHttpClient client = new AsyncHttpClient(); AsyncHttpClient.BoundRequestBuilder nativeRequestBuilder; String endpoint = request.getEndpoint().toASCIIString(); if (request.getMethod().equals(HttpMethod.HEAD)) { nativeRequestBuilder = client.prepareHead(endpoint); } else if (request.getMethod().equals(HttpMethod.GET)) { nativeRequestBuilder = client.prepareGet(endpoint); } else if (request.getMethod().equals(HttpMethod.DELETE)) { nativeRequestBuilder = client.prepareDelete(endpoint); } else if (request.getMethod().equals(HttpMethod.PUT)) { nativeRequestBuilder = client.preparePut(endpoint); } else if (request.getMethod().equals(HttpMethod.POST)) { nativeRequestBuilder = client.preparePost(endpoint); } else { throw new UnsupportedOperationException(request.getMethod()); } Payload payload = request.getPayload(); if (payload != null) { boolean chunked = "chunked".equals(request.getFirstHeaderOrNull("Transfer-Encoding")); if (request.getPayload().getContentMD5() != null) nativeRequestBuilder.addHeader( "Content-MD5", CryptoStreams.base64(request.getPayload().getContentMD5())); if (request.getPayload().getContentType() != null) nativeRequestBuilder.addHeader( HttpHeaders.CONTENT_TYPE, request.getPayload().getContentType()); if (!chunked) { Long length = checkNotNull(request.getPayload().getContentLength(), "payload.getContentLength"); nativeRequestBuilder.addHeader(HttpHeaders.CONTENT_LENGTH, length.toString()); } setPayload(nativeRequestBuilder, payload); } else { nativeRequestBuilder.addHeader(HttpHeaders.CONTENT_LENGTH, "0"); } nativeRequestBuilder.addHeader(HttpHeaders.USER_AGENT, USER_AGENT); for (String header : request.getHeaders().keySet()) { for (String value : request.getHeaders().get(header)) { nativeRequestBuilder.addHeader(header, value); } } return nativeRequestBuilder.build(); }
private void restCall(Tuple tuple) throws ExecutionException, InterruptedException { Future<Response> fureRet = null; for (RestInfo restInfo : restInfos) { String url = restInfo.getUrl(); String body = restInfo.getBody(); for (BaseBindColumnDef bindColumn : restInfo.getColumns()) { url = url.replace( "[:" + bindColumn.getName() + "]", tuple.getStringByField(bindColumn.getName())); if (body != null) { body = body.replace( "[:" + bindColumn.getName() + "]", tuple.getStringByField(bindColumn.getName())); } } AsyncHttpClient.BoundRequestBuilder boundRequestBuilder = null; if (RestCmd.PUT.equals(restInfo.getCmd())) { boundRequestBuilder = asyncHttpClient.preparePut(url); } else if (RestCmd.GET.equals(restInfo.getCmd())) { boundRequestBuilder = asyncHttpClient.prepareGet(url); } else if (RestCmd.DELETE.equals(restInfo.getCmd())) { boundRequestBuilder = asyncHttpClient.prepareDelete(url); } else if (RestCmd.POST.equals(restInfo.getCmd())) { boundRequestBuilder = asyncHttpClient.preparePost(url); } else { break; } if (body != null) { fureRet = boundRequestBuilder.setBody(body).execute(); } else { fureRet = boundRequestBuilder.execute(); } fureRet.get(); } }
public L list() throws KubernetesClientException { try { URL requestUrl = getNamespacedUrl(); AsyncHttpClient.BoundRequestBuilder requestBuilder = getClient().getHttpClient().prepareGet(requestUrl.toString()); String labelQueryParam = getLabelQueryParam(); if (labelQueryParam.length() > 0) { requestBuilder.addQueryParam("labelSelector", labelQueryParam); } String fieldQueryString = getFieldQueryParam(); if (fieldQueryString.length() > 0) { requestBuilder.addQueryParam("fieldSelector", fieldQueryString); } Future<Response> f = requestBuilder.execute(); Response r = f.get(); assertResponseCode(r, 200); return OBJECT_MAPPER.readValue(r.getResponseBodyAsStream(), listType); } catch (InterruptedException | ExecutionException | IOException e) { throw KubernetesClientException.launderThrowable(e); } }
private <T> T callRecurly( final AsyncHttpClient.BoundRequestBuilder builder, @Nullable final Class<T> clazz) throws IOException, ExecutionException, InterruptedException { final Response response = builder .addHeader("Authorization", "Basic " + key) .addHeader("Accept", "application/xml") .addHeader("Content-Type", "application/xml; charset=utf-8") .execute() .get(); final InputStream in = response.getResponseBodyAsStream(); try { final String payload = convertStreamToString(in); if (debug()) { log.info("Msg from Recurly API :: {}", payload); } // Handle errors payload if (response.getStatusCode() >= 300) { log.warn("Recurly error whilst calling: {}\n{}", response.getUri(), payload); if (response.getStatusCode() == 422) { final Errors errors; try { errors = xmlMapper.readValue(payload, Errors.class); } catch (Exception e) { // 422 is returned for transaction errors (see // http://docs.recurly.com/api/transactions/error-codes) // as well as bad input payloads log.debug("Unable to extract error", e); return null; } throw new TransactionErrorException(errors); } else { RecurlyAPIError recurlyError = null; try { recurlyError = xmlMapper.readValue(payload, RecurlyAPIError.class); } catch (Exception e) { log.debug("Unable to extract error", e); } throw new RecurlyAPIException(recurlyError); } } if (clazz == null) { return null; } final T obj = xmlMapper.readValue(payload, clazz); if (obj instanceof RecurlyObject) { ((RecurlyObject) obj).setRecurlyClient(this); } else if (obj instanceof RecurlyObjects) { final RecurlyObjects recurlyObjects = (RecurlyObjects) obj; recurlyObjects.setRecurlyClient(this); // Set the RecurlyClient on all objects for later use for (final Object object : recurlyObjects) { ((RecurlyObject) object).setRecurlyClient(this); } // Set the total number of records final String xRecords = response.getHeader(X_RECORDS_HEADER_NAME); if (xRecords != null) { recurlyObjects.setNbRecords(Integer.valueOf(xRecords)); } // Set links for pagination final String linkHeader = response.getHeader(LINK_HEADER_NAME); if (linkHeader != null) { final String[] links = PaginationUtils.getLinks(linkHeader); recurlyObjects.setStartUrl(links[0]); recurlyObjects.setPrevUrl(links[1]); recurlyObjects.setNextUrl(links[2]); } } return obj; } finally { closeStream(in); } }
void setPayload(AsyncHttpClient.BoundRequestBuilder requestBuilder, Payload payload) { requestBuilder.setBody(new PayloadEntityWriter(payload)); }