org.asynchttpclient.RequestBuilder Java Examples

The following examples show how to use org.asynchttpclient.RequestBuilder. 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: AsyncHttpClientEdgeGridSignatureCalculatorTest.java    From AkamaiOPEN-edgegrid-java with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "requests")
public void testCalculateAndAddSignatureForGet(Request request) throws Exception {

    ClientCredential credential = ClientCredential.builder()
        .accessToken("akaa-dm5g2bfwoodqnc6k-ju7vlao2wz6oz2rp")
        .clientToken("akaa-k7glklzuxkkh2ycw-oadjphopvpn6yjoj")
        .clientSecret("SOMESECRET")
        .host("endpoint.net")
        .build();

    RequestBuilder requestToUpdate = new RequestBuilder(request);
    new AsyncHttpClientEdgeGridSignatureCalculator(credential).calculateAndAddSignature(
        request, requestToUpdate);
    Request updatedRequest = requestToUpdate.build();

    assertThat(updatedRequest.getHeaders().get("Authorization"), not(isEmptyOrNullString()));
    assertThat(updatedRequest.getHeaders().get("Host"), equalTo("endpoint.net"));
    assertThat(updatedRequest.getUri().getHost(), equalTo("endpoint.net"));

}
 
Example #2
Source File: AsyncHttpClientITest.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
  try (final AsyncHttpClient client = new DefaultAsyncHttpClient()) {
    final Request request = new RequestBuilder(HttpConstants.Methods.GET).setUrl("http://www.google.com").build();
    final int statusCode = client.executeRequest(request, new AsyncCompletionHandler<Response>() {
      @Override
      public Response onCompleted(final Response response) {
        TestUtil.checkActiveSpan();
        return response;
      }
    }).get(10, TimeUnit.SECONDS).getStatusCode();

    if (200 != statusCode)
      throw new AssertionError("ERROR: response: " + statusCode);

    TestUtil.checkSpan(true, new ComponentSpanCount("java-asynchttpclient", 1), new ComponentSpanCount("netty", 1));
  }
}
 
Example #3
Source File: AsyncHttpClientServiceShould.java    From mutual-tls-ssl with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void executeRequest() throws Exception {
    Response response = mock(Response.class);
    ListenableFuture<Response> listenableFuture = mock(ListenableFuture.class);

    when(httpClient.executeRequest(any(RequestBuilder.class))).thenReturn(listenableFuture);
    when(listenableFuture.toCompletableFuture()).thenReturn(CompletableFuture.completedFuture(response));

    when(response.getStatusCode()).thenReturn(200);
    when(response.getResponseBody()).thenReturn("Hello");

    ArgumentCaptor<RequestBuilder> requestBuilderArgumentCaptor = ArgumentCaptor.forClass(RequestBuilder.class);

    ClientResponse clientResponse = victim.executeRequest(HTTP_URL);

    assertThat(clientResponse.getStatusCode()).isEqualTo(200);
    assertThat(clientResponse.getResponseBody()).isEqualTo("Hello");

    verify(httpClient, times(1)).executeRequest(requestBuilderArgumentCaptor.capture());
    Request request = requestBuilderArgumentCaptor.getValue().build();
    assertThat(request.getUrl()).isEqualTo(HTTP_URL);
    assertThat(request.getMethod()).isEqualTo(GET_METHOD);
    assertThat(request.getHeaders().get(HEADER_KEY_CLIENT_TYPE)).isEqualTo(ASYNC_HTTP_CLIENT.getValue());
}
 
Example #4
Source File: FunctionsImpl.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<Void> uploadFunctionAsync(String sourceFile, String path) {
    final CompletableFuture<Void> future = new CompletableFuture<>();
    try {
        RequestBuilder builder = post(functions.path("upload").getUri().toASCIIString())
                .addBodyPart(new FilePart("data", new File(sourceFile), MediaType.APPLICATION_OCTET_STREAM))
                .addBodyPart(new StringPart("path", path, MediaType.TEXT_PLAIN));

        asyncHttpClient.executeRequest(addAuthHeaders(functions, builder).build()).toCompletableFuture()
                .thenAccept(response -> {
                    if (response.getStatusCode() < 200 || response.getStatusCode() >= 300) {
                        future.completeExceptionally(
                                getApiException(Response
                                        .status(response.getStatusCode())
                                        .entity(response.getResponseBody())
                                        .build()));
                    } else {
                        future.complete(null);
                    }
                });
    } catch (Exception e) {
        future.completeExceptionally(getApiException(e));
    }
    return future;
}
 
