Java Code Examples for org.apache.http.impl.client.HttpClients#createSystem()

The following examples show how to use org.apache.http.impl.client.HttpClients#createSystem() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DownloadServlet.java    From apicurio-studio with Apache License 2.0 6 votes vote down vote up
@PostConstruct
protected void postConstruct() {
    try {
        if (uiConfig.isDisableHubApiTrustManager()) {
            SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                    return true;
                }
            }).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
            httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } else {
            httpClient = HttpClients.createSystem();
        }
    } catch (Exception e) {
        logger.error("Error creating HTTP client.", e);
        throw new RuntimeException(e);
    }
}
 
Example 2
Source File: Utils.java    From FROST-Server with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Load the contents of a keycloak config file, specified in the given
 * Settings object.
 *
 * @param authSettings The settings object to fetch the config file path
 * from.
 * @return the contents of the config file.
 */
private static String getKeycloakConfigFromServer(Settings authSettings) {
    String keycloakConfigUrl = authSettings.get(TAG_KEYCLOAK_CONFIG_URL, "");
    if (StringHelper.isNullOrEmpty(keycloakConfigUrl)) {
        return "";
    }
    String keycloakConfigSecret = authSettings.get(TAG_KEYCLOAK_CONFIG_SECRET, "");

    LOGGER.info("Fetching Keycloak config from server: {}", keycloakConfigUrl);
    try (CloseableHttpClient client = HttpClients.createSystem()) {
        HttpGet httpGet = new HttpGet(keycloakConfigUrl);
        if (!StringHelper.isNullOrEmpty(keycloakConfigSecret)) {
            String clientId = keycloakConfigUrl.substring(keycloakConfigUrl.lastIndexOf('/') + 1);
            String encoded = clientId + ":" + keycloakConfigSecret;
            httpGet.addHeader("Authorization", "basic " + Base64.encodeBase64String(encoded.getBytes()));
        }
        HttpResponse httpResponse = client.execute(httpGet);
        String configString = EntityUtils.toString(httpResponse.getEntity(), StringHelper.UTF8);
        LOGGER.info("Fetched Keycloak config from server. Size {}", configString.length());
        return configString;
    } catch (IOException exc) {
        LOGGER.error("Failed to read keycloak config file.", exc);
        return "";
    }
}
 
Example 3
Source File: GridInfoExtractor.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 6 votes vote down vote up
public static String[] getHostNameAndPort(String hostName, int port, SessionId session) {
    String[] hostAndPort = new String[2];
    String errorMsg = "Failed to acquire remote webdriver node and port info. Root cause: \n";

    try {
        HttpHost host = new HttpHost(hostName, port);
        CloseableHttpClient client = HttpClients.createSystem();
        URL sessionURL = new URL("http://" + hostName + ":" + port + "/grid/api/testsession?session=" + session);
        BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", sessionURL.toExternalForm());
        HttpResponse response = client.execute(host, r);
        String url = extractUrlFromResponse(response);
        if (url != null) {
            URL myURL = new URL(url);
            if ((myURL.getHost() != null) && (myURL.getPort() != -1)) {
                hostAndPort[0] = myURL.getHost();
                hostAndPort[1] = Integer.toString(myURL.getPort());
            }
        }
    } catch (Exception e) {
        Logger.getLogger(GridInfoExtractor.class.getName()).log(Level.SEVERE, null, errorMsg + e);
    }
    return hostAndPort;
}
 
Example 4
Source File: GitlabServerPullRequestDecorator.java    From sonarqube-community-branch-plugin with GNU General Public License v3.0 5 votes vote down vote up
private <X> X getSingle(String userURL, Map<String, String> headers, Class<X> type) throws IOException {
    HttpGet httpGet = new HttpGet(userURL);
    for (Map.Entry<String, String> entry : headers.entrySet()) {
        httpGet.addHeader(entry.getKey(), entry.getValue());
    }
    try (CloseableHttpClient httpClient = HttpClients.createSystem()) {
        HttpResponse httpResponse = httpClient.execute(httpGet);
        if (null != httpResponse && httpResponse.getStatusLine().getStatusCode() != 200) {
            LOGGER.error(httpResponse.toString());
            LOGGER.error(EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8));
            throw new IllegalStateException(
                    "An error was returned in the response from the Gitlab API. See the previous log messages for details");
        } else if (null != httpResponse) {
            LOGGER.debug(httpResponse.toString());
            HttpEntity entity = httpResponse.getEntity();
            X user = new ObjectMapper()
                .configure(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT, true)
                .configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true)
                .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
                .readValue(IOUtils.toString(entity.getContent(), StandardCharsets.UTF_8), type);

            LOGGER.info(type + " received");

            return user;
        } else {
            throw new IOException("No response reveived");
        }
    }
}
 
Example 5
Source File: HerokuDeployApi.java    From heroku-maven-plugin with MIT License 5 votes vote down vote up
public Stream<String> followBuildOutputStream(URI buildOutputStreamUri) throws IOException {
    CloseableHttpClient client = HttpClients.createSystem();

    HttpGet request = new HttpGet(buildOutputStreamUri);
    httpHeaders.forEach(request::setHeader);

    CloseableHttpResponse response = client.execute(request);
    HttpEntity responseEntity = response.getEntity();

    return Util.readLinesFromInputStream(responseEntity.getContent());
}
 
Example 6
Source File: HerokuDeployApi.java    From heroku-maven-plugin with MIT License 5 votes vote down vote up
public BuildInfo getBuildInfo(String appName, String buildId) throws IOException, HerokuDeployApiException {
    ObjectMapper mapper = new ObjectMapper();
    CloseableHttpClient client = HttpClients.createSystem();

    HttpUriRequest request = new HttpGet("https://api.heroku.com/apps/" + appName + "/builds/" + buildId);
    httpHeaders.forEach(request::setHeader);

    CloseableHttpResponse response = client.execute(request);

    return handleBuildInfoResponse(appName, mapper, response);
}
 
Example 7
Source File: HerokuDeployApi.java    From heroku-maven-plugin with MIT License 5 votes vote down vote up
public BuildInfo createBuild(String appName, URI sourceBlob, String sourceBlobVersion, List<String> buildpacks) throws IOException, HerokuDeployApiException {
    // Create API payload
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode root = mapper.createObjectNode();

    ObjectNode sourceBlobObject = root.putObject("source_blob");
    sourceBlobObject.put("url", sourceBlob.toString());
    sourceBlobObject.put("version", sourceBlobVersion);

    ArrayNode buildpacksArray = root.putArray("buildpacks");
    buildpacks.forEach(buildpackString -> {
        ObjectNode buildpackObjectNode = buildpacksArray.addObject();

        if (buildpackString.startsWith("http")) {
            buildpackObjectNode.put("url", buildpackString);
        } else {
            buildpackObjectNode.put("name", buildpackString);
        }
    });

    StringEntity apiPayloadEntity = new StringEntity(root.toString());
    apiPayloadEntity.setContentType("application/json");
    apiPayloadEntity.setContentEncoding("UTF-8");

    // Send request
    CloseableHttpClient client = HttpClients.createSystem();

    HttpPost request = new HttpPost("https://api.heroku.com/apps/" + appName + "/builds");
    httpHeaders.forEach(request::setHeader);
    request.setEntity(apiPayloadEntity);

    CloseableHttpResponse response = client.execute(request);

    return handleBuildInfoResponse(appName, mapper, response);
}
 
