Example usage for org.apache.http.impl.client DefaultHttpClient getConnectionManager

List of usage examples for org.apache.http.impl.client DefaultHttpClient getConnectionManager

Introduction

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

Prototype

public synchronized final ClientConnectionManager getConnectionManager() 

Source Link

Usage

From source file:org.jboss.as.test.clustering.unmanaged.ejb3.stateful.StatefulFailoverTestCase.java

@Test
@InSequence(1)/*from w  w  w  .  ja  v a2s .  c o m*/
/* @OperateOnDeployment(DEPLOYMENT1) -- See http://community.jboss.org/thread/176096 */
public void testRestart(/*@ArquillianResource(SimpleServlet.class) URL baseURL*/)
        throws IOException, InterruptedException {
    // Container is unmanaged, need to start manually.
    controller.start(CONTAINER1);
    deployer.deploy(DEPLOYMENT1);

    DefaultHttpClient client = new DefaultHttpClient();

    // ARQ-674 Ouch, second hardcoded URL will need fixing. ARQ doesnt support @OperateOnDeployment on 2 containers.
    String url1 = "http://127.0.0.1:8080/stateful/count";
    String url2 = "http://127.0.0.1:8180/stateful/count";

    try {
        assertQueryCount(10101, client, url1);
        assertQueryCount(20202, client, url1);

        controller.start(CONTAINER2);
        deployer.deploy(DEPLOYMENT2);

        assertQueryCount(30303, client, url1);
        assertQueryCount(40404, client, url1);

        assertQueryCount(50505, client, url2);
        assertQueryCount(60606, client, url2);

        controller.stop(CONTAINER2);

        assertQueryCount(70707, client, url1);
        assertQueryCount(80808, client, url1);

        controller.start(CONTAINER2);

        assertQueryCount(90909, client, url1);
        assertQueryCount(101010, client, url1);

        assertQueryCount(111111, client, url2);
        assertQueryCount(121212, client, url2);

        controller.stop(CONTAINER1);
        assertQueryCount(131313, client, url2);
        assertQueryCount(141414, client, url2);

        controller.start(CONTAINER1);

        assertQueryCount(151515, client, url1);
        assertQueryCount(161616, client, url1);

        assertQueryCount(171717, client, url1);
        assertQueryCount(181818, client, url1);
    } finally {
        client.getConnectionManager().shutdown();

        this.cleanup(DEPLOYMENT1, CONTAINER1);
        this.cleanup(DEPLOYMENT2, CONTAINER2);
    }
}

From source file:org.jboss.as.test.clustering.unmanaged.ejb3.stateful.StatefulFailoverTestCase.java

@Test
@InSequence(2)//from  ww  w . ja v a2 s .c o  m
/* @OperateOnDeployment(DEPLOYMENT1) -- See http://community.jboss.org/thread/176096 */
public void testRedeploy(/*@ArquillianResource(SimpleServlet.class) URL baseURL*/)
        throws IOException, InterruptedException {
    // Container is unmanaged, need to start manually.
    controller.start(CONTAINER1);
    deployer.deploy(DEPLOYMENT1);

    DefaultHttpClient client = new DefaultHttpClient();

    // ARQ-674 Ouch, second hardcoded URL will need fixing. ARQ doesnt support @OperateOnDeployment on 2 containers.
    String url1 = "http://127.0.0.1:8080/stateful/count";
    String url2 = "http://127.0.0.1:8180/stateful/count";

    try {
        assertQueryCount(10101, client, url1);
        assertQueryCount(20202, client, url1);

        controller.start(CONTAINER2);
        deployer.deploy(DEPLOYMENT2);

        assertQueryCount(30303, client, url1);
        assertQueryCount(40404, client, url1);

        assertQueryCount(50505, client, url2);
        assertQueryCount(60606, client, url2);

        deployer.undeploy(DEPLOYMENT2);

        assertQueryCount(70707, client, url1);
        assertQueryCount(80808, client, url1);

        deployer.deploy(DEPLOYMENT2);

        assertQueryCount(90909, client, url1);
        assertQueryCount(101010, client, url1);

        assertQueryCount(111111, client, url2);
        assertQueryCount(121212, client, url2);

        deployer.undeploy(DEPLOYMENT1);

        assertQueryCount(131313, client, url2);
        assertQueryCount(141414, client, url2);

        deployer.deploy(DEPLOYMENT1);

        assertQueryCount(151515, client, url1);
        assertQueryCount(161616, client, url1);

        assertQueryCount(171717, client, url2);
        assertQueryCount(181818, client, url2);
    } finally {
        client.getConnectionManager().shutdown();

        this.cleanup(DEPLOYMENT1, CONTAINER1);
        this.cleanup(DEPLOYMENT2, CONTAINER2);
    }
}