Example #5
Source File: AsyncHttpClientEdgeGridRequestSignerIntegrationTest.java    From AkamaiOPEN-edgegrid-java with Apache License 2.0 6 votes vote down vote up
@Test
public void signEachRequest() throws URISyntaxException, IOException, ExecutionException, InterruptedException {

    wireMockServer.stubFor(post(urlPathEqualTo("/papi/v0/properties"))
        .withHeader("Authorization", matching(".*"))
        .withHeader("Host", equalTo(SERVICE_MOCK))
        .willReturn(aResponse()
            .withStatus(201)
            .withHeader("Content-Type", "text/xml")
            .withBody("<response>Some content</response>")));

    Request request = new RequestBuilder("POST")
        .setUrl("http://" + credential.getHost() + "/papi/v0/properties")
        .addQueryParam("contractId","ctr_1-3CV382")
        .addQueryParam("groupId","grp_18385")
        .setBody("{ \"productId\": \"Site_Accel\", \"propertyName\": \"8LuWyUjwea\" }")
        .setHeader("Content-Type", "application/json")
        .setSignatureCalculator(new AsyncHttpClientEdgeGridSignatureCalculator(credential))
        .build();

    asyncHttpClient().executeRequest(request).get();

    assertThat(wireMockServer.findAllUnmatchedRequests().size(), CoreMatchers.equalTo(0));
}
 
Example #6
Source File: AsyncHttpClientEdgeGridSignatureCalculatorTest.java    From AkamaiOPEN-edgegrid-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testPreservingQueryString() throws Exception {

    ClientCredential credential = ClientCredential.builder()
        .accessToken("akaa-dm5g2bfwoodqnc6k-ju7vlao2wz6oz2rp")
        .clientToken("akaa-k7glklzuxkkh2ycw-oadjphopvpn6yjoj")
        .clientSecret("SOMESECRET")
        .host("endpoint.net")
        .build();

    Request request = new RequestBuilder().setUrl("http://localhost/test?x=y").build();
    RequestBuilder requestToUpdate = new RequestBuilder(request);

    new AsyncHttpClientEdgeGridSignatureCalculator(credential).calculateAndAddSignature(
        request, requestToUpdate);
    Request updatedRequest = requestToUpdate.build();

    assertThat(updatedRequest.getUri().getQuery(), equalTo("x=y"));

}
 
Example #7
Source File: AsyncHttpClientEdgeGridSignatureCalculatorTest.java    From AkamaiOPEN-edgegrid-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testNotDuplicatingQueryString() throws Exception {

    ClientCredential credential = ClientCredential.builder()
        .accessToken("akaa-dm5g2bfwoodqnc6k-ju7vlao2wz6oz2rp")
        .clientToken("akaa-k7glklzuxkkh2ycw-oadjphopvpn6yjoj")
        .clientSecret("SOMESECRET")
        .host("endpoint.net")
        .build();

    Request request = new RequestBuilder().setUrl("http://localhost/test").addQueryParam("x", "y").build();
    RequestBuilder requestToUpdate = new RequestBuilder(request);

    new AsyncHttpClientEdgeGridSignatureCalculator(credential).calculateAndAddSignature(
        request, requestToUpdate);
    Request updatedRequest = requestToUpdate.build();

    assertThat(updatedRequest.getUri().getQuery(), equalTo("x=y"));

}
 
Example #8
Source File: QuerySchool.java    From schedge with MIT License 6 votes vote down vote up
public static String querySchool(Term term) {
  logger.info("querying school for term={}", term);

  Request request =
      new RequestBuilder().setUri(ROOT_URI).setRequestTimeout(60000).build();

  try {
    return GetClient.getClient()
        .executeRequest(request)
        .get()
        .getResponseBody();
  } catch (InterruptedException | ExecutionException e) {
    logger.error("Error (term=" + term + "): " + e.getMessage());
    return null;
  }
}
 
