com.ning.http.client.HttpResponseBodyPart Java Examples

The following examples show how to use com.ning.http.client.HttpResponseBodyPart. 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: NingHttpTypedStreamHandler.java    From ob1k with Apache License 2.0 6 votes vote down vote up
@Override
public STATE onBodyPartReceived(final HttpResponseBodyPart bodyPart) throws Exception {

  if (responseMaxSize > 0) {
    responseSizesAggregated += bodyPart.length();
    if (responseSizesAggregated > responseMaxSize) {
      onThrowable(new RuntimeException("Response size is bigger than the limit: " + responseMaxSize));
      return STATE.ABORT;
    }
  }

  final com.ning.http.client.Response ningResponse = new NettyResponse(status, headers, singletonList(bodyPart));
  final TypedResponse<T> response = new NingResponse<>(ningResponse, type, marshallingStrategy);

  try {
    // making sure that we can unmarshall the response
    response.getTypedBody();
  } catch (final Exception e) {
    // if the unmarshall failed, no reason to continuing the stream
    onThrowable(e);
    return STATE.ABORT;
  }

  target.onNext(response);
  return STATE.CONTINUE;
}
 
Example #2
Source File: NingHttpStreamHandler.java    From ob1k with Apache License 2.0 6 votes vote down vote up
@Override
public STATE onBodyPartReceived(final HttpResponseBodyPart bodyPart) throws Exception {

  if (responseMaxSize > 0) {
    responseSizesAggregated += bodyPart.length();
    if (responseSizesAggregated > responseMaxSize) {
      onThrowable(new RuntimeException("Response size is bigger than the limit: " + responseMaxSize));
      return STATE.ABORT;
    }
  }

  final com.ning.http.client.Response ningResponse = new NettyResponse(status, headers, Collections.singletonList(bodyPart));
  final Response response = new NingResponse<>(ningResponse, null, null);

  target.onNext(response);
  return STATE.CONTINUE;
}
 
Example #3
Source File: NingHttpResponseBuilder.java    From junit-servers with MIT License 6 votes vote down vote up
@Override
public Response build() {
	Uri uri = Uri.create("http://localhost:8080/");

	AsyncHttpClientConfig config = new AsyncHttpClientConfig.Builder().build();
	AsyncHttpProvider provider = new JDKAsyncHttpProvider(config);
	HttpURLConnection conn = createFakeUrlConnection();
	HttpResponseStatus status = new ResponseStatus(uri, config, conn);
	HttpResponseHeaders headers = new ResponseHeaders(uri, conn, provider);

	final List<HttpResponseBodyPart> bodyParts;
	if (body != null) {
		byte[] bodyBytes = body.getBytes(defaultCharset());
		HttpResponseBodyPart part = new ResponseBodyPart(bodyBytes, true);
		bodyParts = singletonList(part);
	}
	else {
		bodyParts = emptyList();
	}

	return new JDKResponse(status, headers, bodyParts);
}
 
Example #4
Source File: SSEConnection.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Override
public STATE onBodyPartReceived(HttpResponseBodyPart content) throws Exception {
    // spec says the content is always UTF-8
    for (byte b : content.getBodyPartBytes()) {
        boolean isCRLF = b==0x0D || b==0x0A;
        buf.write(b);
        if (lastByteWasCRLF && isCRLF)
            dispatch();
        lastByteWasCRLF = isCRLF;
    }
    return STATE.CONTINUE;
}
 
Example #5
Source File: AsyncHttpClientPluginIT.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Override
public void transactionMarker() throws Exception {
    AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicInteger statusCode = new AtomicInteger();
    asyncHttpClient.prepareGet("http://localhost:" + getPort() + "/hello3/")
            .execute(new AsyncHandler<Response>() {
                @Override
                public STATE onBodyPartReceived(HttpResponseBodyPart part) {
                    return null;
                }
                @Override
                public Response onCompleted() throws Exception {
                    latch.countDown();
                    return null;
                }
                @Override
                public STATE onHeadersReceived(HttpResponseHeaders headers) {
                    return null;
                }
                @Override
                public STATE onStatusReceived(HttpResponseStatus status) {
                    statusCode.set(status.getStatusCode());
                    return null;
                }
                @Override
                public void onThrowable(Throwable t) {}
            });
    latch.await();
    asyncHttpClient.close();
    if (statusCode.get() != 200) {
        throw new IllegalStateException("Unexpected status code: " + statusCode);
    }
}
 
Example #6
Source File: TestServerFixture.java    From fixd with Apache License 2.0 5 votes vote down vote up
public STATE onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception {
    
    String chunk = new String(bodyPart.getBodyPartBytes()).trim();
    if (chunk.length() != 0) {
        chunks.add(chunk);
    }
    return STATE.CONTINUE;
}
 
Example #7
Source File: TezBodyDeferringAsyncHandler.java    From tez with Apache License 2.0 5 votes vote down vote up
public AsyncHandler.STATE onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception {
  // body arrived, flush headers
  if (!responseSet) {
    response = responseBuilder.build();
    responseSet = true;
    headersArrived.countDown();
  }
  bodyPart.writeTo(output);
  return AsyncHandler.STATE.CONTINUE;
}
 
Example #8
Source File: NettyAsyncHttpProvider.java    From ck with Apache License 2.0 4 votes vote down vote up
public Response prepareResponse(final HttpResponseStatus status,
                                final HttpResponseHeaders headers,
                                final Collection<HttpResponseBodyPart> bodyParts) {
	return new NettyAsyncResponse(status,headers,bodyParts);
}
 
