Search in sources :

Example 41 with RequestConfig

use of org.graylog.shaded.elasticsearch7.org.apache.http.client.config.RequestConfig in project SEPA by arces-wot.

the class DefaultAuthenticationService method registerClient.

public Response registerClient(String client_id, String username, String initialAccessToken, int timeout) throws SEPASecurityException {
    if (client_id == null)
        throw new SEPASecurityException("Identity is null");
    logger.log(Level.getLevel("oauth"), "REGISTER " + client_id);
    CloseableHttpResponse response = null;
    long start = Timings.getTime();
    try {
        URI uri = new URI(oauthProperties.getRegisterUrl());
        ByteArrayEntity body = new ByteArrayEntity(new RegistrationRequest(client_id).toString().getBytes("UTF-8"));
        HttpPost httpRequest = new HttpPost(uri);
        httpRequest.setHeader("Content-Type", "application/json");
        httpRequest.setHeader("Accept", "application/json");
        httpRequest.setEntity(body);
        // Set timeout
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).build();
        httpRequest.setConfig(requestConfig);
        logger.log(Level.getLevel("oauth"), "Request: " + httpRequest);
        try {
            response = httpClient.execute(httpRequest);
        } catch (IOException e) {
            logger.error("HTTP EXECUTE: " + e.getMessage());
            return new ErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "HttpExecute", e.getMessage());
        }
        logger.log(Level.getLevel("oauth"), "Response: " + response);
        HttpEntity entity = response.getEntity();
        String jsonResponse = EntityUtils.toString(entity, Charset.forName("UTF-8"));
        EntityUtils.consume(entity);
        JsonObject json = new JsonParser().parse(jsonResponse).getAsJsonObject();
        if (json.has("error")) {
            int code = json.get("status_code").getAsInt();
            String error = json.get("error").getAsString();
            String description = json.get("error_description").getAsString();
            ErrorResponse ret = new ErrorResponse(code, error, description);
            logger.error(ret);
            return ret;
        }
        String id = json.get("credentials").getAsJsonObject().get("client_id").getAsString();
        String secret = json.get("credentials").getAsJsonObject().get("client_secret").getAsString();
        JsonElement signature = json.get("credentials").getAsJsonObject().get("signature");
        Timings.log("REGISTER", start, Timings.getTime());
        return new RegistrationResponse(id, secret, signature);
    } catch (URISyntaxException e) {
        logger.error(e.getMessage());
        Timings.log("REGISTER_ERROR", start, Timings.getTime());
        return new ErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "URISyntaxException", e.getMessage());
    } catch (UnsupportedEncodingException e) {
        logger.error(e.getMessage());
        Timings.log("REGISTER_ERROR", start, Timings.getTime());
        return new ErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "UnsupportedEncodingException", e.getMessage());
    } catch (ParseException e) {
        logger.error(e.getMessage());
        Timings.log("REGISTER_ERROR", start, Timings.getTime());
        return new ErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "ParseException", e.getMessage());
    } catch (IOException e) {
        logger.error(e.getMessage());
        Timings.log("REGISTER_ERROR", start, Timings.getTime());
        return new ErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "IOException", e.getMessage());
    } finally {
        try {
            if (response != null)
                response.close();
        } catch (IOException e) {
            logger.error(e.getMessage());
            Timings.log("REGISTER_ERROR", start, Timings.getTime());
            return new ErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "IOException", e.getMessage());
        }
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) RequestConfig(org.apache.http.client.config.RequestConfig) HttpEntity(org.apache.http.HttpEntity) SEPASecurityException(it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException) JsonObject(com.google.gson.JsonObject) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) RegistrationRequest(it.unibo.arces.wot.sepa.commons.request.RegistrationRequest) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) JsonElement(com.google.gson.JsonElement) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) ParseException(org.apache.http.ParseException) RegistrationResponse(it.unibo.arces.wot.sepa.commons.response.RegistrationResponse) JsonParser(com.google.gson.JsonParser)

Example 42 with RequestConfig