Example #9
Source File: GetRatings.java    From schedge with MIT License 6 votes vote down vote up
/**
 * Given at instructor, will find the coresponding
 * rmp-id for the instructor.
 * @param instructor
 * @return
 */
private static Future<Instructor> getLinkAsync(Instructor instructor) {
  String param = parseInstructorName(instructor.name);
  Request request = new RequestBuilder()
                        .setUri(Uri.create(RMP_URL + param))
                        .setRequestTimeout(60000)
                        .setMethod("GET")
                        .build();
  return GetClient.getClient()
      .executeRequest(request)
      .toCompletableFuture()
      .handleAsync((resp, throwable) -> {
        if (resp == null) {
          logger.error(throwable.getMessage());
          return null;
        }
        String link = parseLink(resp.getResponseBody());
        if (link == null)
          logger.warn("Instructor query " + instructor.name +
                      " returned no results.");
        return new Instructor(instructor.id, link);
      });
}
 
Example #10
Source File: GetRatings.java    From schedge with MIT License 6 votes vote down vote up
/**
 * Given the rmp-id, we get the rating.
 * Rating can be either a float or N/A, in the case of N/A, we return 0.0
 * @param url
 * @param id
 * @return
 */
private static Future<Rating> queryRatingAsync(String url, int id) {
  Request request = new RequestBuilder()
                        .setUri(Uri.create(RMP_ROOT_URL + url))
                        .setRequestTimeout(60000)
                        .setMethod("GET")
                        .build();

  return GetClient.getClient()
      .executeRequest(request)
      .toCompletableFuture()
      .handleAsync((resp, throwable) -> {
        if (resp == null) {
          logger.error(throwable.getMessage());
          return null;
        }
        if (url == null) {
          logger.warn("URL is null for id=" + id);
          return new Rating(id, -1, -1.0f);
        }

        return new Rating(id, Integer.parseInt(url),
                          parseRating(resp.getResponseBody()));
      });
}
 
Example #11
Source File: FunctionsImpl.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<Void> updateFunctionAsync(
        FunctionConfig functionConfig, String fileName, UpdateOptions updateOptions) {
    final CompletableFuture<Void> future = new CompletableFuture<>();
    try {
        RequestBuilder builder =
                put(functions.path(functionConfig.getTenant())
                        .path(functionConfig.getNamespace())
                        .path(functionConfig.getName()).getUri().toASCIIString())
                .addBodyPart(new StringPart("functionConfig", ObjectMapperFactory.getThreadLocal()
                        .writeValueAsString(functionConfig), MediaType.APPLICATION_JSON));

        if (updateOptions != null) {
            builder.addBodyPart(new StringPart("updateOptions", ObjectMapperFactory.getThreadLocal()
                    .writeValueAsString(updateOptions), MediaType.APPLICATION_JSON));
        }

        if (fileName != null && !fileName.startsWith("builtin://")) {
            // If the function code is built in, we don't need to submit here
            builder.addBodyPart(new FilePart("data", new File(fileName), MediaType.APPLICATION_OCTET_STREAM));
        }

        asyncHttpClient.executeRequest(addAuthHeaders(functions, builder).build())
                .toCompletableFuture()
                .thenAccept(response -> {
                    if (response.getStatusCode() < 200 || response.getStatusCode() >= 300) {
                        future.completeExceptionally(
                                getApiException(Response
                                        .status(response.getStatusCode())
                                        .entity(response.getResponseBody())
                                        .build()));
                    } else {
                        future.complete(null);
                    }
                });
    } catch (Exception e) {
        future.completeExceptionally(getApiException(e));
    }
    return future;
}
 
Example #12
Source File: FunctionsImpl.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<Void> createFunctionAsync(FunctionConfig functionConfig, String fileName) {
    final CompletableFuture<Void> future = new CompletableFuture<>();
    try {
        RequestBuilder builder =
                post(functions.path(functionConfig.getTenant()).path(functionConfig.getNamespace())
                        .path(functionConfig.getName()).getUri().toASCIIString())
                .addBodyPart(new StringPart("functionConfig", ObjectMapperFactory.getThreadLocal()
                        .writeValueAsString(functionConfig), MediaType.APPLICATION_JSON));

        if (fileName != null && !fileName.startsWith("builtin://")) {
            // If the function code is built in, we don't need to submit here
            builder.addBodyPart(new FilePart("data", new File(fileName), MediaType.APPLICATION_OCTET_STREAM));
        }
        asyncHttpClient.executeRequest(addAuthHeaders(functions, builder).build())
                .toCompletableFuture()
                .thenAccept(response -> {
                    if (response.getStatusCode() < 200 || response.getStatusCode() >= 300) {
                        future.completeExceptionally(
                                getApiException(Response
                                        .status(response.getStatusCode())
                                        .entity(response.getResponseBody())
                                        .build()));
                    } else {
                        future.complete(null);
                    }
                });

    } catch (Exception e) {
        future.completeExceptionally(e);
    }
    return future;
}
 
