Search in sources :

Example 11 with HttpClientBuilder

use of org.apache.http.impl.client.HttpClientBuilder in project Xponents by OpenSextant.

the class WebClient method getClient.

/**
     * TODO: Update to use HTTP client "HttpClients....build()" method of creating and tailoring HttpClient
     * using the proxy and cookie settings, as well as any other tuning.
     *
     * Override if your context requires a different style of HTTP client.
     * 
     * @return HttpClient 4.x object
     */
public HttpClient getClient() {
    HttpClientBuilder clientHelper = null;
    if (this.useSystemProperties) {
        clientHelper = HttpClientBuilder.create().useSystemProperties();
    } else {
        clientHelper = HttpClientBuilder.create();
        if (proxyHost != null) {
            clientHelper.setProxy(proxyHost);
        }
    }
    RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).build();
    HttpClient httpClient = clientHelper.setDefaultRequestConfig(globalConfig).build();
    return httpClient;
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) HttpClient(org.apache.http.client.HttpClient) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder)

Example 12 with HttpClientBuilder

use of org.apache.http.impl.client.HttpClientBuilder in project voltdb by VoltDB.

the class TestJSONOverHttps method callProcOverJSON.

private String callProcOverJSON(String varString, final int expectedCode) throws Exception {
    URI uri = URI.create("https://localhost:" + m_port + "/api/1.0/");
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

        @Override
        public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            return true;
        }
    }).build();
    SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sf).build();
    // allows multi-threaded use
    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    HttpClientBuilder b = HttpClientBuilder.create();
    b.setSslcontext(sslContext);
    b.setConnectionManager(connMgr);
    try (CloseableHttpClient httpclient = b.build()) {
        HttpPost post = new HttpPost(uri);
        // play nice by using HTTP 1.1 continue requests where the client sends the request headers first
        // to the server to see if the server is willing to accept it. This allows us to test large requests
        // without incurring server socket connection terminations
        RequestConfig rc = RequestConfig.copy(RequestConfig.DEFAULT).setExpectContinueEnabled(true).build();
        post.setProtocolVersion(HttpVersion.HTTP_1_1);
        post.setConfig(rc);
        post.setEntity(new StringEntity(varString, utf8ApplicationFormUrlEncoded));
        ResponseHandler<String> rh = new ResponseHandler<String>() {

            @Override
            public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                assertEquals(expectedCode, status);
                if ((status >= 200 && status < 300) || status == 400) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                }
                return null;
            }
        };
        return httpclient.execute(post, rh);
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) RequestConfig(org.apache.http.client.config.RequestConfig) TrustStrategy(org.apache.http.conn.ssl.TrustStrategy) ResponseHandler(org.apache.http.client.ResponseHandler) HttpEntity(org.apache.http.HttpEntity) HttpResponse(org.apache.http.HttpResponse) SSLContext(javax.net.ssl.SSLContext) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) URI(java.net.URI) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) StringEntity(org.apache.http.entity.StringEntity) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) SSLContextBuilder(org.apache.http.conn.ssl.SSLContextBuilder)

Example 13 with HttpClientBuilder

use of org.apache.http.impl.client.HttpClientBuilder in project intellij-community by JetBrains.

the class EduStepicClient method initializeClient.

private static void initializeClient() {
    if (ourClient == null) {
        final HttpClientBuilder builder = getBuilder();
        ourClient = builder.build();
    }
}
Also used : HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder)

Example 14 with HttpClientBuilder

use of org.apache.http.impl.client.HttpClientBuilder in project perun by CESNET.

the class ExtSourcePerun method call.

private Deserializer call(String managerName, String methodName, String query) throws PerunException {
    //Prepare sending message
    HttpResponse response;
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    // just like cookie-policy: ignore cookies
    httpClientBuilder.disableCookieManagement();
    HttpClient httpClient = httpClientBuilder.build();
    String commandUrl = perunUrl + format + "/" + managerName + "/" + methodName;
    if (query != null)
        commandUrl += "?" + query;
    HttpGet get = new HttpGet(commandUrl);
    get.setHeader("Content-Type", "application/json");
    get.setHeader("charset", "utf-8");
    get.setHeader("Connection", "Close");
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
    get.addHeader(BasicScheme.authenticate(credentials, "utf-8", false));
    //post.setParams(params);
    InputStream rpcServerAnswer = null;
    try {
        response = httpClient.execute(get);
        rpcServerAnswer = response.getEntity().getContent();
    } catch (IOException ex) {
        this.processIOException(ex);
    }
    JsonDeserializer des = null;
    try {
        des = new JsonDeserializer(rpcServerAnswer);
    } catch (IOException ex) {
        this.processIOException(ex);
    }
    return des;
}
Also used : InputStream(java.io.InputStream) HttpClient(org.apache.http.client.HttpClient) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) IOException(java.io.IOException) JsonDeserializer(cz.metacentrum.perun.rpc.deserializer.JsonDeserializer) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 15 with HttpClientBuilder

use of org.apache.http.impl.client.HttpClientBuilder in project perun by CESNET.

the class RTMessagesManagerBlImpl method sendMessageToRT.

public RTMessage sendMessageToRT(PerunSession sess, int voId, String queue, String subject, String text) throws InternalErrorException {
    log.debug("Parameters of rtMessage are queue='" + queue + "', subject='{}' and text='{}'", subject, text);
    //Get Email from User who get from session
    String email = null;
    User user = sess.getPerunPrincipal().getUser();
    //try to get user/member email from user in session
    if (user != null)
        email = findUserPreferredEmail(sess, user);
    else {
        email = null;
        log.error("Can't get user from session.");
    }
    //try to get email from additionalInformations in session (attribute mail)
    if (email == null) {
        Matcher emailMatcher;
        Map<String, String> additionalInfo = sess.getPerunPrincipal().getAdditionalInformations();
        //If there are some data in additionalInfo
        if (additionalInfo != null) {
            String mailInfo = additionalInfo.get("mail");
            //If there is notnull attribute "mail" in map
            if (mailInfo != null) {
                //If attribute mail has separator ',' or ';'
                if (mailInfo.contains(";")) {
                    String[] mailsFromInfo = mailInfo.split(";");
                    for (String mail : mailsFromInfo) {
                        emailMatcher = Utils.emailPattern.matcher(mail);
                        if (emailMatcher.matches()) {
                            email = mail;
                            break;
                        }
                    }
                } else if (mailInfo.contains(",")) {
                    String[] mailsFromInfo = mailInfo.split(",");
                    for (String mail : mailsFromInfo) {
                        emailMatcher = Utils.emailPattern.matcher(mail);
                        if (emailMatcher.matches()) {
                            email = mail;
                            break;
                        }
                    }
                } else {
                    //If there is no separator, test if this has format of email, if yes, save it to email
                    emailMatcher = Utils.emailPattern.matcher(mailInfo);
                    if (emailMatcher.matches()) {
                        email = mailInfo;
                    }
                }
            }
        }
    }
    //Prepare sending message
    HttpResponse response;
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    // just like cookie-policy: ignore cookies
    httpClientBuilder.disableCookieManagement();
    HttpClient httpClient = httpClientBuilder.build();
    StringBuilder responseMessage = new StringBuilder();
    String ticketNumber = "0";
    try {
        response = httpClient.execute(this.prepareDataAndGetHttpRequest(sess, voId, queue, email, subject, text));
        BufferedReader bw = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        //Reading response from RT
        String line;
        while ((line = bw.readLine()) != null) {
            responseMessage.append(line);
            responseMessage.append('\n');
            //Matcher for ticketNumber
            Matcher ticketNumberMatcher = this.ticketNumberPattern.matcher(line);
            if (ticketNumberMatcher.find()) {
                ticketNumber = ticketNumberMatcher.group(1);
            }
        }
    } catch (IOException ex) {
        throw new InternalErrorException("IOException has been throw while executing http request.", ex);
    }
    //Return message if response is ok, or throw exception with bad response
    int ticketNum = Integer.valueOf(ticketNumber);
    if (ticketNum != 0) {
        RTMessage rtmessage = new RTMessage(email, ticketNum);
        log.debug("RT message was send successfully and the ticket has number: " + ticketNum);
        return rtmessage;
    } else {
        throw new InternalErrorException("RT message was not send due to error with RT returned this message: " + responseMessage.toString());
    }
}
Also used : User(cz.metacentrum.perun.core.api.User) InputStreamReader(java.io.InputStreamReader) Matcher(java.util.regex.Matcher) HttpResponse(org.apache.http.HttpResponse) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) IOException(java.io.IOException) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) RTMessage(cz.metacentrum.perun.core.api.RTMessage) HttpClient(org.apache.http.client.HttpClient) BufferedReader(java.io.BufferedReader)

Aggregations

HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)42 RequestConfig (org.apache.http.client.config.RequestConfig)17 SSLConnectionSocketFactory (org.apache.http.conn.ssl.SSLConnectionSocketFactory)12 HttpHost (org.apache.http.HttpHost)10 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)10 PoolingHttpClientConnectionManager (org.apache.http.impl.conn.PoolingHttpClientConnectionManager)10 SSLContext (javax.net.ssl.SSLContext)9 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)9 CredentialsProvider (org.apache.http.client.CredentialsProvider)9 ConnectionSocketFactory (org.apache.http.conn.socket.ConnectionSocketFactory)9 HttpClient (org.apache.http.client.HttpClient)8 IOException (java.io.IOException)7 HttpResponse (org.apache.http.HttpResponse)7 PlainConnectionSocketFactory (org.apache.http.conn.socket.PlainConnectionSocketFactory)7 AuthScope (org.apache.http.auth.AuthScope)6 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)6 HttpGet (org.apache.http.client.methods.HttpGet)5 HttpPost (org.apache.http.client.methods.HttpPost)5 URI (java.net.URI)4 HttpEntity (org.apache.http.HttpEntity)4