org.apache.http.impl.DefaultHttpResponseFactory Java Examples

The following examples show how to use org.apache.http.impl.DefaultHttpResponseFactory. 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: HttpServerConnectionUpnpStream.java    From TVRemoteIME with GNU General Public License v2.0 6 votes vote down vote up
protected HttpServerConnectionUpnpStream(ProtocolFactory protocolFactory,
                                         HttpServerConnection connection,
                                         final HttpParams params) {
    super(protocolFactory);
    this.connection = connection;
    this.params = params;

    // The Date header is recommended in UDA, need to document the requirement in StreamServer interface?
    httpProcessor.addInterceptor(new ResponseDate());

    // The Server header is only required for Control so callers have to add it to UPnPMessage
    // httpProcessor.addInterceptor(new ResponseServer());

    httpProcessor.addInterceptor(new ResponseContent());
    httpProcessor.addInterceptor(new ResponseConnControl());

    httpService =
            new UpnpHttpService(
                    httpProcessor,
                    new DefaultConnectionReuseStrategy(),
                    new DefaultHttpResponseFactory()
            );
    httpService.setParams(params);
}
 
Example #2
Source File: HttpServerConnectionUpnpStream.java    From DroidDLNA with GNU General Public License v3.0 6 votes vote down vote up
protected HttpServerConnectionUpnpStream(ProtocolFactory protocolFactory,
                                         HttpServerConnection connection,
                                         final HttpParams params) {
    super(protocolFactory);
    this.connection = connection;
    this.params = params;

    // The Date header is recommended in UDA, need to document the requirement in StreamServer interface?
    httpProcessor.addInterceptor(new ResponseDate());

    // The Server header is only required for Control so callers have to add it to UPnPMessage
    // httpProcessor.addInterceptor(new ResponseServer());

    httpProcessor.addInterceptor(new ResponseContent());
    httpProcessor.addInterceptor(new ResponseConnControl());

    httpService =
            new UpnpHttpService(
                    httpProcessor,
                    new DefaultConnectionReuseStrategy(),
                    new DefaultHttpResponseFactory()
            );
    httpService.setParams(params);
}
 
Example #3
Source File: BintrayImpl.java    From bintray-client-java with Apache License 2.0 6 votes vote down vote up
public HttpResponse put(Map<String, InputStream> uriAndStreamMap, Map<String, String> headers) throws MultipleBintrayCallException {
    List<Future<String>> executions = new ArrayList<>();
    List<BintrayCallException> errors = new ArrayList<>();
    List<RequestRunner> runners = createPutRequestRunners(uriAndStreamMap, headers, errors);
    try {
        executions = executorService.invokeAll(runners);
    } catch (InterruptedException e) {
        BintrayCallException bce = new BintrayCallException(409, e.getMessage(), (e.getCause() == null) ? ""
                : e.getCause().toString() + " : " + e.getCause().getMessage());
        log.error(bce.toString());
        log.debug("{}", e.getMessage(), e);
        errors.add(bce);
    }
    collectResults(executions, errors);

    //Return ok or throw errors
    if (errors.isEmpty()) {
        String entity = "Operation Successful";
        HttpResponse response = DefaultHttpResponseFactory.INSTANCE.newHttpResponse(
                new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_CREATED, new HttpClientContext());
        response.setEntity(new StringEntity(entity, Charset.forName("UTF-8")));
        return response;
    } else {
        throw new MultipleBintrayCallException(errors);
    }
}
 
Example #4
Source File: ApiServer.java    From cosmic with Apache License 2.0 5 votes vote down vote up
public ListenerThread(final ApiServer requestHandler, final int port) {
    try {
        _serverSocket = new ServerSocket(port);
    } catch (final IOException ioex) {
        s_logger.error("error initializing api server", ioex);
        return;
    }

    _params = new BasicHttpParams();
    _params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000)
           .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
           .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
           .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
           .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");

    // Set up the HTTP protocol processor
    final BasicHttpProcessor httpproc = new BasicHttpProcessor();
    httpproc.addInterceptor(new ResponseDate());
    httpproc.addInterceptor(new ResponseServer());
    httpproc.addInterceptor(new ResponseContent());
    httpproc.addInterceptor(new ResponseConnControl());

    // Set up request handlers
    final HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
    reqistry.register("*", requestHandler);

    // Set up the HTTP service
    _httpService = new HttpService(httpproc, new NoConnectionReuseStrategy(), new DefaultHttpResponseFactory());
    _httpService.setParams(_params);
    _httpService.setHandlerResolver(reqistry);
}
 