Example #13
Source File: Zendesk.java    From zendesk-java-client with Apache License 2.0 5 votes vote down vote up
private RequestBuilder reqBuilder(String method, String url) {
    RequestBuilder builder = new RequestBuilder(method);
    if (realm != null) {
        builder.setRealm(realm);
    } else {
        builder.addHeader("Authorization", "Bearer " + oauthToken);
    }
    headers.forEach(builder::setHeader);
    return builder.setUrl(RESTRICTED_PATTERN.matcher(url).replaceAll("+")); // replace out %2B with + due to API restriction
}
 
Example #14
Source File: FunctionsImpl.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<Void> putFunctionStateAsync(
        String tenant, String namespace, String function, FunctionState state) {
    final CompletableFuture<Void> future = new CompletableFuture<>();
    try {
        RequestBuilder builder =
                post(functions.path(tenant).path(namespace).path(function)
                        .path("state").path(state.getKey()).getUri().toASCIIString());
        builder.addBodyPart(new StringPart("state", ObjectMapperFactory.getThreadLocal()
                .writeValueAsString(state), MediaType.APPLICATION_JSON));
        asyncHttpClient.executeRequest(addAuthHeaders(functions, builder).build())
                .toCompletableFuture()
                .thenAccept(response -> {
                    if (response.getStatusCode() < 200 || response.getStatusCode() >= 300) {
                        future.completeExceptionally(getApiException(
                                Response.status(response.getStatusCode())
                                        .entity(response.getResponseBody()).build()));
                    } else {
                        future.complete(null);
                    }
                });

    } catch (Exception e) {
        future.completeExceptionally(e);
    }
    return future;
}
 
Example #15
Source File: FunctionsImpl.java    From pulsar with Apache License 2.0 5 votes vote down vote up
public CompletableFuture<Void> updateOnWorkerLeaderAsync(String tenant, String namespace,
                                                         String function, byte[] functionMetaData,
                                                         boolean delete) {
    final CompletableFuture<Void> future = new CompletableFuture<>();
    try {
        RequestBuilder builder =
                put(functions.path("leader").path(tenant).path(namespace)
                        .path(function).getUri().toASCIIString())
                        .addBodyPart(new ByteArrayPart("functionMetaData", functionMetaData))
                .addBodyPart(new StringPart("delete", Boolean.toString(delete)));

        asyncHttpClient.executeRequest(addAuthHeaders(functions, builder).build())
                .toCompletableFuture()
                .thenAccept(response -> {
                    if (response.getStatusCode() < 200 || response.getStatusCode() >= 300) {
                        future.completeExceptionally(
                                getApiException(Response
                                        .status(response.getStatusCode())
                                        .entity(response.getResponseBody())
                                        .build()));
                    } else {
                        future.complete(null);
                    }
                });

    } catch (Exception e) {
        future.completeExceptionally(e);
    }
    return future;
}
 
Example #16
Source File: ComponentResource.java    From pulsar with Apache License 2.0 5 votes vote down vote up
public RequestBuilder addAuthHeaders(WebTarget target, RequestBuilder requestBuilder) throws PulsarAdminException {

        try {
            if (auth != null) {
                Set<Entry<String, String>> headers = getAuthHeaders(target);
                if (headers != null && !headers.isEmpty()) {
                    headers.forEach(header -> requestBuilder.addHeader(header.getKey(), header.getValue()));
                }
            }
            return requestBuilder;
        } catch (Throwable t) {
            throw new PulsarAdminException.GettingAuthenticationDataException(t);
        }
    }
 
