Example usage for org.apache.http.client HttpClient getConnectionManager

List of usage examples for org.apache.http.client HttpClient getConnectionManager

Introduction

In this page you can find the example usage for org.apache.http.client HttpClient getConnectionManager.

Prototype

@Deprecated
ClientConnectionManager getConnectionManager();

Source Link

Document

Obtains the connection manager used by this client.

Usage

From source file:com.meltmedia.jgroups.aws.AWS_PING.java

/**
 * Scans the environment for information about the AWS node that we are
 * currently running on and parses the filters and tags.
 *//* www  .  jav a 2s. c  om*/
public void init() throws Exception {
    super.init();

    // get the instance id and availability zone.
    HttpClient client = null;
    try {
        client = new DefaultHttpClient();
        instanceId = getBody(client, GET_INSTANCE_ID);
        availabilityZone = getBody(client, GET_AVAILABILITY_ZONE);
    } finally {
        if (client != null) {
            client.getConnectionManager().shutdown();
        }
    }

    if (filters != null)
        awsFilters = parseFilters(filters);
    if (tags != null)
        awsTagNames = parseTagNames(tags);

    if (log.isDebugEnabled()) {
        if (filters != null)
            log.debug("\n\nConfigured with filters [" + awsFilters + "]\n\n");
        if (tags != null)
            log.debug("\n\nConfigured with tags [" + awsTagNames + "]\n\n");
    }
    // compute the EC2 endpoint based on the availability zone.
    endpoint = "ec2." + availabilityZone.replaceAll("(.*-\\d+)[^-\\d]+", "$1") + ".amazonaws.com";
}

From source file:org.apache.camel.component.cxf.jaxrs.CxfRsRouterTest.java

