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

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

Introduction

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

Prototype

public CloseableHttpResponse execute(final HttpUriRequest request) throws IOException, ClientProtocolException 

Source Link

Usage

From source file:com.jaspersoft.studio.community.RESTCommunityHelper.java

/**
 * Tries to retrieve the content for the specified node ID.
 * /*from  www . j  av a2s.  co  m*/
 * @param httpclient
 *            the http client
 * @param nodeID
 *            the node ID
 * @param authCookie
 *            the session cookie to use for authentication purpose
 * @return the node content as JSON
 * @throws CommunityAPIException
 */
public static JsonNode retrieveNodeContentAsJSON(CloseableHttpClient httpclient, String nodeID,
        Cookie authCookie) throws CommunityAPIException {
    try {
        HttpGet retrieveNodeContentGET = new HttpGet(
                CommunityConstants.NODE_CONTENT_URL_PREFIX + nodeID + ".json"); //$NON-NLS-1$
        CloseableHttpResponse resp = httpclient.execute(retrieveNodeContentGET);
        int httpRetCode = resp.getStatusLine().getStatusCode();
        String responseBodyAsString = EntityUtils.toString(resp.getEntity());

        if (HttpStatus.SC_OK == httpRetCode) {
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
            mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
            mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
            JsonNode jsonRoot = mapper.readTree(responseBodyAsString);
            return jsonRoot;
        } else {
            CommunityAPIException ex = new CommunityAPIException(
                    Messages.RESTCommunityHelper_NodeContentRetrieveError);
            ex.setHttpStatusCode(httpRetCode);
            ex.setResponseBodyAsString(responseBodyAsString);
            throw ex;
        }
    } catch (IOException e) {
        JSSCommunityActivator.getDefault().logError(Messages.RESTCommunityHelper_GetMethodIOError, e);
        throw new CommunityAPIException(Messages.RESTCommunityHelper_NodeContentRetrieveError, e);
    }
}

From source file:gda.util.ElogEntry.java

/**
 * Creates an ELog entry. Default ELog server is "http://rdb.pri.diamond.ac.uk/devl/php/elog/cs_logentryext_bl.php"
 * which is the development database. "http://rdb.pri.diamond.ac.uk/php/elog/cs_logentryext_bl.php" is the
 * production database. The java.properties file contains the property "gda.elog.targeturl" which can be set to be
 * either the development or production databases.
 * //from   w w w  .ja  v  a  2 s .  co m
 * @param title
 *            The ELog title
 * @param content
 *            The ELog content
 * @param userID
 *            The user ID e.g. epics or gda or abc12345
 * @param visit
 *            The visit number
 * @param logID
 *            The type of log book, The log book ID: Beam Lines: - BLB16, BLB23, BLI02, BLI03, BLI04, BLI06, BLI11,
 *            BLI16, BLI18, BLI19, BLI22, BLI24, BLI15, DAG = Data Acquisition, EHC = Experimental Hall
 *            Coordinators, OM = Optics and Meteorology, OPR = Operations, E
 * @param groupID
 *            The group sending the ELog, DA = Data Acquisition, EHC = Experimental Hall Coordinators, OM = Optics
 *            and Meteorology, OPR = Operations CS = Control Systems, GroupID Can also be a beam line,
 * @param fileLocations
 *            The image file names with path to upload
 * @throws ELogEntryException
 */