Example #17
Source File: SourcesImpl.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<Void> createSourceAsync(SourceConfig sourceConfig, String fileName) {
    final CompletableFuture<Void> future = new CompletableFuture<>();
    try {
        RequestBuilder builder =
                post(source.path(sourceConfig.getTenant())
                        .path(sourceConfig.getNamespace()).path(sourceConfig.getName()).getUri().toASCIIString())
                .addBodyPart(new StringPart("sourceConfig", ObjectMapperFactory.getThreadLocal()
                        .writeValueAsString(sourceConfig), MediaType.APPLICATION_JSON));

        if (fileName != null && !fileName.startsWith("builtin://")) {
            // If the function code is built in, we don't need to submit here
            builder.addBodyPart(new FilePart("data", new File(fileName), MediaType.APPLICATION_OCTET_STREAM));
        }
        asyncHttpClient.executeRequest(addAuthHeaders(source, builder).build())
                .toCompletableFuture()
                .thenAccept(response -> {
                    if (response.getStatusCode() < 200 || response.getStatusCode() >= 300) {
                        future.completeExceptionally(
                                getApiException(Response
                                        .status(response.getStatusCode())
                                        .entity(response.getResponseBody()).build()));
                    } else {
                        future.complete(null);
                    }
                });
    } catch (Exception e) {
        future.completeExceptionally(getApiException(e));
    }
    return future;
}
 
Example #18
Source File: SourcesImpl.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<Void> updateSourceAsync(
        SourceConfig sourceConfig, String fileName, UpdateOptions updateOptions) {
    final CompletableFuture<Void> future = new CompletableFuture<>();
    try {
        RequestBuilder builder =
                put(source.path(sourceConfig.getTenant()).path(sourceConfig.getNamespace())
                        .path(sourceConfig.getName()).getUri().toASCIIString())
                .addBodyPart(new StringPart("sourceConfig", ObjectMapperFactory.getThreadLocal()
                        .writeValueAsString(sourceConfig), MediaType.APPLICATION_JSON));

        if (updateOptions != null) {
            builder.addBodyPart(new StringPart("updateOptions",
                    ObjectMapperFactory.getThreadLocal().writeValueAsString(updateOptions),
                    MediaType.APPLICATION_JSON));
        }

        if (fileName != null && !fileName.startsWith("builtin://")) {
            // If the function code is built in, we don't need to submit here
            builder.addBodyPart(new FilePart("data", new File(fileName), MediaType.APPLICATION_OCTET_STREAM));
        }
        asyncHttpClient.executeRequest(addAuthHeaders(source, builder).build())
                .toCompletableFuture()
                .thenAccept(response -> {
                    if (response.getStatusCode() < 200 || response.getStatusCode() >= 300) {
                        future.completeExceptionally(
                                getApiException(Response
                                        .status(response.getStatusCode())
                                        .entity(response.getResponseBody()).build()));
                    } else {
                        future.complete(null);
                    }
                });
    } catch (Exception e) {
        future.completeExceptionally(getApiException(e));
    }
    return future;
}
 
Example #19
Source File: SinksImpl.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<Void> createSinkAsync(SinkConfig sinkConfig, String fileName) {
    final CompletableFuture<Void> future = new CompletableFuture<>();
    try {
        RequestBuilder builder =
                post(sink.path(sinkConfig.getTenant())
                        .path(sinkConfig.getNamespace()).path(sinkConfig.getName()).getUri().toASCIIString())
                .addBodyPart(new StringPart("sinkConfig", ObjectMapperFactory.getThreadLocal()
                        .writeValueAsString(sinkConfig), MediaType.APPLICATION_JSON));

        if (fileName != null && !fileName.startsWith("builtin://")) {
            // If the function code is built in, we don't need to submit here
            builder.addBodyPart(new FilePart("data", new File(fileName), MediaType.APPLICATION_OCTET_STREAM));
        }
        asyncHttpClient.executeRequest(addAuthHeaders(sink, builder).build())
                .toCompletableFuture()
                .thenAccept(response -> {
                    if (response.getStatusCode() < 200 || response.getStatusCode() >= 300) {
                        future.completeExceptionally(
                                getApiException(Response
                                        .status(response.getStatusCode())
                                        .entity(response.getResponseBody()).build()));
                    } else {
                        future.complete(null);
                    }
                });
    } catch (Exception e) {
        future.completeExceptionally(getApiException(e));
    }
    return future;
}
 