Example #9
Source File: NettyAsyncHttpProvider.java    From ck with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private final boolean updateBodyAndInterrupt(AsyncHandler handler, HttpResponseBodyPart c) throws Exception {
	return handler.onBodyPartReceived(c) != STATE.CONTINUE;
}
 
Example #10
Source File: NingRequestBuilder.java    From ob1k with Apache License 2.0 4 votes vote down vote up
private ComposableFuture<com.ning.http.client.Response> executeAndTransformRequest() {

    try {
      prepareRequestBody();
    } catch (final IOException e) {
      return fromError(e);
    }

    final Request ningRequest = ningRequestBuilder.build();

    if (log.isTraceEnabled()) {
      final String body = ningRequest.getByteData() == null
        ? ningRequest.getStringData() :
        new String(ningRequest.getByteData(), Charset.forName(charset));

      log.trace("Sending HTTP call to {}: headers=[{}], body=[{}]", ningRequest.getUrl(), ningRequest.getHeaders(), body);
    }

    final Provider<com.ning.http.client.Response> provider = new Provider<com.ning.http.client.Response>() {
      private boolean aborted = false;
      private long size;

      @Override
      public ListenableFuture<com.ning.http.client.Response> provide() {
        return asyncHttpClient.executeRequest(ningRequest, new AsyncCompletionHandler<com.ning.http.client.Response>() {
          @Override
          public com.ning.http.client.Response onCompleted(final com.ning.http.client.Response response) throws Exception {
            if (aborted) {
              throw new RuntimeException("Response size is bigger than the limit: " + responseMaxSize);
            }
            return response;
          }

          @Override
          public STATE onBodyPartReceived(final HttpResponseBodyPart content) throws Exception {
            if (responseMaxSize > 0) {
              size += content.length();
              if (size > responseMaxSize) {
                aborted = true;
                return STATE.ABORT;
              }
            }
            return super.onBodyPartReceived(content);
          }
        });
      }
    };

    return fromListenableFuture(provider);
  }
 
Example #11
Source File: TaskResource.java    From Singularity with Apache License 2.0 4 votes vote down vote up
@Override
public STATE onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception {
  bodyPart.writeTo(wrappedOutputStream);
  wrappedOutputStream.flush();
  return STATE.CONTINUE;
}
 
Example #12
Source File: AsyncHttpClientTest.java    From vw-webservice with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void doTest(Request request) throws InterruptedException, ExecutionException, IOException {
	final PipedOutputStream pipedOutputStream = new PipedOutputStream();
	final PipedInputStream pipedInputStream = new PipedInputStream(pipedOutputStream);

	AsyncHandler<Response> asyncHandler = new AsyncHandler<Response>() {
		private final Response.ResponseBuilder builder = new Response.ResponseBuilder();

		@Override
		public STATE onBodyPartReceived(final HttpResponseBodyPart content) throws Exception {
			content.writeTo(pipedOutputStream);
			return STATE.CONTINUE;
		}

		@Override
		public STATE onStatusReceived(final HttpResponseStatus status) throws Exception {
			builder.accumulate(status);
			return STATE.CONTINUE;
		}

		@Override
		public STATE onHeadersReceived(final HttpResponseHeaders headers) throws Exception {
			builder.accumulate(headers);
			return STATE.CONTINUE;
		}

		@Override
		public Response onCompleted() throws Exception {

			LOGGER.info("On complete called!");

			pipedOutputStream.flush();
			pipedOutputStream.close();

			return builder.build();

		}

		@Override
		public void onThrowable(Throwable arg0) {
			// TODO Auto-generated method stub
			LOGGER.error("Error: {}", arg0);
			onTestFailed();
		}

	};

	Future<Void> readingThreadFuture = Executors.newCachedThreadPool().submit(new Callable<Void>() {

		@Override
		public Void call() throws Exception {
			BufferedReader reader = new BufferedReader(new InputStreamReader(pipedInputStream));

			String readPrediction;

			int numPredictionsRead = 0;

			while ((readPrediction = reader.readLine()) != null) {
				//LOGGER.info("Got prediction: {}", readPrediction);
				numPredictionsRead++;
			}

			LOGGER.info("Read a total of {} predictions", numPredictionsRead);
			Assert.assertEquals(roundsOfDataToSubmit * 272274, numPredictionsRead);

			return null;
		}
	});

	Builder config = new AsyncHttpClientConfig.Builder();

	config.setRequestTimeoutInMs(-1); //need to set this to -1, to indicate wait forever. setting to 0 actually means a 0 ms timeout!

	AsyncHttpClient client = new AsyncHttpClient(config.build());

	client.executeRequest(request, asyncHandler).get();

	readingThreadFuture.get(); //verify no exceptions occurred when reading predictions

	client.close();

	Assert.assertFalse(getTestFailed());
}
 
Example #13
Source File: LoggingAsyncHandlerWrapper.java    From parsec-libraries with Apache License 2.0 2 votes vote down vote up
/**
 * onBodyPartReceived.
 *
 * @param bodyPart body part
 * @return STATE
 * @throws Exception exception
 */
@Override
public STATE onBodyPartReceived(final HttpResponseBodyPart bodyPart) throws Exception {
    builder.accumulate(bodyPart);
    return asyncHandler.onBodyPartReceived(bodyPart);
}