Example usage for org.apache.http.impl.client CloseableHttpClient close

List of usage examples for org.apache.http.impl.client CloseableHttpClient close

Introduction

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

Prototype

public void close() throws IOException;

Source Link

Document

Closes this stream and releases any system resources associated with it.

Usage

From source file:ok.MyService2.java

@Override
protected Task<BlockingQueue> createTask() {
    final Task<BlockingQueue> task;
    task = new Task<BlockingQueue>() {

        @Override//from  w  ww  . ja v a2  s .c om
        protected BlockingQueue call() throws Exception {
            BlockingQueue result = new LinkedBlockingQueue<String>();

            PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
            cm.setMaxTotal(100);

            CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();
            try {
                ExecutorService executor = Executors.newFixedThreadPool(sites.size());
                List<Future<String>> results = new ArrayList<Future<String>>();
                for (int i = 0; i < sites.size(); i++) {
                    HttpGet httpget = new HttpGet(sites.get(i));
                    Callable worker = new MyCallable(httpclient, httpget);
                    Future<String> res = executor.submit(worker);
                    results.add(res);
                    // String url = hostList[i];
                    //   Runnable worker = new MyRunnable(url);
                    //   executor.execute(worker);
                    //   executor.submit(null);

                }
                executor.shutdown();
                // Wait until all threads are finish
                //                   while (!executor.isTerminated()) {
                //
                //                   }
                for (Future<String> element : results) {
                    result.add(element.get());
                }
                System.out.println("\nFinished all threads");

            } finally {
                httpclient.close();
            }
            return result;
        }

    };
    return task;
}

From source file:com.linkedin.drelephant.clients.azkaban.AzkabanWorkflowClient.java

/**
 * @param username The username of the user
 * @return Encoded password of the user//from  w w  w.  j av a2  s. co  m
 * @throws IOException private String getHeadlessChallenge(String username) throws IOException {
 */

private String getHeadlessChallenge(String username) throws IOException {

    CloseableHttpClient httpClient = HttpClientBuilder.create().build(); //Use this instead
    String encodedPassword = null;

    try {
        logger.debug("Azkaban URL is " + _azkabanUrl);
        logger.debug("Username  " + username);
        String userUrl = _azkabanUrl + "/restli/liuser?action=headlessChallenge";
        HttpPost request = new HttpPost(userUrl);
        StringEntity params = new StringEntity("{\"username\":\"" + username + "\"}");
        request.addHeader("content-type", "application/json");
        request.setEntity(params);
        HttpResponse response = httpClient.execute(request);
        logger.debug("Response is " + response);
        String responseString = EntityUtils.toString(response.getEntity());
        JSONObject jobject = new JSONObject(responseString);
        encodedPassword = jobject.getString("value");
    } catch (Exception ex) {
        throw new RuntimeException("Unexpected exception in decoding headless account " + ex.toString());
    } finally {
        httpClient.close();
        return encodedPassword;
    }
}

From source file:com.envisioncn.it.super_sonic.showcase.evaluation.biz.EvaluationService.java