Example #20
Source File: SinksImpl.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<Void> updateSinkAsync(
        SinkConfig sinkConfig, String fileName, UpdateOptions updateOptions) {
    final CompletableFuture<Void> future = new CompletableFuture<>();
    try {
        RequestBuilder builder =
                put(sink.path(sinkConfig.getTenant()).path(sinkConfig.getNamespace())
                        .path(sinkConfig.getName()).getUri().toASCIIString())
                .addBodyPart(new StringPart("sinkConfig", ObjectMapperFactory.getThreadLocal()
                        .writeValueAsString(sinkConfig), MediaType.APPLICATION_JSON));

        if (updateOptions != null) {
            builder.addBodyPart(new StringPart("updateOptions",
                    ObjectMapperFactory.getThreadLocal()
                            .writeValueAsString(updateOptions), MediaType.APPLICATION_JSON));
        }

        if (fileName != null && !fileName.startsWith("builtin://")) {
            // If the function code is built in, we don't need to submit here
            builder.addBodyPart(new FilePart("data", new File(fileName), MediaType.APPLICATION_OCTET_STREAM));
        }
        asyncHttpClient.executeRequest(addAuthHeaders(sink, builder).build())
                .toCompletableFuture()
                .thenAccept(response -> {
                    if (response.getStatusCode() < 200 || response.getStatusCode() >= 300) {
                        future.completeExceptionally(
                                getApiException(Response
                                        .status(response.getStatusCode())
                                        .entity(response.getResponseBody()).build()));
                    } else {
                        future.complete(null);
                    }
                });
    } catch (Exception e) {
        future.completeExceptionally(getApiException(e));
    }
    return future;
}
 
Example #21
Source File: AsyncHttpRequest.java    From junit-servers with MIT License 5 votes vote down vote up
@Override
protected HttpResponse doExecute() throws Exception {
	final HttpUrl endpoint = getEndpoint();
	final String scheme = endpoint.getScheme();
	final String userInfo = null;
	final String host = endpoint.getHost();
	final int port = endpoint.getPort();
	final String path = Utf8UrlEncoder.encodePath(endpoint.getPath());
	final String query = null;
	final String fragment = null;
	final Uri uri = new Uri(scheme, userInfo, host, port, path, query, fragment);

	final String method = getMethod().getVerb();
	final RequestBuilder builder = new RequestBuilder(method, true).setUri(uri);

	handleQueryParameters(builder);
	handleBody(builder);
	handleHeaders(builder);
	handleCookies(builder);

	final Request request = builder.build();
	final ListenableFuture<Response> future = client.executeRequest(request);

	final long start = nanoTime();
	final Response response = future.get();
	final long duration = nanoTime() - start;

	return AsyncHttpResponseFactory.of(response, duration);
}
 
Example #22
Source File: AsyncHttpRequest.java    From junit-servers with MIT License 5 votes vote down vote up
/**
 * Add body entity to the final HTTP request.
 *
 * @param builder The pending HTTP request.
 * @see RequestBuilder#addFormParam(String, String)
 * @see RequestBuilder#setBody(String)
 */
private void handleBody(RequestBuilder builder) throws IOException {
	if (!hasBody()) {
		log.debug("HTTP Request does not have body, skip.");
		return;
	}

	log.debug("Set body to current request builder using: {}", body);
	builder.setBody(body.getBody());

	if (body.getContentType() != null) {
		builder.setHeader("Content-Type", body.getContentType());
	}
}
 
Example #23
Source File: AsyncHttpClientEdgeGridSignatureCalculatorTest.java    From AkamaiOPEN-edgegrid-java with Apache License 2.0 5 votes vote down vote up
@DataProvider
public Object[][] requests() {
    return new Object[][]{
        {new RequestBuilder().setUrl("http://localhost/test").build()},
        {new RequestBuilder("POST").setUrl("http://localhost/test").setBody("content").build()},
        {new RequestBuilder("POST").setUrl("http://localhost/test").setBody("content".getBytes()).build()},
        {new RequestBuilder("POST").setUrl("http://localhost/test").setBody(Arrays.asList("content".getBytes())).build()}
    };
}
 
