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.picketlink.test.trust.servlet.GatewayServlet.java

private void forwardCall(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    String serviceServerUrl = req.getParameter(SERVICE_SERVER_URL);
    if (serviceServerUrl == null) {
        serviceServerUrl = "http://localhost:8080/service/incoming";
    }/*www.  java  2  s .  c  om*/
    log.debug("serviceServerUrl=" + serviceServerUrl);

    String sCompress = req.getParameter(TOKEN_COMPRESSION_PARAM);
    boolean compress = Boolean.parseBoolean(sCompress);
    log.debug("compress=" + compress);

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
        HttpGet httpget = new HttpGet(serviceServerUrl);
        String samlToken = getSamlToken().getAssertionAsString();
        log.debug("samlToken from subject=" + samlToken);
        int options = Base64.NO_OPTIONS;
        if (compress) {
            options = Base64.GZIP;
        }

        String encodedToken = Base64.encodeBytes(samlToken.getBytes(), options | Base64.DONT_BREAK_LINES);
        log.debug("encodedToken=" + encodedToken);

        httpget.addHeader(AUTH_HEADER, "token=\"" + encodedToken + "\"");
        HttpResponse response = httpclient.execute(httpget);
        log.debug("Httpget: " + httpget.toString());
        log.debug("Response: " + response.getStatusLine());
        HttpEntity entity = response.getEntity();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        entity.writeTo(baos);
        baos.close();
        resp.getOutputStream().write(baos.toByteArray());

    } catch (Exception e) {
        e.printStackTrace(resp.getWriter());
    } finally {
        httpclient.getConnectionManager().shutdown();
    }

}

From source file:jp.canetrash.maven.plugin.bijint.BujintMojo.java

/**
 * @param image//ww  w  .  ja v  a 2s  .  co m
 * @return
 * @throws IOException
 * @throws ClientProtocolException
 * @throws UnsupportedEncodingException
 */
private String getAsciiArt(BufferedImage image)
        throws IOException, ClientProtocolException, UnsupportedEncodingException {
    File tmpfile = File.createTempFile("bjint_", ".jpg");
    ImageIO.write(image, "jpg", tmpfile);

    // http://picascii.com/????
    // ?????
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet("http://picascii.com/");
    HttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();
    entity.consumeContent();

    // ???
    HttpPost httppost = new HttpPost("http://picascii.com/upload.php");
    //HttpPost httppost = buildDefaultHttpMessage(new HttpPost("http://localhost:8080/sa-struts-tutorial/upload/"));

    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    FileBody bin = new FileBody(tmpfile, "image/jpeg");
    reqEntity.addPart("imageupload", bin);
    reqEntity.addPart("MAX_FILE_SIZE", new StringBody("1000000"));
    reqEntity.addPart("url", new StringBody(""));
    reqEntity.addPart("quality", new StringBody("3"));
    reqEntity.addPart("size", new StringBody("1"));

    httppost.setEntity(reqEntity);

    response = httpclient.execute(httppost);
    String responseHtml = IOUtils.toString(response.getEntity().getContent());

    httpclient.getConnectionManager().shutdown();

    // tmpFile?
    tmpfile.delete();
    return bringOutAsciiArtString(responseHtml);
}

From source file:test.gov.nih.nci.cacoresdk.domain.operations.SpecimenResourceTest.java

public void testPut() throws Exception {

    try {/*from  ww w.  jav  a2  s .  co  m*/
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String url = baseURL + "/rest/Specimen";
        HttpPut putRequest = new HttpPut(url);
        File myFile = new File("Specimen" + "XML.xml");
        if (!myFile.exists()) {
            testGet();
            myFile = new File("Specimen" + "XML.xml");
            if (!myFile.exists())
                return;
        }

        FileEntity input = new FileEntity(myFile);
        input.setContentType("application/xml");
        putRequest.setEntity(input);

        HttpResponse response = httpClient.execute(putRequest);

        if (response.getEntity() != null) {
            BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

            String output;
            System.out.println("Output from Server .... \n");
            while ((output = br.readLine()) != null) {
                System.out.println(output);
            }
        }

        httpClient.getConnectionManager().shutdown();
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }

}