public static void post(String title, String content, String userID, String visit, String logID, String groupID,
        String[] fileLocations) throws ELogEntryException {
    String targetURL = POST_UPLOAD_URL;
    try {
        String entryType = "41";// entry type is always a log (41)
        String titleForPost = visit == null ? title : "Visit: " + visit + " - " + title;

        MultipartEntityBuilder request = MultipartEntityBuilder.create().addTextBody("txtTITLE", titleForPost)
                .addTextBody("txtCONTENT", content).addTextBody("txtLOGBOOKID", logID)
                .addTextBody("txtGROUPID", groupID).addTextBody("txtENTRYTYPEID", entryType)
                .addTextBody("txtUSERID", userID);

        if (fileLocations != null) {
            for (int i = 1; i < fileLocations.length + 1; i++) {
                File targetFile = new File(fileLocations[i - 1]);
                request = request.addBinaryBody("userfile" + i, targetFile, ContentType.create("image/png"),
                        targetFile.getName());
            }
        }

        HttpEntity entity = request.build();
        targetURL = LocalProperties.get("gda.elog.targeturl", POST_UPLOAD_URL);
        HttpPost httpPost = new HttpPost(targetURL);
        httpPost.setEntity(entity);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = httpClient.execute(httpPost);

        try {
            String responseString = EntityUtils.toString(response.getEntity());
            System.out.println(responseString);
            if (!responseString.contains("New Log Entry ID")) {
                throw new ELogEntryException("Upload failed, status=" + response.getStatusLine().getStatusCode()
                        + " response=" + responseString + " targetURL = " + targetURL + " titleForPost = "
                        + titleForPost + " logID = " + logID + " groupID = " + groupID + " entryType = "
                        + entryType + " userID = " + userID);
            }
        } finally {
            response.close();
            httpClient.close();
        }
    } catch (ELogEntryException e) {
        throw e;
    } catch (Exception e) {
        throw new ELogEntryException("Error in ELogger.  Database:" + targetURL, e);
    }
}

From source file:lh.api.showcase.server.util.HttpQueryUtils.java

public static String executeQuery(URI uri, ApiAuth apiAuth, HasProxySettings proxySetting,
        HttpClientFactory httpClientFactory, final int maxRetries) throws HttpErrorResponseException {

    //logger.info("uri: " + uri.toString());

    AtomicInteger tryCounter = new AtomicInteger(0);
    while (true) {

        CloseableHttpClient httpclient = httpClientFactory.getHttpClient(proxySetting);
        HttpGet httpGet = new HttpGet(uri);
        httpGet.addHeader("Authorization", apiAuth.getAuthHeader());
        httpGet.addHeader("Accept", "application/json");

        //logger.info("auth: " + apiAuth.getAuthHeader()) ;
        //logger.info("query: " + httpGet.toString());

        CloseableHttpResponse response = null;
        try {/*from ww w . j  av  a 2 s .  co m*/
            response = httpclient.execute(httpGet);
            StatusLine status = response.getStatusLine();
            BufferedHttpEntity entity = new BufferedHttpEntity(response.getEntity());
            String json = IOUtils.toString(entity.getContent(), "UTF8");
            EntityUtils.consume(entity);
            //logger.info("response: " + json);

            // check for errors
            if (status != null && status.getStatusCode() > 299) {
                if (status.getStatusCode() == 401) {
                    // token has probably expired
                    logger.info("Authentication Error. Token will be refreshed");
                    if (tryCounter.getAndIncrement() < maxRetries) {
                        if (apiAuth.updateAccessToken()) {
                            logger.info("Token successfully refreshed");
                            // we retry with the new token
                            logger.info("Retry number " + tryCounter.get());
                            continue;
                        }
                    }
                }
                throw new HttpErrorResponseException(status.getStatusCode(), status.getReasonPhrase(), json);
            }
            return json;
        } catch (IOException e) {
            logger.severe(e.getMessage());
            break;
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                logger.log(Level.SEVERE, e.getMessage());
            }
        }
    }
    return null;
}

From source file:org.wuspba.ctams.ws.ITHiredJudgeController.java

protected static void delete() throws Exception {
    List<String> ids = new ArrayList<>();

    CloseableHttpClient httpclient = HttpClients.createDefault();

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build();

    HttpGet httpGet = new HttpGet(uri);

    try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
        assertEquals(response.getStatusLine().toString(), IntegrationTestUtils.OK_STRING);

        HttpEntity entity = response.getEntity();

        CTAMSDocument doc = IntegrationTestUtils.convertEntity(entity);

        for (HiredJudge j : doc.getHiredJudges()) {
            ids.add(j.getId());// w w  w  .ja v  a2 s  .  c  o  m
        }

        EntityUtils.consume(entity);
    }

    for (String id : ids) {
        httpclient = HttpClients.createDefault();

        uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH)
                .setParameter("id", id).build();

        HttpDelete httpDelete = new HttpDelete(uri);

        CloseableHttpResponse response = null;

        try {
            response = httpclient.execute(httpDelete);

            assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString());

            HttpEntity responseEntity = response.getEntity();

            EntityUtils.consume(responseEntity);
        } catch (UnsupportedEncodingException ex) {
            LOG.error("Unsupported coding", ex);
        } catch (IOException ioex) {
            LOG.error("IOException", ioex);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException ex) {
                    LOG.error("Could not close response", ex);
                }
            }
        }
    }

    ITJudgeController.delete();
}

