com.ning.http.client.RequestBuilder Java Examples

The following examples show how to use com.ning.http.client.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: NingAsyncHttpRequest.java    From junit-servers with MIT License 6 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 Uri uri = new Uri(scheme, userInfo, host, port, path, query);

	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 long start = nanoTime();
	final Response response = client.executeRequest(request).get();
	final long duration = nanoTime() - start;

	return NingAsyncHttpResponseFactory.of(response, duration);
}
 
Example #2
Source File: Zendesk.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
private Request req(String method, Uri template) {
    RequestBuilder builder = new RequestBuilder(method);
    if (realm != null) {
        builder.setRealm(realm);
    } else {
        builder.addHeader("Authorization", "Bearer " + oauthToken);
    }
    builder.setUrl(template.toString());
    return builder.build();
}
 
Example #3
Source File: Zendesk.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
private Request req(String method, Uri template, String contentType, byte[] body) {
    RequestBuilder builder = new RequestBuilder(method);
    if (realm != null) {
        builder.setRealm(realm);
    } else {
        builder.addHeader("Authorization", "Bearer " + oauthToken);
    }
    builder.setUrl(template.toString());
    builder.addHeader("Content-type", contentType);
    builder.setBody(body);
    return builder.build();
}
 
Example #4
Source File: Zendesk.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
private Request req(String method, Uri template, int page) {
    RequestBuilder builder = new RequestBuilder(method);
    if (realm != null) {
        builder.setRealm(realm);
    } else {
        builder.addHeader("Authorization", "Bearer " + oauthToken);
    }
    builder.addQueryParameter("page", Integer.toString(page));
    builder.setUrl(template.toString().replace("%2B", "+")); //replace out %2B with + due to API restriction
    return builder.build();
}
 
Example #5
Source File: NingAsyncHttpRequest.java    From junit-servers with MIT License 5 votes vote down vote up
/**
 * Add request body.
 *
 * @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 #6
Source File: AsyncHttpConnection.java    From tez with Apache License 2.0 5 votes vote down vote up
/**
 * Connect to source
 *
 * @return true if connection was successful
 * false if connection was previously cleaned up
 * @throws IOException upon connection failure
 */
public boolean connect() throws IOException, InterruptedException {
  computeEncHash();

  RequestBuilder rb = new RequestBuilder();
  rb.setHeader(SecureShuffleUtils.HTTP_HEADER_URL_HASH, encHash);
  rb.setHeader(ShuffleHeader.HTTP_HEADER_NAME, ShuffleHeader.DEFAULT_HTTP_HEADER_NAME);
  rb.setHeader(ShuffleHeader.HTTP_HEADER_VERSION, ShuffleHeader.DEFAULT_HTTP_HEADER_VERSION);
  Request request = rb.setUrl(url.toString()).build();

  //for debugging
  LOG.debug("Request url={}, encHash={}, id={}", url, encHash);

  try {
    //Blocks calling thread until it receives headers, but have the option to defer response body
    responseFuture = httpAsyncClient.executeRequest(request, handler);

    //BodyDeferringAsyncHandler would automatically manage producer and consumer frequency mismatch
    dis = new TezBodyDeferringAsyncHandler.BodyDeferringInputStream(responseFuture, handler, pis);

    response = dis.getAsapResponse();
    if (response == null) {
      throw new IOException("Response is null");
    }
  } catch(IOException e) {
    throw e;
  }

  //verify the response
  int rc = response.getStatusCode();
  if (rc != HttpURLConnection.HTTP_OK) {
    LOG.debug("Request url={}, id={}", response.getUri());
    throw new IOException("Got invalid response code " + rc + " from "
        + url + ": " + response.getStatusText());
  }
  return true;
}
 