Example #5
Source File: ClusterServiceServletContainer.java    From cosmic with Apache License 2.0 5 votes vote down vote up
public ListenerThread(final HttpRequestHandler requestHandler, final int port) {
    _executor = Executors.newCachedThreadPool(new NamedThreadFactory("Cluster-Listener"));

    try {
        _serverSocket = new ServerSocket(port);
    } catch (final IOException ioex) {
        s_logger.error("error initializing cluster service servlet container", ioex);
        return;
    }

    _params = new BasicHttpParams();
    _params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
           .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
           .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
           .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
           .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");

    // Set up the HTTP protocol processor
    final BasicHttpProcessor httpproc = new BasicHttpProcessor();
    httpproc.addInterceptor(new ResponseDate());
    httpproc.addInterceptor(new ResponseServer());
    httpproc.addInterceptor(new ResponseContent());
    httpproc.addInterceptor(new ResponseConnControl());

    // Set up request handlers
    final HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
    reqistry.register("/clusterservice", requestHandler);

    // Set up the HTTP service
    _httpService = new HttpService(httpproc, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory());
    _httpService.setParams(_params);
    _httpService.setHandlerResolver(reqistry);
}
 
Example #6
Source File: ExtendedHttpClientBuilder.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
private static ManagedHttpClientConnectionFactory createConnectionFactory() {
  return new ManagedHttpClientConnectionFactory(null, (buffer, constraints) ->
      new GarbageAllergicHttpResponseParser(
          buffer,
          IcyHttpLineParser.ICY_INSTANCE,
          DefaultHttpResponseFactory.INSTANCE,
          constraints
      ));
}
 
Example #7
Source File: AsyncRequestWrapperTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private AsyncRequestWrapperImpl createAsyncRequestWrapperImplWithRetryAfter(int retryAfter)
    throws IOException, URISyntaxException {

  HttpClient httpClient = mock(HttpClient.class);
  ODataClient oDataClient = mock(ODataClient.class);
  Configuration configuration = mock(Configuration.class);
  HttpClientFactory httpClientFactory = mock(HttpClientFactory.class);
  HttpUriRequestFactory httpUriRequestFactory = mock(HttpUriRequestFactory.class);
  HttpUriRequest httpUriRequest = mock(HttpUriRequest.class);

  when(oDataClient.getConfiguration()).thenReturn(configuration);
  when(configuration.getHttpClientFactory()).thenReturn(httpClientFactory);
  when(configuration.getHttpUriRequestFactory()).thenReturn(httpUriRequestFactory);
  when(httpClientFactory.create(any(), any())).thenReturn(httpClient);
  when(httpUriRequestFactory.create(any(), any())).thenReturn(httpUriRequest);

  HttpResponseFactory factory = new DefaultHttpResponseFactory();
  HttpResponse firstResponse = factory.newHttpResponse(
      new BasicStatusLine(HttpVersion.HTTP_1_1, 202, null), null);
  firstResponse.addHeader(HttpHeader.LOCATION, "http://localhost/monitor");
  firstResponse.addHeader(HttpHeader.RETRY_AFTER, String.valueOf(retryAfter));
  when(httpClient.execute(any(HttpUriRequest.class))).thenReturn(firstResponse);

  AbstractODataRequest oDataRequest = mock(AbstractODataRequest.class);
  ODataResponse oDataResponse = mock(ODataResponse.class);
  when(oDataRequest.getResponseTemplate()).thenReturn(oDataResponse);
  when(oDataRequest.getURI()).thenReturn(new URI("http://localhost/path"));
  when(oDataResponse.initFromHttpResponse(any(HttpResponse.class))).thenReturn(null);

  return new AsyncRequestWrapperImpl(oDataClient, oDataRequest);
}
 
