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:utils.APIImporter.java

/**
 * Updated an existing API/*ww w .jav  a 2  s .  c o m*/
 * @param payload payload to update the API
 * @param apiId API id of the updating API (provider-name-version)
 * @param token access token
 * @param folderPath folder path to the imported API folder
 */
private static void updateApi(String payload, String apiId, String token, String folderPath)
        throws APIImportException {
    String url = config.getPublisherUrl() + "apis/" + apiId;
    CloseableHttpClient client = HttpClientGenerator.getHttpClient(config.getCheckSSLCertificate());
    HttpPut request = new HttpPut(url);
    request.setEntity(new StringEntity(payload, ImportExportConstants.CHARSET));
    request.setHeader(HttpHeaders.AUTHORIZATION, ImportExportConstants.CONSUMER_KEY_SEGMENT + " " + token);
    request.setHeader(HttpHeaders.CONTENT_TYPE, ImportExportConstants.CONTENT_JSON);
    try {
        CloseableHttpResponse response = client.execute(request);
        if (response.getStatusLine().getStatusCode() == Response.Status.OK.getStatusCode()) {
            //getting API uuid
            String responseString = EntityUtils.toString(response.getEntity());
            String uuid = ImportExportUtils.readJsonValues(responseString, ImportExportConstants.UUID);
            updateAPIDocumentation(uuid, apiId, token, folderPath);
            addAPIImage(folderPath, token, uuid);
            System.out.println("API " + apiId + " updated successfully");
        } else {
            String status = response.getStatusLine().toString();
            log.error(status);
            System.out.println(apiId + " update unsuccessful");
        }
    } catch (IOException e) {
        errorMsg = "Error occurred while updating, API " + apiId;
        log.error(errorMsg, e);
        throw new APIImportException(errorMsg, e);
    }
}

From source file:com.farsunset.cim.util.MessageDispatcher.java

private static String httpPost(String url, Message msg) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);

    List<NameValuePair> nvps = new ArrayList<NameValuePair>();

    nvps.add(new BasicNameValuePair("mid", msg.getMid()));
    nvps.add(new BasicNameValuePair("extra", msg.getExtra()));
    nvps.add(new BasicNameValuePair("action", msg.getAction()));
    nvps.add(new BasicNameValuePair("title", msg.getTitle()));
    nvps.add(new BasicNameValuePair("content", msg.getContent()));
    nvps.add(new BasicNameValuePair("sender", msg.getSender()));
    nvps.add(new BasicNameValuePair("receiver", msg.getReceiver()));
    nvps.add(new BasicNameValuePair("timestamp", String.valueOf(msg.getTimestamp())));

    httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
    CloseableHttpResponse response2 = httpclient.execute(httpPost);
    String data = null;/*from www  . j a  va  2  s. c  o m*/
    try {
        System.out.println(response2.getStatusLine());
        HttpEntity entity2 = response2.getEntity();
        data = EntityUtils.toString(entity2);
    } finally {
        response2.close();
    }

    return data;
}

From source file:utils.APIExporter.java

/**
 *write API documents in to the zip file
 * @param uuid APIId/*  ww w .  j av  a  2  s  .c o  m*/
 * @param documentaionSummary resultant string from the getAPIDocuments
 *@param accessToken token with scope apim:api_view
 */