use of org.graylog.shaded.elasticsearch7.org.apache.http.client.config.RequestConfig in project SEPA by arces-wot.

the class KeycloakAuthenticationService method requestToken.

@Override
public Response requestToken(String authorization, int timeout) {
    /*
		 * POST /auth/realms/demo/protocol/openid-connect/token Authorization: Basic
		 * cHJvZHVjdC1zYS1jbGllbnQ6cGFzc3dvcmQ= Content-Type:
		 * application/x-www-form-urlencoded
		 * 
		 * grant_type=client_credentials
		 **/
    logger.log(Level.getLevel("oauth"), "TOKEN_REQUEST: " + authorization);
    CloseableHttpResponse response = null;
    long start = Timings.getTime();
    try {
        URI uri = new URI(oauthProperties.getTokenRequestUrl());
        HttpPost httpRequest = new HttpPost(uri);
        StringEntity body = new StringEntity("grant_type=client_credentials");
        httpRequest.setEntity(body);
        httpRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");
        httpRequest.setHeader("Authorization", authorization);
        // Set timeout
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).build();
        httpRequest.setConfig(requestConfig);
        try {
            response = httpClient.execute(httpRequest);
        // break;
        } catch (Exception e) {
            ErrorResponse err = new ErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getClass().getName(), e.getMessage());
            logger.error(err);
            return err;
        }
        logger.log(Level.getLevel("oauth"), "Response: " + response);
        HttpEntity entity = response.getEntity();
        String jsonResponse = EntityUtils.toString(entity, Charset.forName("UTF-8"));
        EntityUtils.consume(entity);
        // Parse response
        JsonObject json = new JsonParser().parse(jsonResponse).getAsJsonObject();
        if (json.has("error")) {
            Timings.log("TOKEN_REQUEST", start, Timings.getTime());
            ErrorResponse error = new ErrorResponse(response.getStatusLine().getStatusCode(), "token_request", json.get("error").getAsString());
            return error;
        }
        return new JWTResponse(json);
    } catch (Exception e) {
        logger.error(e.getMessage());
        Timings.log("TOKEN_REQUEST", start, Timings.getTime());
        return new ErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Exception", e.getMessage());
    } finally {
        try {
            if (response != null)
                response.close();
        } catch (IOException e) {
            logger.error(e.getMessage());
            Timings.log("TOKEN_REQUEST", start, Timings.getTime());
            return new ErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, "IOException", e.getMessage());
        }
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) RequestConfig(org.apache.http.client.config.RequestConfig) HttpEntity(org.apache.http.HttpEntity) JsonObject(com.google.gson.JsonObject) IOException(java.io.IOException) URI(java.net.URI) ParseException(org.apache.http.ParseException) SEPASecurityException(it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse) StringEntity(org.apache.http.entity.StringEntity) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) JsonParser(com.google.gson.JsonParser) JWTResponse(it.unibo.arces.wot.sepa.commons.response.JWTResponse)

Example 43 with RequestConfig

use of org.graylog.shaded.elasticsearch7.org.apache.http.client.config.RequestConfig in project uavstack by uavorg.

the class HttpAsyncClient method initCloseableHttpAsyncClient.

private CloseableHttpAsyncClient initCloseableHttpAsyncClient(int maxConnectionPerRoute, int maxTotalConnection, int sockTimeout, int connectTimeout, int requestTimeout) {
    ConnectingIOReactor ioReactor = null;
    try {
        ioReactor = new DefaultConnectingIOReactor();
    } catch (IOReactorException e) {
    // ignore
    }
    /**
     * 增加请求连接的相关超时
     */
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(sockTimeout).setConnectTimeout(connectTimeout).setConnectionRequestTimeout(requestTimeout).build();
    if (maxConnectionPerRoute > 0) {
        this.maxConnectionPerRoute = maxConnectionPerRoute;
    }
    if (maxTotalConnection > 0) {
        this.maxTotalConnection = maxTotalConnection;
    }
    PoolingNHttpClientConnectionManager cm = new PoolingNHttpClientConnectionManager(ioReactor);
    cm.setDefaultMaxPerRoute(this.maxConnectionPerRoute);
    cm.setMaxTotal(this.maxTotalConnection);
    return HttpAsyncClients.custom().setDefaultRequestConfig(requestConfig).setConnectionManager(cm).build();
}
Also used : ConnectingIOReactor(org.apache.http.nio.reactor.ConnectingIOReactor) DefaultConnectingIOReactor(org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor) DefaultConnectingIOReactor(org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor) IOReactorException(org.apache.http.nio.reactor.IOReactorException) RequestConfig(org.apache.http.client.config.RequestConfig) PoolingNHttpClientConnectionManager(org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager)