From source file:edu.harvard.i2b2.eclipse.plugins.metadataLoader.views.loader.TableComposite.java

public void update() {
    String catalogString;/* ww  w .  j a  v  a 2  s  .co  m*/
    try {
        // for a local file
        //      FileInputStream catalogStream = new FileInputStream(new File(RunData.getInstance().getCatalogLocation()));
        //   FileInputStream catalogStream = new FileInputStream((RunData.getInstance().getCatalogLocation()));

        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(RunData.getInstance().getCatalogLocation());

        HttpResponse response = httpclient.execute(httpget);

        //         System.out.println(response.getStatusLine());
        HttpEntity entity = response.getEntity();
        if (entity != null) {

            InputStream catalogStream = entity.getContent();

            catalogString = IOUtils.toString(catalogStream, "UTF-8");
            JAXBElement jaxbElement = MetadataLoaderJAXBUtil.getJAXBUtil().unMashallFromString(catalogString);
            OntologyCatalogType catalog = (OntologyCatalogType) jaxbElement.getValue();
            list = catalog.getOntology();
        }
        httpclient.getConnectionManager().shutdown();

        // for a local file
        //   catalogString = IOUtils.toString(catalogStream, "UTF-8");
        //   JAXBElement jaxbElement = MetadataLoaderJAXBUtil.getJAXBUtil().unMashallFromString(catalogString);
        //   OntologyCatalogType catalog  = (OntologyCatalogType) jaxbElement.getValue();
        //   list = catalog.getOntology();
        checkIfPreviouslyInstalled(list, Display.getCurrent(), this.viewer);
        // check to see if any tables previously installed

        refresh();

    } catch (FileNotFoundException e) {
        Display.getCurrent().syncExec(new Runnable() {
            TableViewer theViewer = viewer;

            public void run() {
                // e.getMessage() == Incoming message input stream is null  -- for the case of connection down.
                MessageBox mBox = new MessageBox(theViewer.getTable().getShell(), SWT.ERROR | SWT.OK);
                mBox.setText("Please Note ...");
                mBox.setMessage(
                        "Catalog not found at location \n Please make sure the location is correct and try again");
                int result = mBox.open();
                //      TableComposite.getInstance().refresh();
            }
        });
    } catch (JAXBUtilException e) {
        Display.getCurrent().syncExec(new Runnable() {
            TableViewer theViewer = viewer;

            public void run() {
                // e.getMessage() == Incoming message input stream is null  -- for the case of connection down.
                MessageBox mBox = new MessageBox(theViewer.getTable().getShell(), SWT.ERROR | SWT.OK);
                mBox.setText("Please Note ...");
                mBox.setMessage("Catalog not in correct format");
                int result = mBox.open();
                //      TableComposite.getInstance().refresh();
            }
        });

    } catch (IOException e) {
        Display.getCurrent().syncExec(new Runnable() {
            TableViewer theViewer = viewer;

            public void run() {
                // e.getMessage() == Incoming message input stream is null  -- for the case of connection down.
                MessageBox mBox = new MessageBox(theViewer.getTable().getShell(), SWT.ERROR | SWT.OK);
                mBox.setText("Please Note ...");
                mBox.setMessage(
                        "An I/O exception occurred \n Please make sure the location is correct and try again");
                int result = mBox.open();
                //      TableComposite.getInstance().refresh();
            }
        });
    }

}