private static void exportAPIDocumentation(String uuid, String documentaionSummary, String accessToken,
        String archivePath) {
    System.out.println("                  access token " + accessToken);
    OutputStream outputStream = null;
    ApiImportExportConfiguration config = ApiImportExportConfiguration.getInstance();
    //create directory to hold API documents
    String documentFolderPath = archivePath.concat(File.separator + "docs");
    ImportExportUtils.createDirectory(documentFolderPath);

    try {
        //writing API documents to the zip folder
        Object json = mapper.readValue(documentaionSummary, Object.class);
        String formattedJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
        writeFile(documentFolderPath + File.separator + "docs.json", formattedJson);

        //convert documentation summary to json object
        JSONObject jsonObj = (JSONObject) parser.parse(documentaionSummary);
        if (jsonObj.containsKey("list")) {
            org.json.simple.JSONArray arr = (org.json.simple.JSONArray) jsonObj
                    .get(ImportExportConstants.DOC_LIST);
            // traverse through each document
            for (Object anArr : arr) {
                JSONObject document = (JSONObject) anArr;
                //getting document source type (inline/url/file)
                String sourceType = (String) document.get(ImportExportConstants.SOURCE_TYPE);
                if (ImportExportConstants.FILE_DOC_TYPE.equalsIgnoreCase(sourceType)
                        || ImportExportConstants.INLINE_DOC_TYPE.equalsIgnoreCase(sourceType)) {
                    //getting documentId
                    String documentId = (String) document.get(ImportExportConstants.DOC_ID);
                    //REST API call to get document contents
                    String url = config.getPublisherUrl() + "apis/" + uuid + "/documents/" + documentId
                            + "/content";
                    CloseableHttpClient client = HttpClientGenerator
                            .getHttpClient(config.getCheckSSLCertificate());
                    HttpGet request = new HttpGet(url);
                    request.setHeader(HttpHeaders.AUTHORIZATION,
                            ImportExportConstants.CONSUMER_KEY_SEGMENT + " " + accessToken);
                    HttpResponse response = client.execute(request);
                    HttpEntity entity = response.getEntity();

                    if (ImportExportConstants.FILE_DOC_TYPE.equalsIgnoreCase(sourceType)) {
                        //creating directory to hold FILE type content
                        String filetypeFolderPath = documentFolderPath
                                .concat(File.separator + ImportExportConstants.FILE_DOCUMENT_DIRECTORY);
                        ImportExportUtils.createDirectory(filetypeFolderPath);

                        //writing file type content in to the zip folder
                        String localFilePath = filetypeFolderPath + File.separator
                                + document.get(ImportExportConstants.DOC_NAME);
                        try {
                            outputStream = new FileOutputStream(localFilePath);
                            entity.writeTo(outputStream);
                        } finally {
                            try {
                                assert outputStream != null;
                                outputStream.close();
                            } catch (IOException e) {
                                log.warn("Error occurred while closing the streams");
                            }
                        }
                    } else {
                        //create directory to hold inline contents
                        String inlineFolderPath = documentFolderPath
                                .concat(File.separator + ImportExportConstants.INLINE_DOCUMENT_DIRECTORY);
                        ImportExportUtils.createDirectory(inlineFolderPath);

                        //writing inline content in to the zip folder
                        InputStream inlineStream = null;
                        try {
                            String localFilePath = inlineFolderPath + File.separator
                                    + document.get(ImportExportConstants.DOC_NAME);
                            outputStream = new FileOutputStream(localFilePath);
                            entity.writeTo(outputStream);
                        } finally {
                            try {
                                if (inlineStream != null) {
                                    inlineStream.close();
                                }
                                if (outputStream != null) {
                                    outputStream.close();
                                }
                            } catch (IOException e) {
                                log.warn("Error occure while closing the streams");
                            }
                        }
                    }

                }
            }
        }
    } catch (ParseException e) {
        log.error("Error occurred while getting API documents");
    } catch (IOException e) {
        log.error("Error occured while writing getting API documents");
    }
}

From source file:org.dashbuilder.dataprovider.backend.elasticsearch.ElasticSearchDataSetTestBase.java

public static void createIndexELServer() throws Exception {

    // Create an http client
    CloseableHttpClient httpclient = HttpClients.createDefault();

    // Obtain data to configure & populate the server.
    String mappingsContent = getFileAsString(EL_EXAMPLE_MAPPINGS);

    // Create an index mappings.
    HttpPost httpPost = new HttpPost(urlBuilder.getIndexRoot());
    StringEntity inputMappings = new StringEntity(mappingsContent);
    inputMappings.setContentType(CONTENTTYPE_JSON);
    httpPost.setEntity(inputMappings);/*  w ww  .  j av  a  2s.  c  om*/
    CloseableHttpResponse mappingsResponse = httpclient.execute(httpPost);
    if (mappingsResponse.getStatusLine().getStatusCode() != EL_REST_RESPONSE_OK) {
        System.out.println("Error response body:");
        System.out.println(responseAsString(mappingsResponse));
    }
    Assert.assertEquals(EL_REST_RESPONSE_OK, mappingsResponse.getStatusLine().getStatusCode());
}

From source file:org.wso2.mdm.qsg.utils.HTTPInvoker.java

