All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.outbrain.ob1k.http.ning.NingHttpStreamHandler Maven / Gradle / Ivy

The newest version!
package com.outbrain.ob1k.http.ning;

import static com.google.common.base.Preconditions.checkNotNull;

import com.ning.http.client.AsyncHandler;
import com.ning.http.client.HttpResponseBodyPart;
import com.ning.http.client.HttpResponseHeaders;
import com.ning.http.client.HttpResponseStatus;
import com.ning.http.client.providers.netty.response.NettyResponse;
import com.outbrain.ob1k.http.Response;
import rx.Observer;
import java.util.Collections;

/**
 * @author marenzon
 */
public class NingHttpStreamHandler implements AsyncHandler {

  private final long responseMaxSize;
  private final Observer target;
  private volatile HttpResponseHeaders headers;
  private volatile HttpResponseStatus status;
  private volatile long responseSizesAggregated;

  public NingHttpStreamHandler(final long responseMaxSize, final Observer target) {

    this.responseMaxSize = responseMaxSize;
    this.target = checkNotNull(target, "target may not be null");
  }

  @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;
  }

  @Override
  public STATE onStatusReceived(final HttpResponseStatus responseStatus) throws Exception {

    this.status = responseStatus;
    return STATE.CONTINUE;
  }

  @Override
  public STATE onHeadersReceived(final HttpResponseHeaders headers) throws Exception {

    this.headers = headers;
    return STATE.CONTINUE;
  }

  @Override
  public void onThrowable(final Throwable error) {

    target.onError(error);
  }

  @Override
  public Response onCompleted() throws Exception {

    target.onCompleted();
    return null;
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy