Example usage for org.apache.http.impl.client HttpClients createSystem

List of usage examples for org.apache.http.impl.client HttpClients createSystem

Introduction

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

Prototype

public static CloseableHttpClient createSystem() 

Source Link

Document

Creates CloseableHttpClient instance with default configuration based on ssytem properties.

Usage

From source file:com.github.ljtfreitas.restify.http.client.request.apache.httpclient.ApacheHttpClientRequestFactory.java

public ApacheHttpClientRequestFactory(Charset charset) {
    this(HttpClients.createSystem(), null, HttpClientContext.create(), charset);
}

From source file:io.apicurio.hub.api.security.KeycloakLinkedAccountsProvider.java

@PostConstruct
protected void postConstruct() {
    try {/*from w  w w  .  j  a va 2s  .co  m*/
        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);
    }
}

From source file:com.cognifide.aet.proxy.RestProxyServer.java

@Override
public void addHeader(String name, String value) {
    CloseableHttpClient httpClient = HttpClients.createSystem();
    try {/*  w  w w .j a  v  a  2 s  .co m*/
        URIBuilder uriBuilder = new URIBuilder().setScheme(HTTP).setHost(server.getAPIHost())
                .setPort(server.getAPIPort());
        // Request BMP to add header
        HttpPost request = new HttpPost(
                uriBuilder.setPath(String.format("/proxy/%d/headers", server.getProxyPort())).build());
        request.setHeader("Content-Type", "application/json");
        JSONObject json = new JSONObject();
        json.put(name, value);
        request.setEntity(new StringEntity(json.toString()));
        // Execute request
        CloseableHttpResponse response = httpClient.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != STATUS_CODE_OK) {
            throw new UnableToAddHeaderException(
                    "Invalid HTTP Response when attempting to add header" + statusCode);
        }
        response.close();
    } catch (Exception e) {
        throw new BMPCUnableToConnectException(String.format("Unable to connect to BMP Proxy at '%s:%s'",
                server.getAPIHost(), server.getAPIPort()), e);
    } finally {
        try {
            httpClient.close();
        } catch (IOException e) {
            LOGGER.warn("Unable to close httpClient", e);
        }
    }
}

From source file:io.github.thred.climatetray.ClimateTrayProxySettings.java

public CloseableHttpClient createHttpClient(String... additionalProxyExcludes) {
    if (proxyType == ProxyType.NONE) {
        return HttpClients.createDefault();
    }//w  ww .  j  a  va 2 s .co m

    if (proxyType == ProxyType.SYSTEM_DEFAULT) {
        return HttpClients.createSystem();
    }

    HttpHost proxy = new HttpHost(getProxyHost(), getProxyPort());
    HttpClientBuilder builder = HttpClientBuilder.create().setProxy(proxy);

    if (isProxyAuthorizationNeeded()) {
        Credentials credentials = new UsernamePasswordCredentials(getProxyUser(), getProxyPassword());
        AuthScope authScope = new AuthScope(getProxyHost(), getProxyPort());
        CredentialsProvider credsProvider = new BasicCredentialsProvider();

        credsProvider.setCredentials(authScope, credentials);

        builder.setDefaultCredentialsProvider(credsProvider);
    }

    String excludes = proxyExcludes;

    if (Utils.isBlank(excludes)) {
        excludes = "";
    }

    for (String additionalProxyExclude : additionalProxyExcludes) {
        if (excludes.length() > 0) {
            excludes += ", ";
        }

        excludes += additionalProxyExclude;
    }

    if (!Utils.isBlank(excludes)) {
        WildcardPattern pattern = new WildcardPattern(excludes.split("\\s*,\\s*"));
        HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy) {
            @Override
            public HttpRoute determineRoute(HttpHost host, HttpRequest request, HttpContext context)
                    throws HttpException {
                InetAddress address = host.getAddress();

                if (address == null) {
                    try {
                        address = InetAddress.getByName(host.getHostName());
                    } catch (UnknownHostException e) {
                        ClimateTray.LOG.info("Failed to determine address of host \"%s\"", host.getHostName());
                    }
                }

                if (address != null) {
                    String hostAddress = address.getHostAddress();

                    if (pattern.matches(hostAddress)) {
                        return new HttpRoute(host);
                    }
                }

                String hostName = host.getHostName();

                if (pattern.matches(hostName)) {
                    return new HttpRoute(host);
                }

                return super.determineRoute(host, request, context);
            }
        };

        builder.setRoutePlanner(routePlanner);
    }

    return builder.build();
}

From source file:DeliverWork.java

private static String saveIntoWeed(RemoteFile remoteFile, String projectId)
        throws SQLException, UnsupportedEncodingException {
    String url = "http://59.215.226.174/WebDiskServerDemo/doc?doc_id="
            + URLEncoder.encode(remoteFile.getFileId(), "utf-8");
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse response = null;
    String res = "";
    try {/*from  ww w. j  a va 2  s  . c  o  m*/
        httpClient = HttpClients.createSystem();
        // http(get?)
        HttpGet httpget = new HttpGet(url);
        response = httpClient.execute(httpget);
        HttpEntity result = response.getEntity();
        String fileName = remoteFile.getFileName();
        FileHandleStatus fileHandleStatus = getFileTemplate().saveFileByStream(fileName,
                new ByteArrayInputStream(EntityUtils.toByteArray(result)));
        System.out.println(fileHandleStatus);
        File file = new File();
        if (result != null && result.getContentType() != null && result.getContentType().getValue() != null) {
            file.setContentType(result.getContentType().getValue());
        } else {
            file.setContentType("application/error");
        }
        file.setDataId(Integer.parseInt(projectId));
        file.setName(fileName);
        if (fileName.contains(".bmp") || fileName.contains(".jpg") || fileName.contains(".jpeg")
                || fileName.contains(".png") || fileName.contains(".gif")) {
            file.setType(1);
        } else if (fileName.contains(".doc") || fileName.contains(".docx")) {
            file.setType(2);
        } else if (fileName.contains(".xlsx") || fileName.contains("xls")) {
            file.setType(3);
        } else if (fileName.contains(".pdf")) {
            file.setType(4);
        } else {
            file.setType(5);
        }
        String accessUrl = "/" + fileHandleStatus.getFileId().replaceAll(",", "/").concat("/").concat(fileName);
        file.setUrl(accessUrl);
        file.setSize(fileHandleStatus.getSize());
        file.setPostTime(new java.util.Date());
        file.setStatus(0);
        file.setEnumValue(findFileType(remoteFile.getFileType()));
        file.setResources(1);
        //            JdbcFactory jdbcFactoryChanye=new JdbcFactory("jdbc:mysql://127.0.0.1:3306/fp_guimin?useUnicode=true&characterEncoding=UTF-8","root","111111","com.mysql.jdbc.Driver");
        //            Connection connection = jdbcFactoryChanye.getConnection();
        DatabaseMetaData dmd = connection.getMetaData();
        PreparedStatement ps = connection.prepareStatement(insertFile, new String[] { "ID" });
        ps.setString(1, sdf.format(file.getPostTime()));
        ps.setInt(2, file.getType());
        ps.setString(3, file.getEnumValue());
        ps.setInt(4, file.getDataId());
        ps.setString(5, file.getUrl());
        ps.setString(6, file.getName());
        ps.setString(7, file.getContentType());
        ps.setLong(8, file.getSize());
        ps.setInt(9, file.getStatus());
        ps.setInt(10, file.getResources());
        ps.executeUpdate();
        if (dmd.supportsGetGeneratedKeys()) {
            ResultSet rs = ps.getGeneratedKeys();
            while (rs.next()) {
                System.out.println(rs.getLong(1));
            }
        }
        ps.close();
        res = "success";
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        res = e.getMessage();
    } catch (IOException e) {
        e.printStackTrace();
        res = e.getMessage();
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (httpClient != null) {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return res;
}

From source file:org.phenotips.data.internal.MonarchPatientScorer.java

@Override
public void initialize() throws InitializationException {
    try {/*www  .j av  a2s .c om*/
        this.scorerURL = this.configuration.getProperty("phenotips.patientScoring.monarch.serviceURL",
                "https://monarchinitiative.org/score");
        CacheConfiguration config = new LRUCacheConfiguration("monarchSpecificityScore", 2048, 3600);
        this.cache = this.cacheManager.createNewCache(config);
    } catch (CacheException ex) {
        throw new InitializationException("Failed to create cache", ex);
    }
    try {
        SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustAllStrategy()).build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, null, null,
                NoopHostnameVerifier.INSTANCE);
        this.client = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException ex) {
        this.logger.warn("Failed to set custom certificate trust, using the default", ex);
        this.client = HttpClients.createSystem();
    }
}

From source file:com.core.util.wx.PayUtils.java

/**
 * post???xml?url//  w w  w.ja va  2 s .c o m
 * 
 * @param xml
 * @param url
 * @return
 */
public static String postXmlCurl(String xml, String url) {
    HttpClient client = HttpClients.createSystem();
    HttpPost post = new HttpPost(url);
    String result = null;
    try {
        post.setEntity(new StringEntity(xml));
        HttpResponse httpResponse = client.execute(post);
        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            HttpEntity httpEntity = httpResponse.getEntity();
            result = EntityUtils.toString(httpEntity);// ?
        }
    } catch (UnsupportedEncodingException e) {
        LOG.error(e.getMessage(), e);
    } catch (ClientProtocolException e) {
        LOG.error(e.getMessage(), e);
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
    }
    return result;
}

From source file:com.redhat.jenkins.nodesharing.RestEndpoint.java

@CheckForNull
private <T> T _executeRequest(@Nonnull HttpRequestBase method, @Nonnull ResponseHandler<T> handler) {
    method.setConfig(REQUEST_CONFIG);/*from   www.j a v a 2s  . com*/

    CloseableHttpClient client = HttpClients.createSystem();
    try {
        return client.execute(method, handler, getAuthenticatingContext(method));
    } catch (SocketTimeoutException e) {
        throw new ActionFailed.RequestTimeout("Failed executing REST call: " + method, e);
    } catch (IOException e) {
        throw new ActionFailed.CommunicationError("Failed executing REST call: " + method, e);
    } finally {
        try {
            client.close();
        } catch (IOException e) {
            LOGGER.log(Level.WARNING, "Unable to close HttpClient", e); // $COVERAGE-IGNORE$
        }
    }
}

From source file:nl.mineleni.cbsviewer.servlet.ReverseProxyServlet.java

/**
 * Initialize variables called when context is initialized. Leest de waarden
 * van {@link #ALLOWED_HOSTS} (verplichte optie) en {@link #FORCE_XML_MIME}
 * uit de configuratie./*from  w  w w . j  a v a2s .com*/
 *
 * @param config
 *            the <code>ServletConfig</code> object that contains
 *            configutation information for this servlet
 * @throws ServletException
 *             if an exception occurs that interrupts the servlet's normal
 *             operation
 */
@Override
public void init(final ServletConfig config) throws ServletException {
    super.init(config);
    final String forceXML = config.getInitParameter(FORCE_XML_MIME);
    this.forceXmlResponse = (null != forceXML ? Boolean.parseBoolean(forceXML) : false);

    String csvHostnames = config.getInitParameter(ALLOWED_HOSTS);
    if (csvHostnames == null) {
        LOGGER.error(ERR_MSG_MISSING_CONFIG);
        throw new ServletException(ERR_MSG_MISSING_CONFIG);
    }
    // clean-up whitespace and case
    csvHostnames = csvHostnames.replaceAll("\\s", "").toLowerCase();
    final String[] names = csvHostnames.split(";");
    for (final String name : names) {
        this.allowedHosts.add(name);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("toevoegen aan allowed host namen: " + name);
        }
    }

    // http client set up
    this.client = HttpClients.createSystem();
    this.requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();
    if ((null != this.getProxyHost()) && (this.getProxyPort() > 0)) {
        final HttpHost proxy = new HttpHost(this.getProxyHost(), this.getProxyPort(), "http");
        this.requestConfig = RequestConfig.copy(this.requestConfig).setProxy(proxy).build();
    }

    // voorgond feature info response type
    final String mType = config.getInitParameter("featureInfoType");
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("voorgrond kaartlagen mimetype: " + mType);
    }
    if ((mType != null) && (mType.length() > 0)) {
        type = CONVERTER_TYPE.valueOf(mType);
    }

}

From source file:io.apicurio.hub.api.gitlab.GitLabSourceConnector.java

private ResourceContent getResourceContentFromGitLab(GitLabResource resource)
        throws NotFoundException, SourceConnectorException {
    try (CloseableHttpClient httpClient = HttpClients.createSystem()) {
        String getContentUrl = this.endpoint("/api/v4/projects/:id/repository/files/:path?ref=:branch")
                .bind("id", toEncodedId(resource)).bind("path", toEncodedPath(resource))
                .bind("branch", toEncodedBranch(resource)).url();

        HttpGet get = new HttpGet(getContentUrl);
        get.addHeader("Accept", "application/json");
        get.addHeader("Cache-Control", "no-cache");
        get.addHeader("Postman-Token", "4d2517bb-72d0-9175-1cbe-04d61e9258a0");
        get.addHeader("DNT", "1");
        get.addHeader("Accept-Language", "en-US,en;q=0.8");

        try {//from  w ww  .j av a  2s .co m
            addSecurity(get);
        } catch (Exception e) {
            // If adding security fails, just go ahead and try without security.  If it's a public
            // repository then this will work.  If not, then it will fail with a 404.
        }

        try (CloseableHttpResponse response = httpClient.execute(get)) {
            if (response.getStatusLine().getStatusCode() == 404) {
                throw new NotFoundException();
            }
            if (response.getStatusLine().getStatusCode() != 200) {
                throw new SourceConnectorException(
                        "Unexpected response from GitLab: " + response.getStatusLine().toString());
            }

            try (InputStream contentStream = response.getEntity().getContent()) {
                Map<String, Object> jsonContent = mapper.readerFor(Map.class).readValue(contentStream);
                String b64Content = jsonContent.get("content").toString();
                String content = new String(Base64.decodeBase64(b64Content), StandardCharsets.UTF_8);
                ResourceContent rval = new ResourceContent();

                rval.setContent(content);
                rval.setSha(jsonContent.get("commit_id").toString());

                return rval;
            }
        }
    } catch (IOException e) {
        throw new SourceConnectorException("Error getting GitLab resource content.", e);
    }
}