public static HTTPResponse sendHTTPPutWithOAuthSecurity(String url, String payload,
        HashMap<String, String> headers) {
    HttpPut put = null;//  w w  w  . j  a v  a2  s.c o m
    HttpResponse response = null;
    HTTPResponse httpResponse = new HTTPResponse();
    CloseableHttpClient httpclient = null;
    try {
        httpclient = (CloseableHttpClient) createHttpClient();
        StringEntity requestEntity = new StringEntity(payload, Constants.UTF_8);
        put = new HttpPut(url);
        put.setEntity(requestEntity);
        for (String key : headers.keySet()) {
            put.setHeader(key, headers.get(key));
        }
        put.setHeader(Constants.Header.AUTH, OAUTH_BEARER + oAuthToken);
        response = httpclient.execute(put);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }

    BufferedReader rd = null;
    try {
        rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    } catch (IOException e) {
        e.printStackTrace();
    }

    StringBuffer result = new StringBuffer();
    String line = "";
    try {
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    httpResponse.setResponseCode(response.getStatusLine().getStatusCode());
    httpResponse.setResponse(result.toString());
    try {
        httpclient.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return httpResponse;
}

From source file:org.wso2.mdm.qsg.utils.HTTPInvoker.java

public static HTTPResponse sendHTTPPostWithOAuthSecurity(String url, String payload,
        HashMap<String, String> headers) {
    HttpPost post = null;// w ww  .j  av a 2 s .c  o m
    HttpResponse response = null;
    HTTPResponse httpResponse = new HTTPResponse();
    CloseableHttpClient httpclient = null;
    try {
        httpclient = (CloseableHttpClient) createHttpClient();
        StringEntity requestEntity = new StringEntity(payload, Constants.UTF_8);
        post = new HttpPost(url);
        post.setEntity(requestEntity);
        for (String key : headers.keySet()) {
            post.setHeader(key, headers.get(key));
        }

        post.setHeader(Constants.Header.AUTH, OAUTH_BEARER + oAuthToken);
        response = httpclient.execute(post);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }

    BufferedReader rd = null;
    try {
        rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    } catch (IOException e) {
        e.printStackTrace();
    }

    StringBuffer result = new StringBuffer();
    String line = "";
    try {
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    httpResponse.setResponseCode(response.getStatusLine().getStatusCode());
    httpResponse.setResponse(result.toString());
    try {
        httpclient.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return httpResponse;
}

From source file:utils.APIExporter.java

/**
 * generate a archive of exporting API/*w  ww  .j a  v a 2  s.c om*/
 * @param apiName name of the API
 * @param provider provider of the API
 * @param version version of the API
 * @param accessToken valid access token
 */
private static void exportAPI(String destinationLocation, String apiName, String provider, String version,
        String accessToken) throws APIExportException {

    ApiImportExportConfiguration config = ApiImportExportConfiguration.getInstance();

    //creating a directory to hold API details
    String APIFolderPath = destinationLocation.concat(File.separator + apiName + "-" + version);
    ImportExportUtils.createDirectory(APIFolderPath);

    //building the API id
    String apiId = provider + "-" + apiName + "-" + version;
    String responseString;
    try {
        //getting API meta- information
        CloseableHttpClient client = HttpClientGenerator.getHttpClient(config.getCheckSSLCertificate());
        String metaInfoUrl = config.getPublisherUrl() + "apis/" + apiId;
        HttpGet request = new HttpGet(metaInfoUrl);
        request.setHeader(javax.ws.rs.core.HttpHeaders.AUTHORIZATION,
                ImportExportConstants.CONSUMER_KEY_SEGMENT + " " + accessToken);
        CloseableHttpResponse response = client.execute(request);
        if (response.getStatusLine().getStatusCode() == 404) { ////// TODO: 8/24/16 int value constant 
            String message = "API " + apiId + "does not exist/ not found ";
            log.warn(message);
            return;
        }
        HttpEntity entity = response.getEntity();
        responseString = EntityUtils.toString(entity, ImportExportConstants.CHARSET);
    } catch (IOException e) {
        String errorMsg = "Error occurred while retrieving the API meta information";
        log.error(errorMsg, e);
        throw new APIExportException(errorMsg, e);
    }
    //creating directory to hold meta-information
    String metaInfoFolderPath = APIFolderPath.concat(File.separator + "meta-information");
    ImportExportUtils.createDirectory(metaInfoFolderPath);

    //set API status and scope before exporting
    setJsonValues(responseString, ImportExportConstants.STATUS_CONSTANT, ImportExportConstants.CREATED);
    setJsonValues(responseString, ImportExportConstants.SCOPE_CONSTANT, null);

    try {
        //writing meta-information
        Object json = mapper.readValue(responseString, Object.class);
        String formattedJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
        writeFile(metaInfoFolderPath + File.separator + "api.json", formattedJson);
    } catch (IOException e) {
        String error = "Error occurred while formatting the json string";
        log.error(error, e);
        throw new APIExportException(error, e);
    }

    JSONObject jsonObj = null;
    try {
        jsonObj = (JSONObject) parser.parse(responseString);
        String swagger = (String) jsonObj.get(ImportExportConstants.SWAGGER);
        writeFile(metaInfoFolderPath + File.separator + "swagger.json", swagger);
    } catch (ParseException e) {
        log.error("error occurred while getting swagger definision");
    }
    //get API uuid
    String uuid = null;
    if (jsonObj != null) {
        uuid = (String) jsonObj.get(ImportExportConstants.UUID);
    }

    //export api thumbnail
    String thumbnailUrl = null;
    if (jsonObj != null) {
        thumbnailUrl = (String) jsonObj.get(ImportExportConstants.THUMBNAIL);
    }
    if (thumbnailUrl != null) {
        exportAPIThumbnail(uuid, accessToken, APIFolderPath);
    }

    //export api documents
    String documentationSummary = getAPIDocumentation(accessToken, uuid);
    exportAPIDocumentation(uuid, documentationSummary, accessToken, APIFolderPath);
}

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

private static void add() throws Exception {
    ITBandController.add();//from  w ww .j  av  a 2s.  c o m
    ITBandContestController.add();

    CTAMSDocument doc = new CTAMSDocument();
    doc.getBands().add(TestFixture.INSTANCE.skye);
    doc.getVenues().add(TestFixture.INSTANCE.venue);
    doc.getJudges().add(TestFixture.INSTANCE.judgeAndy);
    doc.getJudges().add(TestFixture.INSTANCE.judgeJamie);
    doc.getJudges().add(TestFixture.INSTANCE.judgeBob);
    doc.getJudges().add(TestFixture.INSTANCE.judgeEoin);
    doc.getResults().add(TestFixture.INSTANCE.result1);
    doc.getResults().add(TestFixture.INSTANCE.result2);
    doc.getResults().add(TestFixture.INSTANCE.result3);
    doc.getResults().add(TestFixture.INSTANCE.result4);
    doc.getBandContests().add(TestFixture.INSTANCE.bandContest);
    doc.getBandContestResults().add(TestFixture.INSTANCE.bandResult);

    String xml = XMLUtils.marshal(doc);

    CloseableHttpClient httpclient = HttpClients.createDefault();

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

    HttpPost httpPost = new HttpPost(uri);

    StringEntity xmlEntity = new StringEntity(xml, ContentType.APPLICATION_XML);

    CloseableHttpResponse response = null;

    try {
        httpPost.setEntity(xmlEntity);
        response = httpclient.execute(httpPost);

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

        HttpEntity responseEntity = response.getEntity();

        doc = IntegrationTestUtils.convertEntity(responseEntity);

        TestFixture.INSTANCE.bandResult.setId(doc.getBandContestResults().get(0).getId());

        for (Result r : doc.getBandContestResults().get(0).getResults()) {
            if (r.getPoints() == TestFixture.INSTANCE.result1.getPoints()) {
                TestFixture.INSTANCE.result1.setId(r.getId());
            } else if (r.getPoints() == TestFixture.INSTANCE.result2.getPoints()) {
                TestFixture.INSTANCE.result2.setId(r.getId());
            } else if (r.getPoints() == TestFixture.INSTANCE.result3.getPoints()) {
                TestFixture.INSTANCE.result3.setId(r.getId());
            } else if (r.getPoints() == TestFixture.INSTANCE.result4.getPoints()) {
                TestFixture.INSTANCE.result4.setId(r.getId());
            }
        }

        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);
            }
        }
    }
}

From source file:utils.APIImporter.java

/**
 * Publishing each imported APIs//from w  w w.  j  a  v a2 s . c o m
 * @param apiFolder path to the imported folder
 * @param token access token
 * @throws APIImportException
 */
private static void publishAPI(String apiFolder, String token) throws APIImportException {
    String apiId = null;
    try {
        //getting api.json of imported API
        String pathToJSONFile = apiFolder + ImportExportConstants.JSON_FILE_LOCATION;
        String jsonContent = FileUtils.readFileToString(new File(pathToJSONFile));
        //building API id
        apiId = ImportExportUtils.readJsonValues(jsonContent, ImportExportConstants.API_PROVIDER) + "-"
                + ImportExportUtils.readJsonValues(jsonContent, ImportExportConstants.API_NAME) + "-"
                + ImportExportUtils.readJsonValues(jsonContent, ImportExportConstants.API_VERSION);

        String url = config.getPublisherUrl() + "apis";
        CloseableHttpClient client = HttpClientGenerator.getHttpClient(config.getCheckSSLCertificate());
        HttpPost request = new HttpPost(url);
        request.setEntity(new StringEntity(jsonContent, ImportExportConstants.CHARSET));
        request.setHeader(HttpHeaders.AUTHORIZATION, ImportExportConstants.CONSUMER_KEY_SEGMENT + " " + token);
        request.setHeader(HttpHeaders.CONTENT_TYPE, ImportExportConstants.CONTENT_JSON);
        CloseableHttpResponse response = client.execute(request);

        if (response.getStatusLine().getStatusCode() == Response.Status.CONFLICT.getStatusCode()) {
            if (config.getUpdateApi()) {
                updateApi(jsonContent, apiId, token, apiFolder);
            } else {
                errorMsg = "API " + apiId + " already exists. ";
                System.out.println(errorMsg);
            }
        } else if (response.getStatusLine().getStatusCode() == Response.Status.CREATED.getStatusCode()) {
            System.out.println("creating API " + apiId);
            //getting created API's uuid
            HttpEntity entity = response.getEntity();
            String responseString = EntityUtils.toString(entity, ImportExportConstants.CHARSET);
            String uuid = ImportExportUtils.readJsonValues(responseString, ImportExportConstants.UUID);
            if (StringUtils.isNotBlank(
                    ImportExportUtils.readJsonValues(jsonContent, ImportExportConstants.THUMBNAIL))) {
                addAPIImage(apiFolder, token, uuid);
            }
            //Adding API documentations
            addAPIDocuments(apiFolder, token, uuid);

            //addAPISequences(pathToArchive, importedApi);
            // addAPISpecificSequences(pathToArchive, importedApi);
            // addAPIWsdl(pathToArchive, importedApi);
            System.out.println("Importing API " + apiId + " was successful");

        } else {
            errorMsg = response.getStatusLine().toString();
            log.error(errorMsg);
            throw new APIImportException(errorMsg);
        }
    } catch (IOException e) {
        String errorMsg = "cannot find details of " + apiId + " for import";
        log.error(errorMsg, e);
        throw new APIImportException(errorMsg, e);
    }
}

From source file:com.zxy.commons.httpclient.HttpclientUtils.java

/**
 * Post url// w w w. j a v  a 2s. c om
 * 
 * @param connectTimeoutSec ()
 * @param socketTimeoutSec ??()
 * @param url url?
 * @param params {@link org.apache.http.NameValuePair} params
 *            <p>
 *            example:{@code params.add(new BasicNameValuePair("id", "123456"));}
 * @return post??
 * @throws ClientProtocolException ClientProtocolException
 * @throws IOException IOException
 * @see org.apache.http.NameValuePair
 * @see org.apache.http.message.BasicNameValuePair
 */
public static String post(int connectTimeoutSec, int socketTimeoutSec, String url, List<NameValuePair> params)
        throws ClientProtocolException, IOException {
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse httpResponse = null;
    try {
        //            httpClient = HttpClients.createDefault();
        RequestConfig config = RequestConfig.custom().setConnectTimeout(connectTimeoutSec * 1000)
                .setConnectionRequestTimeout(connectTimeoutSec * 1000).setSocketTimeout(socketTimeoutSec * 1000)
                .build();
        httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();

        HttpPost httppost = new HttpPost(url);

        UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(params, Charsets.UTF_8);
        httppost.setEntity(uefEntity);

        httpResponse = httpClient.execute(httppost);
        HttpEntity entity = httpResponse.getEntity();
        return EntityUtils.toString(entity, Charsets.UTF_8);
    } finally {
        HttpClientUtils.closeQuietly(httpResponse);
        HttpClientUtils.closeQuietly(httpClient);
    }
}