public String importEvaluation(List<ImportEvaPageBean> list) {
    Objects.requireNonNull(list);
    Gson gson = new Gson();
    int code = 0;
    for (ImportEvaPageBean eva : list) {
        String json = gson.toJson(eva);
        System.out.println(json);
        // httpClient.  
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // httppost    
        ///*from   w  ww  .jav a 2s.  co  m*/
        //           HttpPost httppost = new HttpPost("http://172.16.34.46:10080/Challenger/evaluation"); 
        //
        HttpPost httppost = new HttpPost("https://clg.envisioncn.com/Challenger/evaluation");
        httppost.addHeader("Content-type", "application/json; charset=utf-8");
        httppost.setHeader("Accept", "application/json");
        httppost.setEntity(new StringEntity(json, Charset.forName("UTF-8")));

        try {
            CloseableHttpResponse response = httpclient.execute(httppost);
            code = response.getStatusLine().getStatusCode();

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // ,?    
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return String.valueOf(code);

    /*   for (Evaluation evaluation : list) {
                  
          evaluationMapper.save(evaluation);
       }*/
}

From source file:com.envisioncn.it.super_sonic.showcase.evaluation.biz.EvaluationService.java

public String importAssessment(List<ImportAssPageBean> list) {
    Objects.requireNonNull(list);
    Gson gson = new Gson();
    int code = 0;
    for (ImportAssPageBean eva : list) {
        String json = gson.toJson(eva);
        System.out.println(json);
        // httpClient.  
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // httppost    
        ///*  ww  w.j ava2  s  . c  o m*/
        //           HttpPost httppost = new HttpPost("http://172.16.34.46:10080/Challenger/assessment"); 
        //
        HttpPost httppost = new HttpPost("https://clg.envisioncn.com/Challenger/assessment");
        httppost.addHeader("Content-type", "application/json; charset=utf-8");
        httppost.setHeader("Accept", "application/json");
        httppost.setEntity(new StringEntity(json, Charset.forName("UTF-8")));

        try {
            CloseableHttpResponse response = httpclient.execute(httppost);
            code = response.getStatusLine().getStatusCode();

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // ,?    
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return String.valueOf(code);
    /*   for (ImportAssPageBean assessment : list) {
            
          assessmentMapper.save(assessment);
            
       }*/
}

From source file:de.adesso.referencer.search.helper.MyHelpMethods.java

public static String sendHttpRequest(String url, String requestBody, String requestType) throws IOException {
    String result = null;/*from   w ww  . j  av  a  2  s.  c  o  m*/
    CloseableHttpClient httpclient = HttpClients.createDefault();
    CloseableHttpResponse httpResponse;
    try {
        switch (requestType) {
        case "Get":
            httpResponse = httpclient.execute(new HttpGet(url));
            break;
        case "Post":
            HttpPost httppost = new HttpPost(url);
            if (requestBody != null) {
                httppost.setEntity(new StringEntity(requestBody, DEFAULT_CHARSET));
            }
            httpResponse = httpclient.execute(httppost);
            break;
        case "Put":
            HttpPut httpPut = new HttpPut(url);
            httpPut.addHeader("Content-Type", "application/json");
            httpPut.addHeader("Accept", "application/json");
            if (requestBody != null) {
                httpPut.setEntity(new StringEntity(requestBody, DEFAULT_CHARSET));
            }
            httpResponse = httpclient.execute(httpPut);
            break;
        case "Delete":
            httpResponse = httpclient.execute(new HttpDelete(url));
            break;
        default:
            httpResponse = httpclient.execute(new HttpGet(url));
            break;
        }
        try {
            HttpEntity entity1 = httpResponse.getEntity();
            if (entity1 != null) {
                long len = entity1.getContentLength();
                if (len != -1 && len < MAX_CONTENT_LENGTH) {
                    result = EntityUtils.toString(entity1, DEFAULT_CHARSET);
                } else {
                    System.out.println("Error!!!! entity length=" + len);
                }
            }
            EntityUtils.consume(entity1);
        } finally {
            httpResponse.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        httpclient.close();
    }
    return result;
}

From source file:org.pepstock.jem.commands.util.HttpUtil.java

/**
 * Returns the job by its ID. If is not in output queue, normal <code>Object</code> is returned.
 * @param user user to authenticate//from www. ja  v a  2 s .c  om
 * @param password password to authenticate
 * @param url http URL to call
 * @param jobId jobId
 * @return Object Job instance of a normal <code>Object</code> is not ended
 * @throws SubmitException if errors occur
 */
public static Object getEndedJobByID(String user, String password, String url, String jobId)
        throws SubmitException {
    // creates a HTTP client
    CloseableHttpClient httpclient = null;
    boolean loggedIn = false;
    try {
        httpclient = createHttpClient(url);
        // prepares the entity to send via HTTP
        XStream streamer = new XStream();

        login(user, password, url, httpclient);
        loggedIn = true;
        // concats URL with query string
        String completeUrl = url + HttpUtil.ENDE_JOBID_QUERY_STRING + "?jobId=" + jobId;
        // prepares POST request and basic response handler
        HttpGet httpget = new HttpGet(completeUrl);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();

        // executes and no parsing
        // result must be only a string
        String responseBody = httpclient.execute(httpget, responseHandler);
        return streamer.fromXML(responseBody.trim());
    } catch (KeyManagementException e) {
        throw new SubmitException(SubmitMessage.JEMW004E, e);
    } catch (UnrecoverableKeyException e) {
        throw new SubmitException(SubmitMessage.JEMW004E, e);
    } catch (NoSuchAlgorithmException e) {
        throw new SubmitException(SubmitMessage.JEMW004E, e);
    } catch (KeyStoreException e) {
        throw new SubmitException(SubmitMessage.JEMW004E, e);
    } catch (URISyntaxException e) {
        throw new SubmitException(SubmitMessage.JEMW004E, e);
    } catch (ClientProtocolException e) {
        throw new SubmitException(SubmitMessage.JEMW004E, e);
    } catch (IOException e) {
        throw new SubmitException(SubmitMessage.JEMW004E, e);
    } finally {
        if (loggedIn) {
            try {
                logout(url, httpclient);
            } catch (Exception e) {
                // debug
                LogAppl.getInstance().debug(e.getMessage(), e);
            }
        }
        // close http client
        if (httpclient != null) {
            try {
                httpclient.close();
            } catch (IOException e) {
                LogAppl.getInstance().ignore(e.getMessage(), e);
            }
        }
    }
}

From source file:net.ymate.framework.commons.HttpClientHelper.java

private void __doExecHttpDownload(RequestBuilder requestBuilder, final IFileHandler handler) throws Exception {
    CloseableHttpClient _httpClient = __doBuildHttpClient();
    try {//from   w ww  . j  av a  2 s  .c  om
        _httpClient.execute(requestBuilder.build(), new ResponseHandler<Void>() {

            public Void handleResponse(HttpResponse response) throws IOException {
                String _fileName = null;
                if (response.getStatusLine().getStatusCode() == 200) {
                    if (response.containsHeader("Content-disposition")) {
                        _fileName = StringUtils.substringAfter(
                                response.getFirstHeader("Content-disposition").getValue(), "filename=");
                    }
                }
                handler.handle(response,
                        new IFileWrapper.NEW(_fileName, response.getEntity().getContentType().getValue(),
                                response.getEntity().getContentLength(),
                                new BufferedInputStream(response.getEntity().getContent())));
                return null;
            }
        });
    } finally {
        _httpClient.close();
    }
}

From source file:ng.logentries.logs.LogReader.java

public <T extends LogEntryData> List<T> readLogs(Class<? extends LogEntryData> cls, Account account,
        FilterOptions options) throws Exception {
    List<T> list = new ArrayList<>();
    LogEntryData instance = cls.newInstance();
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    try {//from   www . j ava 2s  .  co m
        URIBuilder uriBuilder = new URIBuilder().setScheme("https").setHost("pull.logentries.com/")
                .setPath(account.getAccessKey() + "/hosts/" + account.getLogSetName() + "/"
                        + account.getLogName() + "/");
        if (options.getLimit() != -1) {
            uriBuilder.addParameter("limit", "" + options.getLimit());
        }
        uriBuilder.addParameter("filter", instance.getPattern());
        if (options.getsTime() != -1) {
            uriBuilder.addParameter("start", "" + options.getsTime());
        }
        if (options.geteTime() != -1) {
            uriBuilder.addParameter("end", "" + options.geteTime());
            System.out.println(options.geteTime());
        }
        HttpGet get = new HttpGet(uriBuilder.build());
        HttpResponse httpResponse = httpClient.execute(get);
        HttpEntity entity = httpResponse.getEntity();
        Scanner in = new Scanner(entity.getContent());
        while (in.hasNext()) {
            T parse = (T) LogDataMapper.parse(in.nextLine(), cls);
            list.add(parse);
            //System.out.println(parse);
        }
    } catch (Exception e) {
        System.out.println("Error while trying to read logs: " + e);
    } finally {
        if (httpClient != null) {
            httpClient.close();
        }
    }

    return list;
}

From source file:atc.otn.ckan.client.CKANClient.java

/***
 * //from   w w w  . j  av a2 s .c om
 * @param dTankDatasetURL
 */
public boolean getDatatankTransform(String dTankDatasetURL) {

    //********************** Variables **********************

    CloseableHttpClient httpclient = HttpClients.createDefault();
    ;

    HttpGet httpGet;

    CloseableHttpResponse response = null;

    //************************ Action *************************  

    try {
        httpGet = new HttpGet(dTankDatasetURL + ".geojson");
        httpGet.setHeader("Content-Type", "application/json");
        httpGet.setHeader("Accept", "application/json");

        //call the service
        response = httpclient.execute(httpGet);
        logger.info(
                "Datatank Trnsformation Effort for: " + dTankDatasetURL + " produced " + response.toString());
        if (response.getStatusLine().getStatusCode() == 200) {
            return true;
        }

    } catch (Exception e) {
        logger.error(e.getMessage());
        return false;

    } finally {
        if (response != null) {
            try {
                response.close();
                httpclient.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                logger.error(e.getMessage());
            }
        } //end if      
    } //end finally   
    return false;
}

From source file:org.exmaralda.webservices.G2PConnector.java

public String callG2P(File bpfInFile, HashMap<String, Object> otherParameters)
        throws IOException, JDOMException {

    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    if (otherParameters != null) {
        builder.addTextBody("lng", (String) otherParameters.get("lng"));
    }/*from w ww  .j a  va 2s.c om*/

    // add the text file
    builder.addTextBody("iform", "bpf");
    builder.addBinaryBody("i", bpfInFile);

    // construct a POST request with the multipart entity
    HttpPost httpPost = new HttpPost(g2pURL);
    httpPost.setEntity(builder.build());
    HttpResponse response = httpClient.execute(httpPost);
    HttpEntity result = response.getEntity();

    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();

    if (statusCode == 200 && result != null) {
        String resultAsString = EntityUtils.toString(result);
        BASWebServiceResult basResult = new BASWebServiceResult(resultAsString);
        if (!(basResult.isSuccess())) {
            String errorText = "Call to G2P was not successful: " + resultAsString;
            throw new IOException(errorText);
        }
        String bpfOutString = basResult.getDownloadText();

        EntityUtils.consume(result);
        httpClient.close();

        return bpfOutString;
    } else {
        // something went wrong, throw an exception
        String reason = statusLine.getReasonPhrase();
        throw new IOException(reason);
    }
}