Example usage for org.apache.http.impl DefaultHttpResponseFactory DefaultHttpResponseFactory

List of usage examples for org.apache.http.impl DefaultHttpResponseFactory DefaultHttpResponseFactory

Introduction

In this page you can find the example usage for org.apache.http.impl DefaultHttpResponseFactory DefaultHttpResponseFactory.

Prototype

public DefaultHttpResponseFactory() 

Source Link

Usage

From source file:org.apache.camel.itest.http.HttpTestServer.java

protected HttpResponseFactory newHttpResponseFactory() {
    return new DefaultHttpResponseFactory();
}

From source file:sonata.kernel.vimadaptor.wrapper.openstack.javastackclient.JavaStackCore.java

public synchronized HttpResponse updateStack(String stackName, String stackUuid, String template)
        throws IOException {

    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpResponseFactory factory = new DefaultHttpResponseFactory();
    HttpPatch updateStack = null;/*from  w  w  w .  ja v  a  2s  . c o m*/
    HttpResponse response = null;

    String jsonTemplate = JavaStackUtils.convertYamlToJson(template);
    JSONObject modifiedObject = new JSONObject();
    modifiedObject.put("stack_name", stackName);
    modifiedObject.put("template", new JSONObject(jsonTemplate));

    if (this.isAuthenticated) {
        Logger.debug("");
        StringBuilder buildUrl = new StringBuilder();
        buildUrl.append("http://");
        buildUrl.append(this.endpoint);
        buildUrl.append(":");
        buildUrl.append(Constants.HEAT_PORT.toString());
        buildUrl.append(String.format("/%s/%s/stacks/%s/%s", Constants.HEAT_VERSION.toString(), tenant_id,
                stackName, stackUuid));

        // Logger.debug(buildUrl.toString());
        updateStack = new HttpPatch(buildUrl.toString());
        updateStack.setEntity(new StringEntity(modifiedObject.toString(), ContentType.APPLICATION_JSON));
        // Logger.debug(this.token_id);
        updateStack.addHeader(Constants.AUTHTOKEN_HEADER.toString(), this.token_id);

        Logger.debug("Request: " + updateStack.toString());
        Logger.debug("Request body: " + modifiedObject.toString());

        response = httpClient.execute(updateStack);
        int statusCode = response.getStatusLine().getStatusCode();
        String responsePhrase = response.getStatusLine().getReasonPhrase();

        Logger.debug("Response: " + response.toString());
        Logger.debug("Response body:");

        if (statusCode != 202) {
            BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String line = null;

            while ((line = in.readLine()) != null)
                Logger.debug(line);
        }

        return (statusCode == 202) ? response
                : factory.newHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, statusCode,
                        responsePhrase + ". Create Failed with Status: " + statusCode), null);
    } else {
        throw new IOException("You must Authenticate before issuing this request, please re-authenticate. ");
    }
}

From source file:com.telefonica.iot.cygnus.backends.http.HttpBackendTest.java

/**
 * [HttpBackend.createJsonResponse] -------- A JsonResponse object is
 * created if the content-type header contains 'application/json' but no
 * location header.//w  w  w  .  j a v a 2 s . co m
 */
@Test
public void testCreateJsonResponseNoLocationHeader() {
    System.out.println(getTestTraceHead("[HttpBackend.createJsonResponse]")
            + "-------- A JsonResponse object is created if the content-type header contains 'application/json' "
            + "but no location header");
    HttpResponseFactory factory = new DefaultHttpResponseFactory();
    HttpResponse response = factory
            .newHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, null), null);
    String responseStr = "{\"somefield1\":\"somevalue1\",\"somefield2\":\"somevalue2\","
            + "\"somefield3\":\"somevalue3\"}";

    try {
        response.setEntity(new StringEntity(responseStr));
    } catch (UnsupportedEncodingException e) {
        System.out.println(getTestTraceHead("[HttpBackend.createJsonResponse]")
                + "- FAIL - There was some problem when creating the HttpResponse object");
        throw new AssertionError(e.getMessage());
    } // try catch

    response.addHeader("Content-Type", "application/json");
    HttpBackend httpBackend = new HttpBackendImpl(host, port, false, false, null, null, null, null, maxConns,
            maxConnsPerRoute);

    try {
        JsonResponse jsonRes = httpBackend.createJsonResponse(response);

        try {
            assertEquals(null, jsonRes.getLocationHeader());
            System.out.println(getTestTraceHead("[HttpBackend.createJsonResponse]")
                    + "-  OK  - The JsonResponse object was created with null location header");
        } catch (AssertionError e) {
            System.out.println(getTestTraceHead("[HttpBackend.createJsonResponse]")
                    + "- FAIL - The JsonResponse object was not created with null location header");
            throw e;
        } // try catch
    } catch (Exception e) {
        System.out.println(getTestTraceHead("[HttpBackend.createJsonResponse]")
                + "- FAIL - There was some problem when creating the JsonResponse object");
        throw new AssertionError(e.getMessage());
    } // try catch
}