Example 8
Source File: KeycloakLinkedAccountsProvider.java    From apicurio-studio with Apache License 2.0 5 votes vote down vote up
@PostConstruct
protected void postConstruct() {
    try {
        if (config.isDisableKeycloakTrustManager()) {
            SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
            httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } else {
            httpClient = HttpClients.createSystem();
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 9
Source File: GitlabServerPullRequestDecorator.java    From sonarqube-community-branch-plugin with GNU General Public License v3.0 5 votes vote down vote up
private void postStatus(StringBuilder statusPostUrl, Map<String, String> headers, AnalysisDetails analysis,
                        String coverage) throws IOException {
    //See https://docs.gitlab.com/ee/api/commits.html#post-the-build-status-to-a-commit
    statusPostUrl.append("?name=SonarQube");
    String status = (analysis.getQualityGateStatus() == QualityGate.Status.OK ? "success" : "failed");
    statusPostUrl.append("&state=").append(status);
    statusPostUrl.append("&target_url=").append(URLEncoder.encode(String.format("%s/dashboard?id=%s&pullRequest=%s", server.getPublicRootUrl(),
            URLEncoder.encode(analysis.getAnalysisProjectKey(),
                    StandardCharsets.UTF_8.name()), URLEncoder
                    .encode(analysis.getBranchName(),
                            StandardCharsets.UTF_8.name())), StandardCharsets.UTF_8.name()));
    statusPostUrl.append("&description=").append(URLEncoder.encode("SonarQube Status", StandardCharsets.UTF_8.name()));
    statusPostUrl.append("&coverage=").append(coverage);
    analysis.getScannerProperty(PULLREQUEST_GITLAB_PIPELINE_ID).ifPresent(pipelineId -> statusPostUrl.append("&pipeline_id=").append(pipelineId));

    HttpPost httpPost = new HttpPost(statusPostUrl.toString());
    for (Map.Entry<String, String> entry : headers.entrySet()) {
        httpPost.addHeader(entry.getKey(), entry.getValue());
    }

    try (CloseableHttpClient httpClient = HttpClients.createSystem()) {
        HttpResponse httpResponse = httpClient.execute(httpPost);
        if (null != httpResponse && httpResponse.toString().contains("Cannot transition status")) {
            // Workaround for https://gitlab.com/gitlab-org/gitlab-ce/issues/25807
            LOGGER.debug("Transition status is already {}", status);
        } else {
            validateGitlabResponse(httpResponse, 201, "Comment posted");
        }
    }
}
 
Example 10
Source File: GitlabServerPullRequestDecorator.java    From sonarqube-community-branch-plugin with GNU General Public License v3.0 5 votes vote down vote up
private void postCommitComment(String commitCommentUrl, Map<String, String> headers, List<NameValuePair> params) throws IOException {
    //https://docs.gitlab.com/ee/api/commits.html#post-comment-to-commit
    HttpPost httpPost = new HttpPost(commitCommentUrl);
    for (Map.Entry<String, String> entry : headers.entrySet()) {
        httpPost.addHeader(entry.getKey(), entry.getValue());
    }
    httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));

    LOGGER.info("Posting {} with headers {} to {}", params, headers, commitCommentUrl);

    try (CloseableHttpClient httpClient = HttpClients.createSystem()) {
        HttpResponse httpResponse = httpClient.execute(httpPost);
        validateGitlabResponse(httpResponse, 201, "Comment posted");
    }
}
 
Example 11
Source File: GitlabServerPullRequestDecorator.java    From sonarqube-community-branch-plugin with GNU General Public License v3.0 5 votes vote down vote up
private void deleteCommitDiscussionNote(String commitDiscussionNoteURL, Map<String, String> headers) throws IOException {
    //https://docs.gitlab.com/ee/api/discussions.html#delete-a-commit-thread-note
    HttpDelete httpDelete = new HttpDelete(commitDiscussionNoteURL);
    for (Map.Entry<String, String> entry : headers.entrySet()) {
        httpDelete.addHeader(entry.getKey(), entry.getValue());
    }

    try (CloseableHttpClient httpClient = HttpClients.createSystem()) {
        LOGGER.info("Deleting {} with headers {}", commitDiscussionNoteURL, headers);

        HttpResponse httpResponse = httpClient.execute(httpDelete);
        validateGitlabResponse(httpResponse, 204, "Commit discussions note deleted");
    }
}
 
Example 12
Source File: GitlabServerPullRequestDecorator.java    From sonarqube-community-branch-plugin with GNU General Public License v3.0 5 votes vote down vote up
private <X> List<X> getPagedList(String commitDiscussionURL, Map<String, String> headers,
                                 TypeReference<List<X>> typeRef) throws IOException {
    HttpGet httpGet = new HttpGet(commitDiscussionURL);
    for (Map.Entry<String, String> entry : headers.entrySet()) {
        httpGet.addHeader(entry.getKey(), entry.getValue());
    }

    List<X> discussions = new ArrayList<>();

    try (CloseableHttpClient httpClient = HttpClients.createSystem()) {
        HttpResponse httpResponse = httpClient.execute(httpGet);
        if (null != httpResponse && httpResponse.getStatusLine().getStatusCode() != 200) {
            LOGGER.error(httpResponse.toString());
            LOGGER.error(EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8));
            throw new IllegalStateException("An error was returned in the response from the Gitlab API. See the previous log messages for details");
        } else if (null != httpResponse) {
            LOGGER.debug(httpResponse.toString());
            HttpEntity entity = httpResponse.getEntity();
            List<X> pagedDiscussions = new ObjectMapper()
                    .configure(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT, true)
                    .configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true)
                    .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
                    .readValue(IOUtils.toString(entity.getContent(), StandardCharsets.UTF_8), typeRef);
            discussions.addAll(pagedDiscussions);
            LOGGER.info("MR discussions received");
            Optional<String> nextURL = getNextUrl(httpResponse);
            if (nextURL.isPresent()) {
                LOGGER.info("Getting next page");
                discussions.addAll(getPagedList(nextURL.get(), headers, typeRef));
            }
        }
    }
    return discussions;
}
 