Example #8
Source File: AsyncRequestWrapperTest.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
private AsyncResponseWrapperImpl createAsyncRequestWrapperImplWithLocation(String target, String location)
    throws IOException, URISyntaxException {

  HttpClient httpClient = mock(HttpClient.class);
  ODataClient oDataClient = mock(ODataClient.class);
  Configuration configuration = mock(Configuration.class);
  HttpClientFactory httpClientFactory = mock(HttpClientFactory.class);
  HttpUriRequestFactory httpUriRequestFactory = mock(HttpUriRequestFactory.class);
  HttpUriRequest httpUriRequest = mock(HttpUriRequest.class);

  when(oDataClient.getConfiguration()).thenReturn(configuration);
  when(configuration.getHttpClientFactory()).thenReturn(httpClientFactory);
  when(configuration.getHttpUriRequestFactory()).thenReturn(httpUriRequestFactory);
  when(httpClientFactory.create(any(), any())).thenReturn(httpClient);
  when(httpUriRequestFactory.create(any(), any())).thenReturn(httpUriRequest);

  HttpResponseFactory factory = new DefaultHttpResponseFactory();
  HttpResponse firstResponse = factory.newHttpResponse(
      new BasicStatusLine(HttpVersion.HTTP_1_1, 202, null), null);
  firstResponse.addHeader(HttpHeader.LOCATION, location);
  when(httpClient.execute(any(HttpUriRequest.class))).thenReturn(firstResponse);

  ODataResponse oDataResponse = mock(ODataResponse.class);
  when(oDataResponse.initFromHttpResponse(any(HttpResponse.class))).thenReturn(null);

  AbstractODataRequest oDataRequest = mock(AbstractODataRequest.class);
  when(oDataRequest.getURI()).thenReturn(new URI(target));
  when(oDataRequest.getResponseTemplate()).thenReturn(oDataResponse);

  AsyncRequestWrapperImpl req = new AsyncRequestWrapperImpl(oDataClient, oDataRequest);
  AsyncResponseWrapper wrappedResponse = req.execute();
  assertTrue(wrappedResponse instanceof AsyncResponseWrapperImpl);
  return (AsyncResponseWrapperImpl) wrappedResponse;
}
 
Example #9
Source File: ApiServer.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public ListenerThread(final ApiServer requestHandler, final int port) {
    try {
        _serverSocket = new ServerSocket(port);
    } catch (final IOException ioex) {
        s_logger.error("error initializing api server", ioex);
        return;
    }

    _params = new BasicHttpParams();
    _params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000)
    .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
    .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
    .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
    .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");

    // Set up the HTTP protocol processor
    final BasicHttpProcessor httpproc = new BasicHttpProcessor();
    httpproc.addInterceptor(new ResponseDate());
    httpproc.addInterceptor(new ResponseServer());
    httpproc.addInterceptor(new ResponseContent());
    httpproc.addInterceptor(new ResponseConnControl());

    // Set up request handlers
    final HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
    reqistry.register("*", requestHandler);

    // Set up the HTTP service
    _httpService = new HttpService(httpproc, new NoConnectionReuseStrategy(), new DefaultHttpResponseFactory());
    _httpService.setParams(_params);
    _httpService.setHandlerResolver(reqistry);
}
 
Example #10
Source File: ClusterServiceServletContainer.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public ListenerThread(HttpRequestHandler requestHandler, int port) {
    _executor = Executors.newCachedThreadPool(new NamedThreadFactory("Cluster-Listener"));

    try {
        _serverSocket = new ServerSocket(port);
    } catch (IOException ioex) {
        s_logger.error("error initializing cluster service servlet container", ioex);
        return;
    }

    _params = new BasicHttpParams();
    _params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
        .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
        .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
        .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
        .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");

    // Set up the HTTP protocol processor
    BasicHttpProcessor httpproc = new BasicHttpProcessor();
    httpproc.addInterceptor(new ResponseDate());
    httpproc.addInterceptor(new ResponseServer());
    httpproc.addInterceptor(new ResponseContent());
    httpproc.addInterceptor(new ResponseConnControl());

    // Set up request handlers
    HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
    reqistry.register("/clusterservice", requestHandler);

    // Set up the HTTP service
    _httpService = new HttpService(httpproc, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory());
    _httpService.setParams(_params);
    _httpService.setHandlerResolver(reqistry);
}
 
Example #11
Source File: BintrayImpl.java    From bintray-client-java with Apache License 2.0 5 votes vote down vote up
/**
 * Executes a sign request using the ExecutorService and uses the file count to set a timeout to avoid timing out
 * on long requests
 *
 * @throws BintrayCallException
 */