From source file:marytts.server.http.MaryHttpServer.java

public void run() {
    logger.info("Starting server.");

    int localPort = MaryProperties.needInteger("socket.port");

    HttpParams params = new BasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 0) // 0 means no timeout, any positive value means time out in miliseconds (i.e. 50000 for 50 seconds)
            .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");

    BasicHttpProcessor httpproc = new BasicHttpProcessor();
    httpproc.addInterceptor(new ResponseDate());
    httpproc.addInterceptor(new ResponseServer());
    httpproc.addInterceptor(new ResponseContent());
    httpproc.addInterceptor(new ResponseConnControl());

    BufferingHttpServiceHandler handler = new BufferingHttpServiceHandler(httpproc,
            new DefaultHttpResponseFactory(), new DefaultConnectionReuseStrategy(), params);

    // Set up request handlers
    HttpRequestHandlerRegistry registry = new HttpRequestHandlerRegistry();
    registry.register("/process", new SynthesisRequestHandler());
    InfoRequestHandler infoRH = new InfoRequestHandler();
    registry.register("/version", infoRH);
    registry.register("/datatypes", infoRH);
    registry.register("/locales", infoRH);
    registry.register("/voices", infoRH);
    registry.register("/audioformats", infoRH);
    registry.register("/exampletext", infoRH);
    registry.register("/audioeffects", infoRH);
    registry.register("/audioeffect-default-param", infoRH);
    registry.register("/audioeffect-full", infoRH);
    registry.register("/audioeffect-help", infoRH);
    registry.register("/audioeffect-is-hmm-effect", infoRH);
    registry.register("/features", infoRH);
    registry.register("/features-discrete", infoRH);
    registry.register("/vocalizations", infoRH);
    registry.register("/styles", infoRH);
    registry.register("*", new FileRequestHandler());

    handler.setHandlerResolver(registry);

    // Provide an event logger
    handler.setEventListener(new EventLogger());

    IOEventDispatch ioEventDispatch = new DefaultServerIOEventDispatch(handler, params);

    int numParallelThreads = MaryProperties.getInteger("server.http.parallelthreads", 5);

    logger.info("Waiting for client to connect on port " + localPort);

    try {/*from   w w w  . j  ava  2 s.  c o  m*/
        ListeningIOReactor ioReactor = new DefaultListeningIOReactor(numParallelThreads, params);
        ioReactor.listen(new InetSocketAddress(localPort));
        isReady = true;
        ioReactor.execute(ioEventDispatch);
    } catch (InterruptedIOException ex) {
        logger.info("Interrupted", ex);
    } catch (IOException e) {
        logger.info("Problem with HTTP connection", e);
    }
    logger.debug("Shutdown");
}

From source file:com.telefonica.iot.cygnus.backends.http.HttpBackendTest.java

/**
 * [HttpBackend.createJsonResponse] -------- A JsonResponse object is
 * created if the content-type header contains 'application/json' but no
 * location header.//  w w  w  . ja va2 s. co  m
 */