Example 13
Source File: Utils.java    From azure-kusto-java with MIT License 4 votes vote down vote up
static KustoOperationResult post(String url, String payload, InputStream stream, Integer timeoutMs, HashMap<String, String> headers, boolean leaveOpen) throws DataServiceException, DataClientException {
    HttpClient httpClient;
    if (timeoutMs != null) {
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeoutMs).build();
        httpClient = HttpClientBuilder.create().useSystemProperties().setDefaultRequestConfig(requestConfig).build();
    } else {
        httpClient = HttpClients.createSystem();
    }

    // TODO: maybe remove this as the stream closes by the httpClient anyway
    try (InputStream streamToClose = (stream != null && !leaveOpen) ? stream : null) {
        URL cleanUrl = new URL(url);
        URI uri = new URI(cleanUrl.getProtocol(), cleanUrl.getUserInfo(), cleanUrl.getHost(), cleanUrl.getPort(), cleanUrl.getPath(), cleanUrl.getQuery(), cleanUrl.getRef());

        // Request parameters and other properties.
        HttpEntity requestEntity = (stream == null) ? new StringEntity(payload, ContentType.APPLICATION_JSON)
                : new InputStreamEntity(stream);

        HttpPost httpPost = new HttpPost(uri);
        httpPost.setEntity(requestEntity);
        httpPost.addHeader("Accept-Encoding", "gzip,deflate");
        for (HashMap.Entry<String, String> entry : headers.entrySet()) {
            httpPost.addHeader(entry.getKey(), entry.getValue());
        }

        // Execute and get the response.
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            StatusLine statusLine = response.getStatusLine();
            String responseContent = EntityUtils.toString(entity);
            if (statusLine.getStatusCode() == 200) {
                return new KustoOperationResult(responseContent, url.endsWith("v2/rest/query") ? "v2" : "v1");
            }
            else {
                throw new DataServiceException(url, "Error in post request", new DataWebException(responseContent, response));
            }
        }
    } catch (JSONException | IOException | URISyntaxException | KustoServiceError e) {
        throw new DataClientException(url, "Error in post request", e);
    }
    return null;
}
 
Example 14
Source File: WebApplication.java    From elasticsearch with Apache License 2.0 4 votes vote down vote up
@Bean
public HttpClient httpClient() {
    return HttpClients.createSystem();
}
 
Example 15
Source File: Deployer.java    From heroku-maven-plugin with MIT License 3 votes vote down vote up
private static void uploadSourceBlob(Path path, URI destination, BiConsumer<Long, Long> progressConsumer) throws IOException {
    long fileSize = Files.size(path);

    CloseableHttpClient client = HttpClients.createSystem();

    HttpPut request = new HttpPut(destination);
    request.setEntity(new UploadProgressHttpEntity(new FileEntity(path.toFile()), bytes -> progressConsumer.accept(bytes, fileSize)));

    client.execute(request);
}
 
Example 16
Source File: HttpComponentsClientHttpRequestFactory.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Create a new instance of the {@code HttpComponentsClientHttpRequestFactory}
 * with a default {@link HttpClient}.
 */
public HttpComponentsClientHttpRequestFactory() {
	this.httpClient = HttpClients.createSystem();
}
 
Example 17
Source File: AbstractHttpClient.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 2 votes vote down vote up
/**
 * returns systen Def client
 *
 * @return
 */
public final CloseableHttpClient getSystemClient() {
    return HttpClients.createSystem();
}
 
Example 18
Source File: HttpComponentsClientHttpRequestFactory.java    From spring4-understanding with Apache License 2.0 2 votes vote down vote up
/**
 * Create a new instance of the {@code HttpComponentsClientHttpRequestFactory}
 * with a default {@link HttpClient}.
 */
public HttpComponentsClientHttpRequestFactory() {
	this(HttpClients.createSystem());
}
 
Example 19
Source File: HttpComponentsClientHttpRequestFactory.java    From java-technology-stack with MIT License 2 votes vote down vote up
/**
 * Create a new instance of the {@code HttpComponentsClientHttpRequestFactory}
 * with a default {@link HttpClient} based on system properties.
 */
public HttpComponentsClientHttpRequestFactory() {
	this.httpClient = HttpClients.createSystem();
}
 
Example 20
Source File: HttpComponentsClientHttpRequestFactory.java    From spring-analysis-note with MIT License 2 votes vote down vote up
/**
 * Create a new instance of the {@code HttpComponentsClientHttpRequestFactory}
 * with a default {@link HttpClient} based on system properties.
 */
public HttpComponentsClientHttpRequestFactory() {
	this.httpClient = HttpClients.createSystem();
}