From source file:org.jboss.as.test.clustering.cluster.ejb.stateful.StatefulFailoverTestCase.java

/**
 * Validates failover of a @Stateful bean containing a nested @Stateful bean
 * containing an injected CDI bean that uses an interceptor and decorator.
 *///from  w w  w.  j a va  2 s  .c  om
@Test
public void nestedBeanFailover(@ArquillianResource() @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1,
        @ArquillianResource() @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2) throws Exception {

    DefaultHttpClient client = org.jboss.as.test.http.util.HttpClientUtils.relaxedCookieHttpClient();

    URI uri1 = StatefulServlet.createURI(baseURL1, MODULE_NAME, NestedIncrementorBean.class.getSimpleName());
    URI uri2 = StatefulServlet.createURI(baseURL2, MODULE_NAME, NestedIncrementorBean.class.getSimpleName());

    try {
        assertEquals(20010101, queryCount(client, uri1));
        assertEquals(20020202, queryCount(client, uri1));

        assertEquals(20030303, queryCount(client, uri2));
        assertEquals(20040404, queryCount(client, uri2));

        undeploy(DEPLOYMENT_2);

        assertEquals(20050505, queryCount(client, uri1));
        assertEquals(20060606, queryCount(client, uri1));

        deploy(DEPLOYMENT_2);

        assertEquals(20070707, queryCount(client, uri1));
        assertEquals(20080808, queryCount(client, uri1));

        assertEquals(20090909, queryCount(client, uri2));
        assertEquals(20101010, queryCount(client, uri2));

        undeploy(DEPLOYMENT_1);

        assertEquals(20111111, queryCount(client, uri2));
        assertEquals(20121212, queryCount(client, uri2));

        deploy(DEPLOYMENT_1);

        assertEquals(20131313, queryCount(client, uri1));
        assertEquals(20141414, queryCount(client, uri1));

        assertEquals(20151515, queryCount(client, uri2));
        assertEquals(20161616, queryCount(client, uri2));
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:sand.actionhandler.weibo.UdaClient.java

public static String syn(String url) {
    String content = "";

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {//from ww  w  .  ja va 2s  .com
        httpclient = createHttpClient();

        HttpGet httpget = new HttpGet(url);

        // Execute HTTP request
        //System.out.println("executing request " + httpget.getURI());
        //logger.info("executing request " + httpget.getURI());

        //            System.out.println("----------------------------------------");
        //            System.out.println(response.getStatusLine());
        //            System.out.println(response.getLastHeader("Content-Encoding"));
        //            System.out.println(response.getLastHeader("Content-Length"));
        //            System.out.println("----------------------------------------");

        //System.out.println(entity.getContentType());

        httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2965);

        httpget.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

        CookieStore cookieStore = new BasicCookieStore();

        addCookie(cookieStore);
        // 
        httpclient.setCookieStore(cookieStore);
        //httpclient.ex
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            content = EntityUtils.toString(entity);
            System.out.println(content);
            System.out.println("----------------------------------------");
            System.out.println("Uncompressed size: " + content.length());
        }

    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }

    return content;
}

From source file:org.springframework.social.reddit.connect.RedditOAuth2Template.java