@Test
public void testCreateJsonResponseHeader() {
    System.out.println(getTestTraceHead("[HttpBackend.createJsonResponse]")
            + "-------- A JsonResponse object is created if the content-type header contains 'application/json' "
            + "but no location header");
    HttpResponseFactory factory = new DefaultHttpResponseFactory();
    HttpResponse response = factory
            .newHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, null), null);
    String responseStr = "{\"somefield1\":\"somevalue1\",\"somefield2\":\"somevalue2\","
            + "\"somefield3\":\"somevalue3\"}";

    try {
        response.setEntity(new StringEntity(responseStr));
    } catch (UnsupportedEncodingException e) {
        System.out.println(getTestTraceHead("[HttpBackend.createJsonResponse]")
                + "- FAIL - There was some problem when creating the HttpResponse object");
        throw new AssertionError(e.getMessage());
    } // try catch

    response.addHeader("Content-Type", "application/json");
    HttpBackend httpBackend = new HttpBackendImpl(host, port, false, false, null, null, null, null, maxConns,
            maxConnsPerRoute);
    httpBackend.setAllHeaders(true);

    try {
        JsonResponse jsonRes = httpBackend.createJsonResponse(response);

        try {
            for (Header header : jsonRes.getHeaders()) {
                assertEquals("Content-Type", header.getName());
                assertEquals("application/json", header.getValue());

            }
            System.out.println(getTestTraceHead("[HttpBackend.createJsonResponse]")
                    + "-  OK  - The JsonResponse object was created with headers");
        } catch (AssertionError e) {
            System.out.println(getTestTraceHead("[HttpBackend.createJsonResponse]")
                    + "- FAIL - The JsonResponse object was not created with null location header");
            throw e;
        } // try catch
    } catch (Exception e) {
        System.out.println(getTestTraceHead("[HttpBackend.createJsonResponse]")
                + "- FAIL - There was some problem when creating the JsonResponse object");
        throw new AssertionError(e.getMessage());
    } // try catch
}

From source file:org.apache.axis2.transport.http.server.HttpFactory.java

public HttpResponseFactory newResponseFactory() {
    return new DefaultHttpResponseFactory();
}

From source file:sonata.kernel.vimadaptor.wrapper.openstack.javastackclient.JavaStackCore.java

public synchronized HttpResponse listStacks(String endpoint) throws IOException {

    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpResponseFactory factory = new DefaultHttpResponseFactory();
    HttpResponse response = null;//  w ww.  jav  a  2 s. c  o  m
    HttpGet listStacks = null;

    if (this.isAuthenticated) {

        StringBuilder buildUrl = new StringBuilder();
        buildUrl.append("http://");
        buildUrl.append(endpoint);
        buildUrl.append(":");
        buildUrl.append(Constants.HEAT_PORT.toString());
        buildUrl.append(String.format("/%s/%s/stacks", Constants.HEAT_VERSION.toString(), this.tenant_id));

        System.out.println(buildUrl);
        System.out.println(this.token_id);

        listStacks = new HttpGet(buildUrl.toString());
        listStacks.addHeader(Constants.AUTHTOKEN_HEADER.toString(), this.token_id);

        response = httpClient.execute(listStacks);
        int status_code = response.getStatusLine().getStatusCode();

        return (status_code == 200) ? response
                : factory.newHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, status_code,
                        "List Failed with Status: " + status_code), null);

    } else {
        throw new IOException("You must Authenticate before issuing this request, please re-authenticate. ");
    }

}

From source file:sonata.kernel.vimadaptor.wrapper.openstack.javastackclient.JavaStackCore.java

public synchronized HttpResponse getStackTemplate(String stackName, String stackId)
        throws IOException, URISyntaxException {

    HttpResponseFactory factory = new DefaultHttpResponseFactory();
    HttpClient httpclient = HttpClientBuilder.create().build();
    HttpGet getStackTemplate = null;//from www .j  a va2 s .  c o m
    HttpResponse response = null;

    if (isAuthenticated) {

        URIBuilder builder = new URIBuilder();
        String path = String.format("/%s/%s/stacks/%s/%s/template", Constants.HEAT_VERSION.toString(),
                this.tenant_id, stackName, stackId);

        builder.setScheme("http").setHost(endpoint).setPort(Integer.parseInt(Constants.HEAT_PORT.toString()))
                .setPath(path);

        URI uri = builder.build();

        getStackTemplate = new HttpGet(uri);
        getStackTemplate.addHeader(Constants.AUTHTOKEN_HEADER.toString(), this.token_id);

        Logger.debug("Request: " + getStackTemplate.toString());

        response = httpclient.execute(getStackTemplate);
        int status_code = response.getStatusLine().getStatusCode();

        Logger.debug("Response: " + response.toString());

        return (status_code == 200) ? response
                : factory.newHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, status_code,
                        "Get Template Failed with Status: " + status_code), null);

    } else {
        throw new IOException("You must Authenticate before issuing this request, please re-authenticate. ");
    }

}