From source file:de.l3s.boilerpipe.sax.HTMLFetcher.java

public static HTMLDocument fetch(final String url) throws IOException {
    //DefaultHttpClient httpclient = new DefaultHttpClient();
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet request = new HttpGet(url.toString());
    request.setHeader("User-Agent",
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.104 Safari/537.36");
    request.setHeader("Referer", "http://www.google.com");

    HttpResponse response = httpclient.execute(request);
    HttpEntity entity = response.getEntity();
    //System.out.println("Response Code: " +
    //response.getStatusLine().getStatusCode());
    ContentType contentType = ContentType.getOrDefault(entity);
    Charset charset = contentType.getCharset();
    if (charset == null) {
        charset = Charset.forName("gb2312");
    }/*from w  w w.j a va  2 s.co m*/

    BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent(), charset));

    StringBuilder builder = new StringBuilder();
    String aux = "";
    Charset cs = Charset.forName("utf8");
    boolean charsetFlag = false;
    while ((aux = rd.readLine()) != null) {
        if (aux != null && !charsetFlag && (aux.contains("http-equiv") || !aux.contains("src"))) {
            Matcher m = PAT_CHARSET_REX.matcher(aux);
            if (m.find()) {
                final String cName = m.group(1);
                charsetFlag = true;
                try {
                    cs = Charset.forName(cName);
                    break;
                } catch (UnsupportedCharsetException e) {
                    // keep default
                }
            }
        }
        //builder.append(aux);
        //System.out.println(builder.toString());
    }

    HttpGet request2 = new HttpGet(url.toString());
    request2.setHeader("User-Agent",
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.104 Safari/537.36");
    request2.setHeader("Referer", "http://www.google.com");

    HttpResponse response2 = httpclient.execute(request2);
    HttpEntity entity2 = response2.getEntity();
    contentType = ContentType.getOrDefault(entity2);
    charset = contentType.getCharset();
    if (charset == null)
        charset = cs;
    //if(charset.name().toLowerCase().equals("gb2312"))
    //   charset = Charset.forName("gbk");
    BufferedReader rd2 = new BufferedReader(new InputStreamReader(entity2.getContent(), charset));
    while ((aux = rd2.readLine()) != null) {
        builder.append(aux);
        //System.out.println(builder.toString());
    }

    String text = builder.toString();
    //System.out.println(text);
    rd.close();
    rd2.close();
    return new HTMLDocument(text, cs); //sometimes cs not equal to charset
}

From source file:org.cloudsimulator.utility.RestAPI.java

private static CloseableHttpResponse putRequestBasicAuth(final CloseableHttpClient httpClient, final String uri,
        final String username, final String password, final String contentType, final HttpEntity entityToSend)
        throws IOException {
    HttpPut httpPut = new HttpPut(uri);
    httpPut.addHeader(CONTENTTYPE, contentType);
    httpPut.addHeader(AUTHORIZATION, getBasicAuth(username, password));
    httpPut.setEntity(entityToSend);/*from w w w . jav a2  s  .co m*/
    return httpClient.execute(httpPut);
}

From source file:com.glaf.core.util.http.HttpClientUtils.java