@Test
public void testPostConsumerUniqueResponseCode() throws Exception {
    HttpPost post = new HttpPost("http://localhost:" + getPort()
            + "/CxfRsRouterTest/route/customerservice/customersUniqueResponseCode");
    post.addHeader("Accept", "text/xml");
    StringEntity entity = new StringEntity(POST_REQUEST, "ISO-8859-1");
    entity.setContentType("text/xml; charset=ISO-8859-1");
    post.setEntity(entity);//from w ww .  jav  a2s  .  com
    HttpClient httpclient = new DefaultHttpClient();

    try {
        HttpResponse response = httpclient.execute(post);
        assertEquals(201, response.getStatusLine().getStatusCode());
        assertEquals(
                "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Customer><id>124</id><name>Jack</name></Customer>",
                EntityUtils.toString(response.getEntity()));

        HttpDelete del = new HttpDelete(
                "http://localhost:" + getPort() + "/CxfRsRouterTest/route/customerservice/customers/124/");
        httpclient.execute(del);
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:co.cask.cdap.runtime.OpenCloseDataSetTest.java

@Test(timeout = 120000)
public void testDataSetsAreClosed() throws Exception {
    final String tableName = "foo";

    TrackingTable.resetTracker();/*  w w  w.  ja  v  a 2  s .c  om*/
    ApplicationWithPrograms app = AppFabricTestHelper
            .deployApplicationWithManager(DummyAppWithTrackingTable.class, TEMP_FOLDER_SUPPLIER);
    ProgramRunnerFactory runnerFactory = AppFabricTestHelper.getInjector()
            .getInstance(ProgramRunnerFactory.class);
    List<ProgramController> controllers = Lists.newArrayList();

    // start the programs
    for (Program program : app.getPrograms()) {
        if (program.getType().equals(ProgramType.MAPREDUCE)) {
            continue;
        }
        ProgramRunner runner = runnerFactory.create(program.getType());
        BasicArguments systemArgs = new BasicArguments(
                ImmutableMap.of(ProgramOptionConstants.RUN_ID, RunIds.generate().getId()));
        controllers.add(runner.run(program,
                new SimpleProgramOptions(program.getName(), systemArgs, new BasicArguments())));
    }

    // write some data to queue
    TransactionSystemClient txSystemClient = AppFabricTestHelper.getInjector()
            .getInstance(TransactionSystemClient.class);

    QueueName queueName = QueueName.fromStream(app.getId().getNamespaceId(), "xx");
    QueueClientFactory queueClientFactory = AppFabricTestHelper.getInjector()
            .getInstance(QueueClientFactory.class);
    QueueProducer producer = queueClientFactory.createProducer(queueName);

    // start tx to write in queue in tx
    Transaction tx = txSystemClient.startShort();
    ((TransactionAware) producer).startTx(tx);

    StreamEventCodec codec = new StreamEventCodec();
    for (int i = 0; i < 4; i++) {
        String msg = "x" + i;
        StreamEvent event = new StreamEvent(ImmutableMap.<String, String>of(),
                ByteBuffer.wrap(msg.getBytes(Charsets.UTF_8)));
        producer.enqueue(new QueueEntry(codec.encodePayload(event)));
    }

    // commit tx
    ((TransactionAware) producer).commitTx();
    txSystemClient.commit(tx);

    while (TrackingTable.getTracker(tableName, "write") < 4) {
        TimeUnit.MILLISECONDS.sleep(50);
    }

    // get the number of writes to the foo table
    Assert.assertEquals(4, TrackingTable.getTracker(tableName, "write"));
    // only 2 "open" calls should be tracked:
    // 1. the flow has started with single flowlet (service is loaded lazily on 1st request)
    // 2. DatasetSystemMetadataWriter also instantiates the dataset because it needs to add some system tags
    // for the dataset
    Assert.assertEquals(2, TrackingTable.getTracker(tableName, "open"));

    // now send a request to the service
    Gson gson = new Gson();
    DiscoveryServiceClient discoveryServiceClient = AppFabricTestHelper.getInjector()
            .getInstance(DiscoveryServiceClient.class);

    Discoverable discoverable = new RandomEndpointStrategy(discoveryServiceClient
            .discover(String.format("service.%s.%s.%s", DefaultId.NAMESPACE.getId(), "dummy", "DummyService")))
                    .pick(5, TimeUnit.SECONDS);
    Assert.assertNotNull(discoverable);

    HttpClient client = new DefaultHttpClient();
    HttpGet get = new HttpGet(String.format("http://%s:%d/v3/namespaces/default/apps/%s/services/%s/methods/%s",
            discoverable.getSocketAddress().getHostName(), discoverable.getSocketAddress().getPort(), "dummy",
            "DummyService", "x1"));
    HttpResponse response = client.execute(get);
    String responseContent = gson
            .fromJson(new InputStreamReader(response.getEntity().getContent(), Charsets.UTF_8), String.class);
    client.getConnectionManager().shutdown();
    Assert.assertEquals("x1", responseContent);

    // now the dataset must have a read and another open operation
    Assert.assertEquals(1, TrackingTable.getTracker(tableName, "read"));
    Assert.assertEquals(3, TrackingTable.getTracker(tableName, "open"));
    // The dataset that was instantiated by the DatasetSystemMetadataWriter should have been closed
    Assert.assertEquals(1, TrackingTable.getTracker(tableName, "close"));

    // stop all programs, they should both close the data set foo
    for (ProgramController controller : controllers) {
        controller.stop().get();
    }
    int timesOpened = TrackingTable.getTracker(tableName, "open");
    Assert.assertTrue(timesOpened >= 2);
    Assert.assertEquals(timesOpened, TrackingTable.getTracker(tableName, "close"));

    // now start the m/r job
    ProgramController controller = null;
    for (Program program : app.getPrograms()) {
        if (program.getType().equals(ProgramType.MAPREDUCE)) {
            ProgramRunner runner = runnerFactory.create(program.getType());
            BasicArguments systemArgs = new BasicArguments(
                    ImmutableMap.of(ProgramOptionConstants.RUN_ID, RunIds.generate().getId()));
            controller = runner.run(program,
                    new SimpleProgramOptions(program.getName(), systemArgs, new BasicArguments()));
        }
    }
    Assert.assertNotNull(controller);

    while (!controller.getState().equals(ProgramController.State.COMPLETED)) {
        TimeUnit.MILLISECONDS.sleep(100);
    }

    // M/r job is done, one mapper and the m/r client should have opened and closed the data set foo
    // we don't know the exact number of times opened, but it is at least once, and it must be closed the same number
    // of times.
    Assert.assertTrue(timesOpened < TrackingTable.getTracker(tableName, "open"));
    Assert.assertEquals(TrackingTable.getTracker(tableName, "open"),
            TrackingTable.getTracker(tableName, "close"));
    Assert.assertTrue(0 < TrackingTable.getTracker("bar", "open"));
    Assert.assertEquals(TrackingTable.getTracker("bar", "open"), TrackingTable.getTracker("bar", "close"));

}

From source file:org.apache.camel.component.cxf.jaxrs.CxfRsRouterTest.java

@Test
public void testPostConsumer() throws Exception {
    HttpPost post = new HttpPost(
            "http://localhost:" + getPort() + "/CxfRsRouterTest/route/customerservice/customers");
    post.addHeader("Accept", "text/xml");
    StringEntity entity = new StringEntity(POST_REQUEST, "ISO-8859-1");
    entity.setContentType("text/xml; charset=ISO-8859-1");
    post.setEntity(entity);/*from w  ww . j a  v a2 s.  co  m*/
    HttpClient httpclient = new DefaultHttpClient();

    try {
        HttpResponse response = httpclient.execute(post);
        assertEquals(200, response.getStatusLine().getStatusCode());
        assertEquals(
                "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Customer><id>124</id><name>Jack</name></Customer>",
                EntityUtils.toString(response.getEntity()));

        HttpDelete del = new HttpDelete(
                "http://localhost:" + getPort() + "/CxfRsRouterTest/route/customerservice/customers/124/");
        httpclient.execute(del);
    } finally {
        httpclient.getConnectionManager().shutdown();
    }

}

From source file:org.neo4j.server.rest.RetrieveRelationshipsFromNodeDocIT.java

@Test
public void shouldParameteriseUrisInRelationshipRepresentationWithoutHostHeaderUsingRequestUri()
        throws Exception {
    HttpClient httpclient = new DefaultHttpClient();
    try {/*  w  ww .j a v a  2s  .  co  m*/
        HttpGet httpget = new HttpGet("http://localhost:7474/db/data/relationship/" + likes);

        httpget.setHeader("Accept", "application/json");
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        String entityBody = IOUtils.toString(entity.getContent(), "UTF-8");

        assertThat(entityBody, containsString("http://localhost:7474/db/data/relationship/" + likes));
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:org.apache.juddi.v3.tck.UDDI_160_RESTIntergrationTest.java

@Test
public void InquiryREST_GET_Business() throws Exception {
    Assume.assumeTrue(TckPublisher.isEnabled());
    Assume.assumeTrue(TckPublisher.isInquiryRestEnabled());
    FindBusiness fb = new FindBusiness();
    fb.setMaxRows(1);/*from  www .j a va  2s .  c  om*/
    fb.getName().add(new Name(UDDIConstants.WILDCARD, null));
    fb.setFindQualifiers(new FindQualifiers());
    fb.getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH);
    BusinessList findBusiness = inquiry.findBusiness(fb);
    Assume.assumeTrue(findBusiness != null);
    Assume.assumeTrue(findBusiness.getBusinessInfos() != null);
    Assume.assumeTrue(!findBusiness.getBusinessInfos().getBusinessInfo().isEmpty());

    String url = manager.getClientConfig().getHomeNode().getInquiry_REST_Url();

    Assume.assumeNotNull(url);
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(
            url + "?businessKey=" + findBusiness.getBusinessInfos().getBusinessInfo().get(0).getBusinessKey());
    logger.info("Fetching " + httpGet.getURI());
    HttpResponse response = client.execute(httpGet);

    Assert.assertTrue(response.getStatusLine().getStatusCode() == 200);
    logger.info("Response content: " + response.getEntity().getContent());
    BusinessEntity unmarshal = JAXB.unmarshal(response.getEntity().getContent(), BusinessEntity.class);
    client.getConnectionManager().shutdown();
    Assert.assertNotNull(unmarshal);
    Assert.assertEquals(unmarshal.getBusinessKey(),
            findBusiness.getBusinessInfos().getBusinessInfo().get(0).getBusinessKey());

}

From source file:org.apache.juddi.v3.tck.UDDI_160_RESTIntergrationTest.java

@Test
public void InquiryREST_GET_Service() throws Exception {
    Assume.assumeTrue(TckPublisher.isEnabled());
    Assume.assumeTrue(TckPublisher.isInquiryRestEnabled());
    //find the first service via inquriy soap
    FindService fb = new FindService();
    fb.setMaxRows(1);// ww w  .j av a2  s.c  o  m
    fb.getName().add(new Name(UDDIConstants.WILDCARD, null));
    fb.setFindQualifiers(new FindQualifiers());
    fb.getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH);
    ServiceList findService = inquiry.findService(fb);
    Assume.assumeTrue(findService != null);
    Assume.assumeTrue(findService.getServiceInfos() != null);
    Assume.assumeTrue(!findService.getServiceInfos().getServiceInfo().isEmpty());

    String url = manager.getClientConfig().getHomeNode().getInquiry_REST_Url();

    Assume.assumeNotNull(url);

    //get the results via inquiry rest
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(
            url + "?serviceKey=" + findService.getServiceInfos().getServiceInfo().get(0).getServiceKey());
    logger.info("Fetching " + httpGet.getURI());
    HttpResponse response = client.execute(httpGet);

    Assert.assertTrue(response.getStatusLine().getStatusCode() == 200);
    logger.info("Response content: " + response.getEntity().getContent());
    BusinessService unmarshal = JAXB.unmarshal(response.getEntity().getContent(), BusinessService.class);
    client.getConnectionManager().shutdown();
    Assert.assertNotNull(unmarshal);
    Assert.assertEquals(unmarshal.getServiceKey(),
            findService.getServiceInfos().getServiceInfo().get(0).getServiceKey());

}

From source file:com.google.appengine.tck.blobstore.support.FileUploader.java

public String uploadFile(String uri, String partName, String filename, String mimeType, byte[] contents,
        int expectedResponseCode) throws URISyntaxException, IOException {
    HttpClient httpClient = new DefaultHttpClient();
    try {/*from  ww  w . ja va 2  s .  com*/
        HttpPost post = new HttpPost(uri);
        MultipartEntity entity = new MultipartEntity();
        ByteArrayBody contentBody = new ByteArrayBody(contents, mimeType, filename);
        entity.addPart(partName, contentBody);
        post.setEntity(entity);
        HttpResponse response = httpClient.execute(post);
        String result = EntityUtils.toString(response.getEntity());
        int statusCode = response.getStatusLine().getStatusCode();
        Assert.assertEquals(String.format("Invalid response code, %s", statusCode), expectedResponseCode,
                statusCode);
        return result;
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:io.werval.maven.DevShellMojoIT.java

@Test
public void devshellMojoIntegrationTest() throws InterruptedException, IOException {
    final Holder<Exception> errorHolder = new Holder<>();
    Thread devshellThread = new Thread(newRunnable(errorHolder, "werval:devshell"),
            "maven-werval-devshell-thread");
    try {/*from   w w  w .  j av a 2s  . co  m*/
        devshellThread.start();

        await().atMost(60, SECONDS).until(() -> lock.exists());

        if (errorHolder.isSet()) {
            throw new RuntimeException("Error during devhell invocation: " + errorHolder.get().getMessage(),
                    errorHolder.get());
        }

        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet("http://localhost:23023/");
        ResponseHandler<String> handler = new BasicResponseHandler();

        assertThat(client.execute(get, handler), containsString("I ran!"));

        Files.write(new File(tmp.getRoot(), "src/main/java/controllers/Application.java").toPath(),
                CONTROLLER_CHANGED.getBytes(UTF_8));

        // Wait for source code change to be detected
        Thread.sleep(2000);

        assertThat(client.execute(get, handler), containsString("I ran changed!"));

        assertThat(client.execute(new HttpGet("http://localhost:23023/@doc"), handler),
                containsString("Werval Documentation"));

        client.getConnectionManager().shutdown();
    } finally {
        devshellThread.interrupt();
    }
}

From source file:org.zywx.wbpalmstar.platform.push.report.PushReportHttpClient.java

public static String getGetData(String url, Context mCtx) {
    PushReportUtility.log(url);/*  w w  w  .  j  ava  2 s.  com*/
    HttpGet get = new HttpGet(url);
    HttpResponse httpResponse = null;
    HttpClient httpClient = getSSLHttpClient(mCtx);
    // HttpClient httpClient = null;
    get.setHeader("Accept", "*/*");
    try {
        // httpClient = new DefaultHttpClient(setRedirecting());
        Header[] Headers = get.getAllHeaders();
        for (Header header : Headers) {
            PushReportUtility.log(header.getName() + "=" + header.getValue());
        }
        httpResponse = httpClient.execute(get);
        int responesCode = httpResponse.getStatusLine().getStatusCode();
        BDebug.d("debug", "responesCode == " + responesCode);
        PushReportUtility.log("responesCode = " + responesCode);
        if (responesCode == 200) {
            // ?
            String res = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);
            PushReportUtility.log("res = " + res);
            return res;
        }
    } catch (Exception e) {
        PushReportUtility.log("Exception ==" + e.getMessage());
        e.printStackTrace();
    } finally {
        if (get != null) {
            get.abort();
            get = null;
        }
        if (httpResponse != null) {
            httpResponse = null;
        }
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
            httpClient = null;
        }
    }
    return null;
}