From source file:com.telefonica.iot.cygnus.backends.http.HttpBackendTest.java

/**
 * [HttpBackend.finishTransaction] -------- Once a transaction is finished,
 * the byte counts are correct./* w w w  .j  ava2s. c o  m*/
 */
@Test
public void testFinishTransaction() {
    System.out.println(getTestTraceHead("[HttpBackend.finishTransaction]")
            + "-------- Once a transaction is finished, the byte counts are correct");

    // Create a response
    HttpResponseFactory factory = new DefaultHttpResponseFactory();
    HttpResponse response = factory
            .newHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, null), null);
    String responseStr = "{\"somefield1\":\"somevalue1\",\"somefield2\":\"somevalue2\","
            + "\"somefield3\":\"somevalue3\"}";

    try {
        response.setEntity(new StringEntity(responseStr));
    } catch (UnsupportedEncodingException e) {
        System.out.println(getTestTraceHead("[HttpBackend.createJsonResponse]")
                + "- FAIL - There was some problem when creating the HttpResponse object");
        throw new AssertionError(e.getMessage());
    } // try catch

    response.addHeader("Content-Type", "application/json");

    // Create the http backend
    HttpBackend httpBackend = new HttpBackendImpl(host, port, false, false, null, null, null, null, maxConns,
            maxConnsPerRoute);

    // Start transaction
    httpBackend.startTransaction();

    // Process the response
    try {
        httpBackend.createJsonResponse(response);
    } catch (Exception e) {
        System.out.println(getTestTraceHead("[HttpBackend.createJsonResponse]")
                + "- FAIL - There was some problem when creating the JsonResponse object");
        throw new AssertionError(e.getMessage());
    } // try catch

    // Finish transaction
    ImmutablePair<Long, Long> transactionBytes = httpBackend.finishTransaction();

    // Check the byte counts
    try {
        assertEquals(0, transactionBytes.left.longValue());
        System.out.println(
                getTestTraceHead("[HttpBackend.finishTransaction]") + "-  OK  - Request bytes is equals to 0");
    } catch (AssertionError e) {
        System.out.println(getTestTraceHead("[HttpBackend.finishTransaction]")
                + "- FAIL - Request bytes is not equals to 0");
        throw e;
    } // try catch

    try {
        assertEquals(79, transactionBytes.right.longValue());
        System.out.println(getTestTraceHead("[HttpBackend.finishTransaction]")
                + "-  OK  - Response bytes is equals to 79");
    } catch (AssertionError e) {
        System.out.println(getTestTraceHead("[HttpBackend.finishTransaction]")
                + "- FAIL - Response bytes is not equals to 79");
        throw e;
    } // try catch
}

From source file:sonata.kernel.vimadaptor.wrapper.openstack.javastackclient.JavaStackCore.java

public synchronized HttpResponse showResourceData(String stackName, String stackId, String resourceName)
        throws IOException, URISyntaxException {
    HttpResponseFactory factory = new DefaultHttpResponseFactory();
    HttpClient httpclient = HttpClientBuilder.create().build();
    HttpGet showResourceData = null;/*  w  ww .  j a va  2s  . co  m*/
    HttpResponse response = null;

    if (isAuthenticated) {
        URIBuilder builder = new URIBuilder();
        String path = String.format("/%s/%s/stacks/%s/%s/resources/%s", Constants.HEAT_VERSION.toString(),
                this.tenant_id, stackName, stackId, resourceName);

        builder.setScheme("http").setHost(endpoint).setPort(Integer.parseInt(Constants.HEAT_PORT.toString()))
                .setPath(path);

        URI uri = builder.build();

        showResourceData = new HttpGet(uri);
        showResourceData.addHeader(Constants.AUTHTOKEN_HEADER.toString(), this.token_id);

        response = httpclient.execute(showResourceData);
        int status_code = response.getStatusLine().getStatusCode();

        return (status_code == 200) ? response
                : factory.newHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, status_code,
                        "List Failed with Status: " + status_code), null);

    } else {
        throw new IOException("You must Authenticate before issuing this request, please re-authenticate. ");
    }
}