Example #7
Source File: ParsecEqualsUtilTest.java    From parsec-libraries with Apache License 2.0 4 votes vote down vote up
@Test
public void testNingRequestEquals() throws Exception {
    Assert.assertTrue(
        ParsecEqualsUtil.ningRequestEquals(
            new RequestBuilder().setUrl("http://localhost:4080").build(),
            new RequestBuilder().setUrl("http://localhost:4080").build()
        )
    );

    Assert.assertFalse(
        ParsecEqualsUtil.ningRequestEquals(
            new RequestBuilder().setUrl("http://localhost:4080")
                .setBody(Arrays.asList(new byte[] {1,2,3}))
                .build(),
            new RequestBuilder().setUrl("http://localhost:4080")
                .build()
        )
    );

    Assert.assertFalse(
        ParsecEqualsUtil.ningRequestEquals(
            new RequestBuilder().setUrl("http://localhost:4080")
                .addBodyPart(new StringPart("abc", "def"))
                .build(),
            new RequestBuilder().setUrl("http://localhost:4080")
                .build()
        )
    );

    Assert.assertFalse(
        ParsecEqualsUtil.ningRequestEquals(
            new RequestBuilder().setUrl("http://localhost:4080")
                .setProxyServer(new ProxyServer("localhost", 8080))
                .build(),
            new RequestBuilder().setUrl("http://localhost:4080")
                .build()
        )
    );

    Assert.assertFalse(
        ParsecEqualsUtil.ningRequestEquals(
            new RequestBuilder().setUrl("http://localhost:4080")
                .build(),
            new RequestBuilder().setUrl("http://localhost:4080")
                .setBody(Arrays.asList(new byte[] {1,2,3}))
                .build()
        )
    );

    Assert.assertFalse(
        ParsecEqualsUtil.ningRequestEquals(
            new RequestBuilder().setUrl("http://localhost:4080")
                .build(),
            new RequestBuilder().setUrl("http://localhost:4080")
                .addBodyPart(new StringPart("abc", "def"))
                .build()
        )
    );

    Assert.assertFalse(
        ParsecEqualsUtil.ningRequestEquals(
            new RequestBuilder().setUrl("http://localhost:4080")
                .build(),
            new RequestBuilder().setUrl("http://localhost:4080")
                .setProxyServer(new ProxyServer("localhost", 8080))
                .build()
        )
    );
}
 
Example #8
Source File: SingularityHealthchecker.java    From Singularity with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
void asyncHealthcheck(final SingularityTask task) {
  final Optional<String> uri = getHealthcheckUri(task);
  final SingularityHealthcheckAsyncHandler handler = new SingularityHealthcheckAsyncHandler(
    exceptionNotifier,
    configuration,
    this,
    newTaskChecker,
    taskManager,
    task
  );

  if (!uri.isPresent()) {
    saveFailure(handler, "Invalid healthcheck uri or ports not present");
    return;
  }
  handler.setHealthcheckUri(uri.get());

  final Integer timeoutSeconds;
  final String method;

  if (task.getTaskRequest().getDeploy().getHealthcheck().isPresent()) {
    HealthcheckOptions options = task
      .getTaskRequest()
      .getDeploy()
      .getHealthcheck()
      .get();

    method = options.getMethod().orElse(HealthcheckMethod.GET).getMethod();
    timeoutSeconds =
      options
        .getResponseTimeoutSeconds()
        .orElse(configuration.getHealthcheckTimeoutSeconds());
  } else {
    timeoutSeconds = configuration.getHealthcheckTimeoutSeconds();
    method = HealthcheckMethod.GET.getMethod();
  }

  try {
    HealthcheckProtocol protocol = task
      .getTaskRequest()
      .getDeploy()
      .getHealthcheck()
      .get()
      .getProtocol()
      .orElse(HealthcheckProtocol.HTTP);

    LOG.trace(
      "Issuing a healthcheck ({}) for task {} with timeout {}s",
      uri.get(),
      task.getTaskId(),
      timeoutSeconds
    );

    if (
      protocol == HealthcheckProtocol.HTTP2 || protocol == HealthcheckProtocol.HTTPS2
    ) {
      // Creates a lightweight new client which shares the underlying resource pools of the original instance.
      http2
        .newBuilder()
        .retryOnConnectionFailure(false)
        .followRedirects(true)
        .connectTimeout(timeoutSeconds, TimeUnit.SECONDS)
        .readTimeout(timeoutSeconds, TimeUnit.SECONDS)
        .cache(null)
        .build()
        .newCall(
          new okhttp3.Request.Builder().method(method, null).url(uri.get()).build()
        )
        .enqueue(wrappedHttp2Handler(handler));
    } else {
      RequestBuilder builder = new RequestBuilder("GET");
      builder.setFollowRedirects(true);
      builder.setUrl(uri.get());
      builder.setRequestTimeout((int) TimeUnit.SECONDS.toMillis(timeoutSeconds));

      http.prepareRequest(builder.build()).execute(wrappedHttp1Handler(handler));
    }
  } catch (Throwable t) {
    LOG.debug(
      "Exception while preparing healthcheck ({}) for task ({})",
      uri.get(),
      task.getTaskId(),
      t
    );
    exceptionNotifier.notify(
      String.format("Error preparing healthcheck (%s)", t.getMessage()),
      t,
      ImmutableMap.of("taskId", task.getTaskId().toString())
    );
    saveFailure(
      handler,
      String.format(
        "Healthcheck (%s) failed due to exception: %s",
        uri.get(),
        t.getMessage()
      )
    );
  }
}
 