Example 44 with RequestConfig

use of org.graylog.shaded.elasticsearch7.org.apache.http.client.config.RequestConfig in project sldeditor by robward-scisys.

the class CheckUpdateGitHub method readDataFromURL.

/**
 * Read data from URL.
 *
 * @param url the url
 * @return the string
 */
protected String readDataFromURL(String url) {
    destinationReached = false;
    StringBuilder sb = new StringBuilder();
    if (url != null) {
        int timeout = 5;
        RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build();
        try (CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build()) {
            HttpGet getRequest = new HttpGet(url);
            getRequest.addHeader("accept", "application/json");
            HttpResponse response = httpClient.execute(getRequest);
            if (response.getStatusLine().getStatusCode() != 200) {
                ConsoleManager.getInstance().error(this, String.format("%s %s", Localisation.getField(CheckUpdatePanel.class, "CheckUpdateGitHub.httpError"), response.getStatusLine().getStatusCode()));
            } else {
                BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
                String output;
                while ((output = br.readLine()) != null) {
                    sb.append(output);
                }
                destinationReached = true;
            }
        } catch (IOException e) {
            ConsoleManager.getInstance().error(this, Localisation.getString(CheckUpdatePanel.class, "CheckUpdatePanel.destinationUnreachable"));
        }
    }
    return sb.toString();
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) InputStreamReader(java.io.InputStreamReader) HttpGet(org.apache.http.client.methods.HttpGet) BufferedReader(java.io.BufferedReader) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException)

Example 45 with RequestConfig

use of org.graylog.shaded.elasticsearch7.org.apache.http.client.config.RequestConfig in project spring-boot by Linda-Tan.

the class RestTemplateConfig method httpClient.

@Bean
public HttpClient httpClient() throws KeyManagementException, NoSuchAlgorithmException {
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", new SSLConnectionSocketFactory(createIgnoreVerifySSL())).build();
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
    connectionManager.setMaxTotal(5);
    connectionManager.setDefaultMaxPerRoute(5);
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(8000).setConnectTimeout(8000).setConnectionRequestTimeout(8000).build();
    return HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).setConnectionManager(connectionManager).build();
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) ConditionalOnMissingBean(org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean) Bean(org.springframework.context.annotation.Bean)

Aggregations

RequestConfig (org.apache.http.client.config.RequestConfig)344 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)146 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)97 HttpGet (org.apache.http.client.methods.HttpGet)94 IOException (java.io.IOException)78 HttpEntity (org.apache.http.HttpEntity)67 HttpPost (org.apache.http.client.methods.HttpPost)65 HttpResponse (org.apache.http.HttpResponse)60 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)55 URI (java.net.URI)46 StringEntity (org.apache.http.entity.StringEntity)43 Map (java.util.Map)41 Test (org.junit.Test)41 BasicCookieStore (org.apache.http.impl.client.BasicCookieStore)33 HttpHost (org.apache.http.HttpHost)32 PoolingHttpClientConnectionManager (org.apache.http.impl.conn.PoolingHttpClientConnectionManager)32 HttpClient (org.apache.http.client.HttpClient)31 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)27 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)24 SSLConnectionSocketFactory (org.apache.http.conn.ssl.SSLConnectionSocketFactory)24