From source file:test.gov.nih.nci.cacoresdk.domain.operations.ChildTestResourceTest.java

public void testPut() throws Exception {

    try {// ww  w  . j  a va2  s.  c  om
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String url = baseURL + "/rest/ChildTest";
        HttpPut putRequest = new HttpPut(url);
        File myFile = new File("ChildTest" + "XML.xml");
        if (!myFile.exists()) {
            testGet();
            myFile = new File("ChildTest" + "XML.xml");
            if (!myFile.exists())
                return;
        }

        FileEntity input = new FileEntity(myFile);
        input.setContentType("application/xml");
        putRequest.setEntity(input);

        HttpResponse response = httpClient.execute(putRequest);

        if (response.getEntity() != null) {
            BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

            String output;
            System.out.println("Output from Server .... \n");
            while ((output = br.readLine()) != null) {
                System.out.println(output);
            }
        }

        httpClient.getConnectionManager().shutdown();
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }

}

From source file:org.jboss.as.test.clustering.cluster.web.ClusteredWebTestCase.java

@Test
@OperateOnDeployment("deployment-0")
public void testSerialized(@ArquillianResource(SimpleServlet.class) URL baseURL)
        throws ClientProtocolException, IOException {
    DefaultHttpClient client = new DefaultHttpClient();

    // returns the URL of the deployment (http://127.0.0.1:8180/distributable)
    String url = baseURL.toString();
    System.out.println("URL = " + url);

    try {/*from  w w w  . j  av  a 2s. c  om*/
        HttpResponse response = client.execute(new HttpGet(url + "simple"));
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Assert.assertEquals(1, Integer.parseInt(response.getFirstHeader("value").getValue()));
        Assert.assertFalse(Boolean.valueOf(response.getFirstHeader("serialized").getValue()));
        response.getEntity().getContent().close();

        response = client.execute(new HttpGet(url + "simple"));
        Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
        Assert.assertEquals(2, Integer.parseInt(response.getFirstHeader("value").getValue()));
        // This won't be true unless we have somewhere to which to replicate
        Assert.assertTrue(Boolean.valueOf(response.getFirstHeader("serialized").getValue()));
        response.getEntity().getContent().close();
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:eu.juniper.MonitoringLib.java

/**
 * @param appDescription Description of the application to be sent
 * @param userName User name to be sent/*from  www .  j av  a 2  s . c om*/
 * @param hostname Host name of the application to be sent
 * @return Response of the REST POST method, represented as String
 * @throws ParseException
 */
public String registerApplication(String appDescription, String userName, String hostname)
        throws ParseException {
    String responseString = "";
    String resource = monitoringServiceURL;

    long milis = System.currentTimeMillis();
    long seconds = System.currentTimeMillis() / 1000;
    String curTime = "" + seconds + "." + (milis - seconds * 1000) * 10000;
    String requestString = "{ \"Start_date\": " + curTime + ",  \"Username\": \"" + userName
            + "\",  \"Hostname\": \"" + hostname + "\",  \"Description\": \"" + appDescription + "\"  }  ";
    System.out.println("Registering application: " + requestString);

    try {
        DefaultHttpClient httpclient = new DefaultHttpClient();

        HttpPost httpPost = new HttpPost(resource);

        System.out.println("executing POST request:\n" + httpPost.getRequestLine());

        httpPost.addHeader("content-type", "application/json");
        httpPost.addHeader("Accept", "application/json");
        StringEntity params = new StringEntity(requestString);
        httpPost.setEntity(params);

        HttpResponse response;
        response = httpclient.execute(httpPost);
        HttpEntity responseEntity = response.getEntity();

        if (responseEntity != null) {
            System.out.println("Response content length: " + responseEntity.getContentLength());
        }

        responseString = EntityUtils.toString(responseEntity);

        System.out.println(responseString);
        httpclient.getConnectionManager().shutdown();

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return responseString;
}

From source file:org.talend.librariesmanager.deploy.ArtifactsDeployer.java

private void installToRemote(HttpEntity entity, URL targetURL) throws BusinessException {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    try {/*from   w  w  w.  j  ava2s .co  m*/
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(targetURL.getHost(), targetURL.getPort()),
                new UsernamePasswordCredentials(nexusServer.getUserName(), nexusServer.getPassword()));

        HttpPut httpPut = new HttpPut(targetURL.toString());
        httpPut.setEntity(entity);
        HttpResponse response = httpClient.execute(httpPut);
        StatusLine statusLine = response.getStatusLine();
        int responseCode = statusLine.getStatusCode();
        EntityUtils.consume(entity);
        if (responseCode > 399) {
            if (responseCode == 401) {
                throw new BusinessException("Authrity failed");
            } else {
                throw new BusinessException(
                        "Deploy failed: " + responseCode + ' ' + statusLine.getReasonPhrase());
            }
        }
    } catch (Exception e) {
        throw new BusinessException("softwareupdate.error.cannotupload", e.getMessage());
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:test.gov.nih.nci.cacoresdk.domain.operations.SiteResourceTest.java

public void testPost() throws Exception {

    try {/*from  w  w w  .java2s .c  o  m*/
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String url = baseURL + "/rest/Site";
        WebClient client = WebClient.create(url);
        HttpPost postRequest = new HttpPost(url);
        File myFile = new File("Site" + "XML.xml");
        if (!myFile.exists()) {
            testGet();
            myFile = new File("Site" + "XML.xml");
            if (!myFile.exists())
                return;
        }

        FileEntity input = new FileEntity(myFile);
        input.setContentType("application/xml");
        System.out.println("input: " + myFile);
        postRequest.setEntity(input);

        HttpResponse response = httpClient.execute(postRequest);

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }

        httpClient.getConnectionManager().shutdown();
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }

}

From source file:org.picketbox.test.authentication.http.jetty.DelegatingSecurityFilterHTTPBasicUnitTestCase.java

@Test
public void testBasicAuth() throws Exception {
    URL url = new URL(urlStr);

    DefaultHttpClient httpclient = null;
    try {/*from   w w  w  .  jav  a  2  s . c  o  m*/
        String user = "Aladdin";
        String pass = "Open Sesame";

        httpclient = new DefaultHttpClient();
        httpclient.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()),
                new UsernamePasswordCredentials(user, pass));

        HttpGet httpget = new HttpGet(url.toExternalForm());

        System.out.println("executing request" + httpget.getRequestLine());
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        StatusLine statusLine = response.getStatusLine();
        System.out.println(statusLine);
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        assertEquals(200, statusLine.getStatusCode());
        EntityUtils.consume(entity);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:DesignGUI.java

private void bt_searchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_searchActionPerformed
    // StackExchangeAPI stack = new StackExchangeAPI();       
    String search = this.lb_qusetion.getText();
    search = search.replaceAll(" ", "%20");
    this.cb_Site.getItemListeners();

    String url = "https://api.stackexchange.com/2.2/search/advanced?order=desc&sort=activity&accepted=True&title="
            + search + "&site=stackoverflow&filter=withbody";
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet getRequest = new HttpGet(url);
    HttpResponse httpResponse;//  w  w w.  j  a v  a  2s  .  c o m
    try {
        httpResponse = httpclient.execute(getRequest);
        HttpEntity entity = httpResponse.getEntity();
        System.out.println("----------------------------------------");
        System.out.println(httpResponse.getStatusLine());
        Header[] headers = httpResponse.getAllHeaders();
        for (int i = 0; i < headers.length; i++) {
            System.out.println(headers[i]);
        }
        System.out.println("----------------------------------------");
        if (entity != null) {
            entity = new GzipDecompressingEntity(entity);
            String jsonStr = EntityUtils.toString(entity);
            //  System.out.println(jsonStr);
            parseStackExchange(jsonStr);
        } else {
            System.out.println("NOTHING");
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        httpclient.getConnectionManager().shutdown();
    }

}