Example #9
Source File: AsyncHttpClientTest.java    From vw-webservice with BSD 3-Clause "New" or "Revised" License 3 votes vote down vote up
@Ignore
@Test
public void plainTextExamplesTest() throws IOException, InterruptedException, ExecutionException {

	RequestBuilder builder = new RequestBuilder("POST");

	//note: assumes that a vw-webservice is running on localhost at 8080.
	//modify the address accordingly if it's running on a different host/port.

	Request request = builder.setUrl("http://localhost:8080/vw-webservice-jersey/predict/main").addHeader("Content-Type", ExampleMediaTypes.PLAINTEXT_0_1_0).setBody(getPlainTextInputStreamBodyGenerator()).build();

	doTest(request);
}
 
Example #10
Source File: AsyncHttpClientTest.java    From vw-webservice with BSD 3-Clause "New" or "Revised" License 3 votes vote down vote up
@Ignore
@Test
public void structuredJsonExamplesTest() throws IOException, InterruptedException, ExecutionException {

	RequestBuilder builder = new RequestBuilder("POST");

	//note: assumes that a vw-webservice is running on localhost at 8080.
	//modify the address accordingly if it's running on a different host/port.

	Request request = builder.setUrl("http://localhost:8080/vw-webservice-jersey/predict/main").addHeader("Content-Type", ExampleMediaTypes.STRUCTURED_JSON_0_1_0).setBody(getJsonInputStreamBodyGenerator()).build();

	doTest(request);
}
 
Example #11
Source File: NingAsyncHttpRequest.java    From junit-servers with MIT License 2 votes vote down vote up
/**
 * Add query parameter to the final HTTP request.
 *
 * @param builder The pending HTTP request.
 * @see RequestBuilder#addQueryParam(String, String)
 */
private void handleQueryParameters(RequestBuilder builder) {
	for (HttpParameter p : queryParams.values()) {
		builder.addQueryParam(p.getEncodedName(), p.getEncodedValue());
	}
}
 
Example #12
Source File: NingAsyncHttpRequest.java    From junit-servers with MIT License 2 votes vote down vote up
/**
 * Add cookies to the final HTTP request.
 *
 * @param builder The pending HTTP request.
 * @see RequestBuilder#addCookie(com.ning.http.client.cookie.Cookie)
 */
private void handleCookies(RequestBuilder builder) {
	if (!cookies.isEmpty()) {
		builder.addHeader(HttpHeaders.COOKIE, Cookies.serialize(cookies));
	}
}
 
Example #13
Source File: NingAsyncHttpRequest.java    From junit-servers with MIT License 2 votes vote down vote up
/**
 * Add request headers.
 *
 * @param builder The pending HTTP request.
 * @see RequestBuilder#addHeader(String, String)
 */
private void handleHeaders(RequestBuilder builder) {
	for (HttpHeader header : headers.values()) {
		builder.setHeader(header.getName(), header.serializeValues());
	}
}