private String getAccessToken(String code, String redirectUrl)
        throws UnsupportedEncodingException, IOException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {/*w  ww  . j  a v  a 2  s  . co m*/

        //Reddit Requires clientId and clientSecret be attached via basic auth
        httpclient.getCredentialsProvider().setCredentials(new AuthScope("ssl.reddit.com", 443),
                new UsernamePasswordCredentials(clientId, clientSecret));

        HttpPost httppost = new HttpPost(RedditPaths.OAUTH_TOKEN_URL);

        List<NameValuePair> nvps = new ArrayList<NameValuePair>(3);
        nvps.add(new BasicNameValuePair("code", code));
        nvps.add(new BasicNameValuePair("grant_type", "authorization_code"));
        nvps.add(new BasicNameValuePair("redirect_uri", redirectUrl));

        httppost.setEntity(new UrlEncodedFormEntity(nvps));
        httppost.addHeader("User-Agent", "a unique user agent");
        httppost.setHeader("Accept", "any;");

        HttpResponse request = httpclient.execute(httppost);
        HttpEntity response = request.getEntity(); // Reddit response containing accessToken

        if (response != null) {
            BufferedReader br = new BufferedReader(new InputStreamReader(response.getContent()));
            StringBuilder content = new StringBuilder();
            String line;
            while (null != (line = br.readLine())) {
                content.append(line);
            }
            System.out.println(content.toString());
            Map json = (Map) JSONValue.parse(content.toString());
            if (json.containsKey("access_token")) {
                return (String) (json.get("access_token"));
            }
        }
        EntityUtils.consume(response);
    } finally {
        httpclient.getConnectionManager().shutdown(); //cleanup
    }
    return null;
}

From source file:com.lehealth.common.sdk.CCPRestSDK.java

/**
 * ???/*ww w.  j  a  v  a  2s .  co m*/
 * 
 * @param to
 *            ? ??????????100
 * @param templateId
 *            ? ?Id
 * @param datas
 *            ?? ???{??}
 * @return
 */