public HttpResponse sign(String uri, Map<String, String> headers, int fileCount) throws BintrayCallException {
    HttpPost signRequest = new HttpPost(createUrl(uri));
    setHeaders(signRequest, headers);
    signRequest.setConfig(RequestConfig.custom().setSocketTimeout(signRequestTimeoutPerFile * fileCount)
            .setConnectionRequestTimeout(signRequestTimeoutPerFile * fileCount)
            .setConnectTimeout(signRequestTimeoutPerFile * fileCount).build());
    RequestRunner runner = new RequestRunner(signRequest, client, responseHandler);
    Future<String> signResponse = executorService.submit(runner);
    try {
        signResponse.get();
    } catch (Exception e) {
        BintrayCallException bce;
        if (e.getCause() instanceof BintrayCallException) {
            bce = (BintrayCallException) e.getCause();
        } else {
            bce = new BintrayCallException(409, e.getMessage(), (e.getCause() == null) ? ""
                    : ", " + e.getCause().toString() + " : " + e.getCause().getMessage());
        }
        log.error(bce.toString());
        log.debug("{}", e.getMessage(), e);
        throw bce;
    }

    //Return ok
    String entity = "Signing the version was successful";
    HttpResponse response = DefaultHttpResponseFactory.INSTANCE.newHttpResponse(
            new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_CREATED, new HttpClientContext());
    response.setEntity(new StringEntity(entity, Charset.forName("UTF-8")));
    return response;
}
 
Example #12
Source File: BintrayImpl.java    From bintray-client-java with Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse handleResponse(HttpResponse response) throws BintrayCallException {
    int statusCode = response.getStatusLine().getStatusCode();
    if (statusNotOk(statusCode)) {
        BintrayCallException bce = new BintrayCallException(response);

        //We're using CloseableHttpClient so it's ok
        HttpClientUtils.closeQuietly((CloseableHttpResponse) response);
        throw bce;
    }

    //Response entity might be null, 500 and 405 also give the html itself so skip it
    byte[] entity = new byte[0];
    if (response.getEntity() != null && statusCode != 500 && statusCode != 405) {
        try {
            entity = IOUtils.toByteArray(response.getEntity().getContent());
        } catch (IOException | NullPointerException e) {
            //Null entity - Ignore
        } finally {
            HttpClientUtils.closeQuietly((CloseableHttpResponse) response);
        }
    }

    HttpResponse newResponse = DefaultHttpResponseFactory.INSTANCE.newHttpResponse(response.getStatusLine(),
            new HttpClientContext());
    newResponse.setEntity(new ByteArrayEntity(entity));
    newResponse.setHeaders(response.getAllHeaders());
    return newResponse;
}
 
Example #13
Source File: TinyHttpServer.java    From spydroid-ipcamera with GNU General Public License v3.0 5 votes vote down vote up
protected RequestListener() throws Exception {

			mHttpService = new org.apache.http.protocol.HttpService(
					mHttpProcessor, 
					new DefaultConnectionReuseStrategy(), 
					new DefaultHttpResponseFactory());
			mHttpService.setHandlerResolver(mRegistry);
			mHttpService.setParams(mParams);

		}
 
Example #14
Source File: IheHttpFactory.java    From openxds with Apache License 2.0 4 votes vote down vote up
public HttpResponseFactory newResponseFactory() {
    return new DefaultHttpResponseFactory();
}
 
Example #15
Source File: DropboxFileDownloaderTest.java    From endpoints-codelab-android with GNU General Public License v3.0 4 votes vote down vote up
private DropboxServerException notFoundException() {
    HttpResponseFactory factory = new DefaultHttpResponseFactory();
    HttpResponse response = factory.newHttpResponse(new BasicStatusLine(
            HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_FOUND, null), null);
    return new DropboxServerException(response);
}
 
Example #16
Source File: DropboxFileUploaderTest.java    From endpoints-codelab-android with GNU General Public License v3.0 4 votes vote down vote up
private DropboxServerException notFoundException() {
    HttpResponseFactory factory = new DefaultHttpResponseFactory();
    HttpResponse response = factory.newHttpResponse(new BasicStatusLine(
            HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_FOUND, null), null);
    return new DropboxServerException(response);
}