Example #24
Source File: Zendesk.java    From zendesk-java-client with Apache License 2.0 5 votes vote down vote up
public ArticleAttachments createUploadArticle(long articleId, File file, boolean inline) throws IOException {
RequestBuilder builder = reqBuilder("POST", tmpl("/help_center/articles/{id}/attachments.json").set("id", articleId).toString());
    builder.setHeader("Content-Type", "multipart/form-data");

    if (inline)
        builder.addBodyPart(new StringPart("inline", "true"));

  builder.addBodyPart(
        new FilePart("file", file, "application/octet-stream", StandardCharsets.UTF_8, file.getName()));
    final Request req = builder.build();
    return complete(submit(req, handle(ArticleAttachments.class, "article_attachment")));
}
 
Example #25
Source File: AzureAsyncContainerProvider.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Override
public boolean doesContainerExists(final String containerName) {
  // API: https://docs.microsoft.com/en-gb/rest/api/storageservices/datalakestoragegen2/filesystem/getproperties
  logger.debug("Checking for missing azure container " + account + ":" + containerName);
  final Request req = new RequestBuilder(HttpConstants.Methods.HEAD)
    .addHeader("x-ms-date", toHttpDateFormat(System.currentTimeMillis()))
    .addHeader("x-ms-version", XMS_VERSION)
    .addHeader("Content-Length", 0)
    .addHeader("x-ms-client-request-id", UUID.randomUUID().toString())
    .setUrl(AzureAsyncHttpClientUtils.getBaseEndpointURL(account, true) + "/" + containerName)
    .addQueryParam("resource", "filesystem")
    .addQueryParam("timeout", String.valueOf(requestTimeoutSeconds)).build();

  req.getHeaders().add("Authorization", authProvider.getAuthzHeaderValue(req));
  final AtomicBoolean containerExists = new AtomicBoolean(false);
  retryer.call(() -> {
    int status = asyncHttpClient.executeRequest(req).get().getStatusCode();
    if (status != 200 && status != 404) {
      logger.error("Error while checking for azure container " + account + ":" + containerName + " status code " + status);
      throw new RuntimeException(String.format("Error response %d while checking for existence of container %s", status, containerName));
    }
    if (status == 200) {
      logger.debug("Azure container is found valid " + account + ":" + containerName);
      containerExists.set(true);
    }
    return true;
  });

  return containerExists.get();
}
 
Example #26
Source File: AddToCart.java    From schedge with MIT License 5 votes vote down vote up
public static Future<Void> addRelated(Term term, String form,
                                      Integer registrationNumber,
                                      Context.HttpContext context) {

  /**
   * Make the request given session token and shopping cart
   * "https://m.albert.nyu.edu/app/student/enrollmentcart/addToCart/NYUNV/UGRD/1204/7669";
   */
  System.out.println(ADD_RELATED_ROOT_URL_STRING + term.getId() + "/" +
                     registrationNumber);
  Request sectionRequest =
      new RequestBuilder()
          .setUri(Uri.create(ADD_RELATED_DATA_URL_STRING))
          .setRequestTimeout(60000)
          .setHeader("Referer", ADD_RELATED_ROOT_URL_STRING + term.getId() +
                                    "/" + registrationNumber)
          .setHeader("Host", "m.albert.nyu.edu")
          .setHeader("Accept-Language", "en-US,en;q=0.5")
          .setHeader("Accept-Encoding", "gzip, deflate, br")
          .setHeader("Content-Type",
                     "application/x-www-form-urlencoded; charset=UTF-8")
          .setHeader("X-Requested-With", "XMLHttpRequest")
          .setHeader("Origin", "https://m.albert.nyu.edu")
          .setHeader("DNT", "1")
          .setHeader("Connection", "keep-alive")
          .setHeader("Cookie", context.cookies.stream()
                                   .map(it -> it.name() + '=' + it.value())
                                   .collect(Collectors.joining("; ")))
          .setMethod("POST")
          .setBody(form)
          .build();

  GetClient.getClient()
      .executeRequest(sectionRequest)
      .toCompletableFuture()
      .handleAsync(((resp, throwable) -> { return null; }));
  return null;
}
 
Example #27
Source File: AddToCart.java    From schedge with MIT License 5 votes vote down vote up
/**
 * Currently only work for Fall 2020. Fix later
 */