public static String doPost(String url, String data, String contentType, String encoding) {
    StringBuffer buffer = new StringBuffer();
    InputStreamReader is = null;/*www  .  ja va2 s.  c om*/
    BufferedReader reader = null;
    BasicCookieStore cookieStore = new BasicCookieStore();
    HttpClientBuilder builder = HttpClientBuilder.create();
    CloseableHttpClient client = builder.setDefaultCookieStore(cookieStore).build();
    try {
        HttpPost post = new HttpPost(url);
        if (data != null) {
            StringEntity entity = new StringEntity(data, encoding);
            post.setHeader("Content-Type", contentType);
            post.setEntity(entity);
        }
        HttpResponse response = client.execute(post);
        HttpEntity entity = response.getEntity();
        is = new InputStreamReader(entity.getContent(), encoding);
        reader = new BufferedReader(is);
        String tmp = reader.readLine();
        while (tmp != null) {
            buffer.append(tmp);
            tmp = reader.readLine();
        }
    } catch (IOException ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    } finally {
        IOUtils.closeStream(reader);
        IOUtils.closeStream(is);
        try {
            client.close();
        } catch (IOException ex) {
        }
    }
    return buffer.toString();
}

From source file:org.everit.osgi.authentication.cas.tests.SampleApp.java

public static void pingCasLoginUrl(final BundleContext bundleContext) throws Exception {
    CloseableHttpClient httpClient = new SecureHttpClient(null, bundleContext).getHttpClient();

    HttpGet httpGet = new HttpGet(CAS_LOGIN_URL + "?" + LOCALE);
    HttpResponse httpResponse = null;/*from  w w  w. ja va2s . co  m*/
    try {
        httpResponse = httpClient.execute(httpGet);
        Assert.assertEquals(CAS_PING_FAILURE_MESSAGE, HttpServletResponse.SC_OK,
                httpResponse.getStatusLine().getStatusCode());
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail(CAS_PING_FAILURE_MESSAGE);
    } finally {
        if (httpResponse != null) {
            EntityUtils.consume(httpResponse.getEntity());
        }
        httpClient.close();
    }
}

From source file:org.wuspba.ctams.ws.ITBandMemberController.java

protected static void delete() throws Exception {
    List<String> ids = new ArrayList<>();

    CloseableHttpClient httpclient = HttpClients.createDefault();

    URI uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH).build();

    HttpGet httpGet = new HttpGet(uri);

    try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
        assertEquals(response.getStatusLine().toString(), IntegrationTestUtils.OK_STRING);

        HttpEntity entity = response.getEntity();

        CTAMSDocument doc = IntegrationTestUtils.convertEntity(entity);

        for (BandMember m : doc.getBandMembers()) {
            ids.add(m.getId());/*from w  w  w  .  jav a2 s .co  m*/
        }

        EntityUtils.consume(entity);
    }

    for (String id : ids) {
        httpclient = HttpClients.createDefault();

        uri = new URIBuilder().setScheme(PROTOCOL).setHost(HOST).setPort(PORT).setPath(PATH)
                .setParameter("id", id).build();

        HttpDelete httpDelete = new HttpDelete(uri);

        CloseableHttpResponse response = null;

        try {
            response = httpclient.execute(httpDelete);

            assertEquals(IntegrationTestUtils.OK_STRING, response.getStatusLine().toString());

            HttpEntity responseEntity = response.getEntity();

            EntityUtils.consume(responseEntity);
        } catch (UnsupportedEncodingException ex) {
            LOG.error("Unsupported coding", ex);
        } catch (IOException ioex) {
            LOG.error("IOException", ioex);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException ex) {
                    LOG.error("Could not close response", ex);
                }
            }
        }
    }

    ITPersonController.delete();
}

From source file:eu.citadel.converter.io.index.CitadelIndexUtil.java

/**
 * Index an uploaded file//from w  ww.  ja va  2  s  . c om
 * @param config Index publish configuration
 * @param datasetFile File name of file stored in the dataset
 * @return The response string
 * @throws ClientProtocolException
 * @throws IOException
 */
private static String saveToIndex(CitadelIndexConfig config, String datasetFile)
        throws ClientProtocolException, IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost request = new HttpPost(config.getSaveIndexUrl());

    ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
    postParameters.add(new BasicNameValuePair(REQUEST_PARAM_DATASET_INFO, generateJson(config, datasetFile)));
    request.setEntity(new UrlEncodedFormEntity(postParameters));

    CloseableHttpResponse response = httpclient.execute(request);
    return EntityUtils.toString(response.getEntity());

}