public JSONObject sendTemplateSMS(String to, String templateId, String[] datas, String domain, String appId,
        String sid, String token) {
    JSONObject errorInfo = this.accountValidate(domain, appId, sid, token);
    if (errorInfo != null) {
        return errorInfo;
    }

    if (StringUtils.isBlank(to) || StringUtils.isBlank(appId) || StringUtils.isBlank(templateId)) {
        throw new IllegalArgumentException("?:" + (StringUtils.isBlank(to) ? " ?? " : "")
                + (StringUtils.isBlank(templateId) ? " ?Id " : "") + "");
    }

    String timestamp = DateFormatUtils.format(new Date(), Constant.dateFormat_yyyymmddhhmmss);
    String acountName = sid;
    String sig = sid + token + timestamp;
    String acountType = "Accounts";
    String signature = DigestUtils.md5Hex(sig);
    String url = getBaseUrl(domain).append("/" + acountType + "/").append(acountName)
            .append("/" + TemplateSMS + "?sig=").append(signature).toString();

    String src = acountName + ":" + timestamp;
    String auth = Base64.encodeBase64String(src.getBytes());
    Map<String, String> header = new HashMap<String, String>();
    header.put("Accept", "application/json");
    header.put("Content-Type", "application/json;charset=utf-8");
    header.put("Authorization", auth);

    JSONObject json = new JSONObject();
    json.accumulate("appId", appId);
    json.accumulate("to", to);
    json.accumulate("templateId", templateId);
    if (datas != null) {
        JSONArray Jarray = new JSONArray();
        for (String s : datas) {
            Jarray.add(s);
        }
        json.accumulate("datas", Jarray);
    }
    String requestBody = json.toString();

    DefaultHttpClient httpclient = null;
    HttpPost postMethod = null;
    try {
        httpclient = new CcopHttpClient().registerSSL(domain, NumberUtils.toInt(SERVER_PORT), "TLS", "https");
        postMethod = new HttpPost(url);
        if (header != null && !header.isEmpty()) {
            for (Entry<String, String> e : header.entrySet()) {
                postMethod.setHeader(e.getKey(), e.getValue());
            }
        }
        postMethod.setConfig(PoolConnectionManager.requestConfig);
        BasicHttpEntity requestEntity = new BasicHttpEntity();
        requestEntity.setContent(new ByteArrayInputStream(requestBody.getBytes("UTF-8")));
        requestEntity.setContentLength(requestBody.getBytes("UTF-8").length);
        postMethod.setEntity(requestEntity);

        HttpResponse response = httpclient.execute(postMethod);

        HttpEntity entity = response.getEntity();
        if (entity != null) {
            String result = EntityUtils.toString(entity, "UTF-8");
            EntityUtils.consume(entity);
            return JSONObject.fromObject(result);
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (postMethod != null) {
            postMethod.releaseConnection();
        }
        if (httpclient != null) {
            httpclient.getConnectionManager().shutdown();
        }
    }
    return getMyError("999999", "");
}

From source file:org.jboss.as.test.clustering.cluster.ejb3.stateful.StatefulFailoverTestCase.java

@Test
public void testRedeploy(@ArquillianResource() @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1,
        @ArquillianResource() @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2)
        throws IOException, InterruptedException, URISyntaxException {

    stop(CONTAINER_2);/*from   w  w  w  .  j  a  v a  2s.co  m*/

    DefaultHttpClient client = org.jboss.as.test.http.util.HttpClientUtils.relaxedCookieHttpClient();

    String url1 = baseURL1.toString() + "count";
    String url2 = baseURL2.toString() + "count";

    try {
        assertEquals(20010101, this.queryCount(client, url1));
        assertEquals(20020202, this.queryCount(client, url1));

        start(CONTAINER_2);

        assertEquals(20030303, this.queryCount(client, url1));
        assertEquals(20040404, this.queryCount(client, url1));

        assertEquals(20050505, this.queryCount(client, url2));
        assertEquals(20060606, this.queryCount(client, url2));

        undeploy(DEPLOYMENT_2);

        assertEquals(20070707, this.queryCount(client, url1));
        assertEquals(20080808, this.queryCount(client, url1));

        deploy(DEPLOYMENT_2);

        assertEquals(20090909, this.queryCount(client, url1));
        assertEquals(20101010, this.queryCount(client, url1));

        assertEquals(20111111, this.queryCount(client, url2));
        assertEquals(20121212, this.queryCount(client, url2));

        undeploy(DEPLOYMENT_1);

        assertEquals(20131313, this.queryCount(client, url2));
        assertEquals(20141414, this.queryCount(client, url2));

        deploy(DEPLOYMENT_1);

        assertEquals(20151515, this.queryCount(client, url1));
        assertEquals(20161616, this.queryCount(client, url1));

        assertEquals(20171717, this.queryCount(client, url2));
        assertEquals(20181818, this.queryCount(client, url2));
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:com.katsu.springframework.security.authentication.dni.HttpDniAuthenticationDao.java

private Collection<? extends GrantedAuthority> doLogin(URL url, String username, String password, String dni)
        throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = null;//from   w ww. j  a va2  s .c  o m
    HttpResponse httpResponse = null;
    HttpEntity entity = null;
    try {
        httpclient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY),
                new UsernamePasswordCredentials(username, password));
        URIBuilder urib = new URIBuilder(url.toURI().toASCIIString());
        urib.addParameter("dni", dni);
        httpget = new HttpGet(urib.build());
        httpResponse = httpclient.execute(httpget);
        entity = httpResponse.getEntity();

        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            logger.trace(httpResponse.getStatusLine().toString());
            String body = new java.util.Scanner(new InputStreamReader(entity.getContent())).useDelimiter("\\A")
                    .next();
            List<? extends GrantedAuthority> roles = json.deserialize(body, new TypeToken<List<Role>>() {
            }.getType());
            if (roles != null && roles.size() > 0 && roles.get(0).getAuthority() == null) {
                roles = json.deserialize(body, new TypeToken<List<Role1>>() {
                }.getType());
            }
            return roles;
        } else {
            throw new Exception(httpResponse.getStatusLine().getStatusCode() + " Http code response.");
        }
    } catch (Exception e) {
        if (entity != null) {
            logger.error(log(entity.getContent()), e);
        } else {
            logger.error(e);
        }
        throw e;
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}