public static Future<String> addOptions(Term term, String form,
                                        Integer registrationNumber,
                                        Context.HttpContext context) {

  /**
   * Make the request given session token and shopping cart
   * "https://m.albert.nyu.edu/app/student/enrollmentcart/addToCart/NYUNV/UGRD/1204/7669";
   */
  Request optionRequest =
      new RequestBuilder()
          .setUri(ADD_OPTIONS_URI)
          .setRequestTimeout(60000)
          .setHeader("Referer", SELECT_OPTIONS_ROOT_URL_STRING +
                                    term.getId() + "/" + registrationNumber +
                                    "/add")
          .setHeader("Host", "m.albert.nyu.edu")
          .setHeader("Accept-Language", "en-US,en;q=0.9,vi;q=0.8")
          .setHeader("Accept-Encoding", "gzip, deflate, br")
          .setHeader("Content-Type", "application/x-www-form-urlencoded")
          .setHeader("cache-Control", "no-cache")
          .setHeader("Sec-Fetch-Dest", "document")
          .setHeader("Sec-Fetch-Mode", "navigate")
          .setHeader("Sec-Fetch-Size", "same-origin")
          .setHeader("Origin", "https://m.albert.nyu.edu")
          .setHeader("DNT", "1")
          .setHeader("Connection", "keep-alive")
          .setHeader("Cookie", context.cookies.stream()
                                   .map(it -> it.name() + '=' + it.value())
                                   .collect(Collectors.joining("; ")))
          .setMethod("POST")
          .setBody(form)
          .build();
  GetClient.getClient()
      .executeRequest(optionRequest)
      .toCompletableFuture()
      .handleAsync(((resp, throwable) -> { return null; }));
  return null;
}
 
Example #28
Source File: AsyncHttpClientService.java    From mutual-tls-ssl with Apache License 2.0 5 votes vote down vote up
@Override
public ClientResponse executeRequest(String url) throws Exception {
    RequestBuilder requestBuilder = new RequestBuilder()
            .setUrl(url)
            .setHeader(HEADER_KEY_CLIENT_TYPE, getClientType().getValue());

    Response response = httpClient.executeRequest(requestBuilder)
            .toCompletableFuture()
            .get(TIMEOUT_AMOUNT_IN_SECONDS, TimeUnit.SECONDS);

    return new ClientResponse(response.getResponseBody(), response.getStatusCode());
}
 
Example #29
Source File: AsyncHttpClientTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoHandler(final MockTracer tracer) throws IOException {
  try (final AsyncHttpClient client = new DefaultAsyncHttpClient()) {
    final Request request = new RequestBuilder(HttpConstants.Methods.GET).setUrl("http://localhost:12345").build();
    try {
      client.executeRequest(request).get(10, TimeUnit.SECONDS);
    }
    catch (final Exception ignore) {
    }
  }

  await().atMost(15, TimeUnit.SECONDS).until(TestUtil.reportedSpansSize(tracer), equalTo(1));
  assertEquals(1, tracer.finishedSpans().size());
  assertNull(tracer.activeSpan());
}
 
Example #30
Source File: AsyncHttpClientTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithHandler(final MockTracer tracer) throws IOException {
  final AtomicInteger counter = new AtomicInteger();
  try (final AsyncHttpClient client = new DefaultAsyncHttpClient()) {
    final Request request = new RequestBuilder(HttpConstants.Methods.GET).setUrl("http://localhost:12345").build();
    try {
      client.executeRequest(request, new AsyncCompletionHandler<Object>() {
        @Override
        public Object onCompleted(final Response response) {
          assertNotNull(tracer.activeSpan());
          counter.incrementAndGet();
          return response;
        }

        @Override
        public void onThrowable(final Throwable t) {
          assertNotNull(tracer.activeSpan());
          counter.incrementAndGet();
        }
      }).get(10, TimeUnit.SECONDS);
    }
    catch (final Exception ignore) {
    }
  }

  await().atMost(15, TimeUnit.SECONDS).until(TestUtil.reportedSpansSize(tracer), equalTo(1));
  assertEquals(1, tracer.finishedSpans().size());
  assertEquals(1, counter.get());
  assertNull(tracer.activeSpan());
}