Search in sources :

Example 16 with Credentials

use of org.apache.hc.client5.http.auth.Credentials in project jahia by Jahia.

the class CacheFilterHttpTest method getContent.

public String getContent(URL url, SimpleCredentials credentials, String requestId) throws IOException {
    String content;
    try (CloseableHttpResponse response = executeCall(url, credentials, requestId)) {
        assertEquals("Bad result code", HttpServletResponse.SC_OK, response.getCode());
        content = EntityUtils.toString(response.getEntity());
    } catch (ParseException e) {
        throw new IOException(e);
    }
    return content;
}
Also used : CloseableHttpResponse(org.apache.hc.client5.http.impl.classic.CloseableHttpResponse) ParseException(org.apache.hc.core5.http.ParseException) IOException(java.io.IOException)

Example 17 with Credentials

use of org.apache.hc.client5.http.auth.Credentials in project gradle-download-task by michel-kraemer.

the class DownloadAction method openConnection.

/**
 * Opens a connection to the given HTTP host and requests a file. Checks
 * the last-modified header on the server if the given timestamp is
 * greater than 0.
 * @param httpHost the HTTP host to connect to
 * @param file the file to request
 * @param timestamp the timestamp of the destination file, in milliseconds
 * @param etag the cached ETag for the requested host and file
 * @param client the HTTP client to use to perform the request
 * @return the URLConnection
 * @throws IOException if the connection could not be opened
 */
private CloseableHttpResponse openConnection(HttpHost httpHost, String file, long timestamp, String etag, CloseableHttpClient client) throws IOException {
    // configure authentication
    HttpClientContext context = null;
    if (username != null && password != null) {
        context = HttpClientContext.create();
        Credentials c = new UsernamePasswordCredentials(username, password.toCharArray());
        addAuthentication(httpHost, c, context);
    }
    // create request
    HttpGet get = new HttpGet(file);
    // configure timeouts
    RequestConfig config = RequestConfig.custom().setConnectTimeout(Timeout.ofMilliseconds(connectTimeoutMs)).setConnectionRequestTimeout(Timeout.ofMilliseconds(connectTimeoutMs)).setResponseTimeout(Timeout.ofMilliseconds(readTimeoutMs)).setContentCompressionEnabled(compress).build();
    get.setConfig(config);
    // add authentication information for proxy
    String scheme = httpHost.getSchemeName();
    String proxyHost = System.getProperty(scheme + ".proxyHost");
    String proxyPort = System.getProperty(scheme + ".proxyPort");
    String proxyUser = System.getProperty(scheme + ".proxyUser");
    String proxyPassword = System.getProperty(scheme + ".proxyPassword");
    if (proxyHost != null && proxyPort != null && proxyUser != null && proxyPassword != null) {
        if (context == null) {
            context = HttpClientContext.create();
        }
        int nProxyPort = Integer.parseInt(proxyPort);
        HttpHost proxy = new HttpHost(scheme, proxyHost, nProxyPort);
        Credentials credentials = new UsernamePasswordCredentials(proxyUser, proxyPassword.toCharArray());
        addAuthentication(proxy, credentials, context);
    }
    // set If-Modified-Since header
    if (timestamp > 0) {
        get.setHeader("If-Modified-Since", DateUtils.formatDate(new Date(timestamp)));
    }
    // set If-None-Match header
    if (etag != null) {
        get.setHeader("If-None-Match", etag);
    }
    // set headers
    if (headers != null) {
        for (Map.Entry<String, String> headerEntry : headers.entrySet()) {
            get.addHeader(headerEntry.getKey(), headerEntry.getValue());
        }
    }
    // execute request
    CloseableHttpResponse response = client.execute(httpHost, get, context);
    // handle response
    int code = response.getCode();
    if ((code < 200 || code > 299) && code != HttpStatus.SC_NOT_MODIFIED) {
        String phrase = response.getReasonPhrase();
        String url = httpHost + file;
        if (phrase == null || phrase.isEmpty()) {
            phrase = "HTTP status code: " + code + ", URL: " + url;
        } else {
            phrase += " (HTTP status code: " + code + ", URL: " + url + ")";
        }
        response.close();
        throw new ClientProtocolException(phrase);
    }
    return response;
}
Also used : RequestConfig(org.apache.hc.client5.http.config.RequestConfig) HttpGet(org.apache.hc.client5.http.classic.methods.HttpGet) HttpClientContext(org.apache.hc.client5.http.protocol.HttpClientContext) Date(java.util.Date) UsernamePasswordCredentials(org.apache.hc.client5.http.auth.UsernamePasswordCredentials) ClientProtocolException(org.apache.hc.client5.http.ClientProtocolException) HttpHost(org.apache.hc.core5.http.HttpHost) CloseableHttpResponse(org.apache.hc.client5.http.impl.classic.CloseableHttpResponse) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) Credentials(org.apache.hc.client5.http.auth.Credentials) UsernamePasswordCredentials(org.apache.hc.client5.http.auth.UsernamePasswordCredentials)

Example 18 with Credentials

use of org.apache.hc.client5.http.auth.Credentials in project gradle-download-task by michel-kraemer.

the class DownloadAction method addAuthentication.

/**
 * Add authentication information for the given host
 * @param host the host
 * @param credentials the credentials
 * @param context the context in which the authentication information
 * should be saved
 */
private void addAuthentication(HttpHost host, Credentials credentials, HttpClientContext context) {
    AuthCache authCache = context.getAuthCache();
    if (authCache == null) {
        authCache = new BasicAuthCache();
        context.setAuthCache(authCache);
    }
    CredentialsProvider credsProvider = context.getCredentialsProvider();
    if (credsProvider == null) {
        credsProvider = new BasicCredentialsProvider();
        context.setCredentialsProvider(credsProvider);
    }
    ((CredentialsStore) credsProvider).setCredentials(new AuthScope(host), credentials);
}
Also used : BasicCredentialsProvider(org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider) AuthCache(org.apache.hc.client5.http.auth.AuthCache) BasicAuthCache(org.apache.hc.client5.http.impl.auth.BasicAuthCache) CredentialsStore(org.apache.hc.client5.http.auth.CredentialsStore) AuthScope(org.apache.hc.client5.http.auth.AuthScope) BasicAuthCache(org.apache.hc.client5.http.impl.auth.BasicAuthCache) BasicCredentialsProvider(org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider) CredentialsProvider(org.apache.hc.client5.http.auth.CredentialsProvider)

Example 19 with Credentials

use of org.apache.hc.client5.http.auth.Credentials in project sms-java-client by altiria.

the class AltiriaClient method sendSms.

/**
 * Send a SMS.
 * @param textMessage this object contains the SMS data. See AltiriaModelTextMessage class.
 * @return Json response.
 * @throws Exception
 */
public String sendSms(AltiriaModelTextMessage textMessage) throws Exception {
    log.debug("Altiria-sendSms CMD: " + textMessage.toString());
    String jsonResponse = null;
    try {
        JsonObject jsonObject = new JsonObject();
        JsonObject credentialsJsonObject = new JsonObject();
        JsonObject messageJsonObject = new JsonObject();
        JsonArray destinationsJsonArray = null;
        if (this.login == null) {
            log.error("ERROR: The login parameter is mandatory");
            throw new JsonException("LOGIN_NOT_NULL");
        }
        if (this.passwd == null) {
            log.error("ERROR: The password parameter is mandatory");
            throw new JsonException("PASSWORD_NOT_NULL");
        }
        if (textMessage.getDestination() == null || textMessage.getDestination().trim().isEmpty()) {
            log.error("ERROR: The destination parameter is mandatory");
            throw new AltiriaGwException("INVALID_DESTINATION", "015");
        } else {
            destinationsJsonArray = new JsonArray();
            destinationsJsonArray.add(new JsonPrimitive(new String(textMessage.getDestination())));
        }
        if (textMessage.getMessage() == null || textMessage.getMessage().trim().isEmpty()) {
            log.error("ERROR: The message parameter is mandatory");
            throw new AltiriaGwException("EMPTY_MESSAGE", "017");
        } else
            messageJsonObject.addProperty("msg", textMessage.getMessage());
        if (textMessage.getSenderId() != null && !textMessage.getSenderId().trim().isEmpty())
            messageJsonObject.addProperty("senderId", textMessage.getSenderId());
        if (textMessage.isAck()) {
            messageJsonObject.addProperty("ack", true);
            if (textMessage.getIdAck() != null && !textMessage.getIdAck().trim().isEmpty())
                messageJsonObject.addProperty("idAck", textMessage.getIdAck());
        }
        if (textMessage.isConcat())
            messageJsonObject.addProperty("concat", true);
        if (textMessage.isCertDelivery())
            messageJsonObject.addProperty("certDelivery", true);
        if (textMessage.getEncoding() != null && textMessage.getEncoding().equals("unicode"))
            messageJsonObject.addProperty("encoding", "unicode");
        credentialsJsonObject.addProperty(this.isApiKey ? "apikey" : "login", this.login);
        credentialsJsonObject.addProperty(this.isApiKey ? "apisecret" : "passwd", this.passwd);
        jsonObject.add("credentials", credentialsJsonObject);
        jsonObject.add("destination", destinationsJsonArray);
        jsonObject.add("message", messageJsonObject);
        jsonObject.addProperty("source", source);
        RequestConfig config = RequestConfig.custom().setConnectTimeout(this.connectionTimeout, TimeUnit.MILLISECONDS).setResponseTimeout(this.timeout, TimeUnit.MILLISECONDS).build();
        HttpClientBuilder builder = HttpClientBuilder.create();
        builder.setDefaultRequestConfig(config);
        CloseableHttpClient httpClient = builder.build();
        HttpPost request = new HttpPost(this.urlBase + "/sendSms");
        final HttpEntity[] entity = { HttpEntities.create(jsonObject.toString(), ContentType.APPLICATION_JSON.withCharset(StandardCharsets.UTF_8)) };
        request.setEntity(entity[0]);
        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(request);
            jsonResponse = EntityUtils.toString(httpResponse.getEntity());
            log.debug("HTTP status:" + httpResponse.getCode());
            log.debug("HTTP body:" + jsonResponse);
            LinkedTreeMap<String, Object> mapBody = gson.fromJson(jsonResponse, new TypeToken<LinkedTreeMap<String, Object>>() {
            }.getType());
            if (httpResponse.getCode() != 200) {
                log.error("ERROR: Invalid request: " + jsonResponse);
                String errorMsg = (String) mapBody.get("error");
                throw new JsonException(errorMsg);
            } else {
                String status = (String) mapBody.get("status");
                if (!status.equals("000")) {
                    String errorMsg = getStatus(status);
                    log.error("ERROR: Invalid parameter. Error message: " + errorMsg + ", Status: " + status);
                    throw new AltiriaGwException(errorMsg, status);
                }
            }
        } catch (ConnectTimeoutException cte) {
            log.error("ERROR: Connection timeout");
            throw new ConnectionException("CONNECTION_TIMEOUT");
        } catch (SocketTimeoutException ste) {
            log.error("ERROR: Response timeout");
            throw new ConnectionException("RESPONSE_TIMEOUT");
        } finally {
            try {
                if (httpResponse != null)
                    httpResponse.close();
                if (httpClient != null)
                    httpClient.close();
            } catch (IOException ioe) {
                log.error("ERROR closing resources");
            }
        }
    } catch (GeneralAltiriaException e) {
        throw e;
    } catch (Exception e) {
        log.error("ERROR: Unexpected error", e);
        throw new AltiriaGwException("GENERAL_ERROR", "001");
    }
    return jsonResponse;
}
Also used : JsonException(com.altiria.app.exception.JsonException) RequestConfig(org.apache.hc.client5.http.config.RequestConfig) CloseableHttpClient(org.apache.hc.client5.http.impl.classic.CloseableHttpClient) HttpPost(org.apache.hc.client5.http.classic.methods.HttpPost) HttpEntity(org.apache.hc.core5.http.HttpEntity) JsonPrimitive(com.google.gson.JsonPrimitive) JsonObject(com.google.gson.JsonObject) HttpClientBuilder(org.apache.hc.client5.http.impl.classic.HttpClientBuilder) IOException(java.io.IOException) GeneralAltiriaException(com.altiria.app.exception.GeneralAltiriaException) SocketTimeoutException(java.net.SocketTimeoutException) ConnectTimeoutException(org.apache.hc.client5.http.ConnectTimeoutException) AltiriaGwException(com.altiria.app.exception.AltiriaGwException) ConnectionException(com.altiria.app.exception.ConnectionException) IOException(java.io.IOException) JsonException(com.altiria.app.exception.JsonException) JsonArray(com.google.gson.JsonArray) GeneralAltiriaException(com.altiria.app.exception.GeneralAltiriaException) SocketTimeoutException(java.net.SocketTimeoutException) TypeToken(com.google.gson.reflect.TypeToken) CloseableHttpResponse(org.apache.hc.client5.http.impl.classic.CloseableHttpResponse) AltiriaGwException(com.altiria.app.exception.AltiriaGwException) JsonObject(com.google.gson.JsonObject) ConnectionException(com.altiria.app.exception.ConnectionException) ConnectTimeoutException(org.apache.hc.client5.http.ConnectTimeoutException)

Example 20 with Credentials

use of org.apache.hc.client5.http.auth.Credentials in project sms-java-client by altiria.

the class AltiriaClient method getCredit.

/**
 * Get the user credit.
 * @return credit
 * @throws Exception
 */
public String getCredit() throws Exception {
    log.debug("Altiria-getCredit CMD");
    String credit = null;
    try {
        if (this.login == null) {
            log.error("ERROR: The login parameter is mandatory");
            throw new JsonException("LOGIN_NOT_NULL");
        }
        if (this.passwd == null) {
            log.error("ERROR: The password parameter is mandatory");
            throw new JsonException("PASSWORD_NOT_NULL");
        }
        JsonObject jsonObject = new JsonObject();
        JsonObject credentialsJsonObject = new JsonObject();
        credentialsJsonObject.addProperty(this.isApiKey ? "apikey" : "login", this.login);
        credentialsJsonObject.addProperty(this.isApiKey ? "apisecret" : "passwd", this.passwd);
        jsonObject.add("credentials", credentialsJsonObject);
        jsonObject.addProperty("source", source);
        RequestConfig config = RequestConfig.custom().setConnectTimeout(this.connectionTimeout, TimeUnit.MILLISECONDS).setResponseTimeout(this.timeout, TimeUnit.MILLISECONDS).build();
        HttpClientBuilder builder = HttpClientBuilder.create();
        builder.setDefaultRequestConfig(config);
        CloseableHttpClient httpClient = builder.build();
        HttpPost request = new HttpPost(this.urlBase + "/getCredit");
        final HttpEntity[] entity = { HttpEntities.create(jsonObject.toString(), ContentType.APPLICATION_JSON.withCharset(StandardCharsets.UTF_8)) };
        request.setEntity(entity[0]);
        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(request);
            String jsonResponse = EntityUtils.toString(httpResponse.getEntity());
            log.debug("HTTP status:" + httpResponse.getCode());
            log.debug("HTTP body:" + jsonResponse);
            LinkedTreeMap<String, Object> mapBody = gson.fromJson(jsonResponse, new TypeToken<LinkedTreeMap<String, Object>>() {
            }.getType());
            if (httpResponse.getCode() != 200) {
                log.error("ERROR: Invalid request: " + jsonResponse);
                String errorMsg = (String) mapBody.get("error");
                throw new JsonException(errorMsg);
            } else {
                String status = (String) mapBody.get("status");
                if (!status.equals("000")) {
                    String errorMsg = getStatus(status);
                    log.error("ERROR: Invalid parameter. Error message: " + errorMsg + ", Status: " + status);
                    throw new AltiriaGwException(errorMsg, status);
                } else
                    credit = (String) mapBody.get("credit");
            }
        } catch (ConnectTimeoutException cte) {
            log.error("ERROR: Connection timeout");
            throw new ConnectionException("CONNECTION_TIMEOUT");
        } catch (SocketTimeoutException ste) {
            log.error("ERROR: Response timeout");
            throw new ConnectionException("RESPONSE_TIMEOUT");
        } finally {
            try {
                if (httpResponse != null)
                    httpResponse.close();
                if (httpClient != null)
                    httpClient.close();
            } catch (IOException ioe) {
                log.error("ERROR closing resources");
            }
        }
    } catch (GeneralAltiriaException e) {
        throw e;
    } catch (Exception e) {
        log.error("ERROR: Unexpected error", e);
        throw new AltiriaGwException("GENERAL_ERROR", "001");
    }
    return credit;
}
Also used : JsonException(com.altiria.app.exception.JsonException) RequestConfig(org.apache.hc.client5.http.config.RequestConfig) CloseableHttpClient(org.apache.hc.client5.http.impl.classic.CloseableHttpClient) HttpPost(org.apache.hc.client5.http.classic.methods.HttpPost) HttpEntity(org.apache.hc.core5.http.HttpEntity) JsonObject(com.google.gson.JsonObject) HttpClientBuilder(org.apache.hc.client5.http.impl.classic.HttpClientBuilder) IOException(java.io.IOException) GeneralAltiriaException(com.altiria.app.exception.GeneralAltiriaException) SocketTimeoutException(java.net.SocketTimeoutException) ConnectTimeoutException(org.apache.hc.client5.http.ConnectTimeoutException) AltiriaGwException(com.altiria.app.exception.AltiriaGwException) ConnectionException(com.altiria.app.exception.ConnectionException) IOException(java.io.IOException) JsonException(com.altiria.app.exception.JsonException) GeneralAltiriaException(com.altiria.app.exception.GeneralAltiriaException) SocketTimeoutException(java.net.SocketTimeoutException) TypeToken(com.google.gson.reflect.TypeToken) CloseableHttpResponse(org.apache.hc.client5.http.impl.classic.CloseableHttpResponse) JsonObject(com.google.gson.JsonObject) AltiriaGwException(com.altiria.app.exception.AltiriaGwException) ConnectionException(com.altiria.app.exception.ConnectionException) ConnectTimeoutException(org.apache.hc.client5.http.ConnectTimeoutException)

Aggregations

UsernamePasswordCredentials (org.apache.hc.client5.http.auth.UsernamePasswordCredentials)13 AuthScope (org.apache.hc.client5.http.auth.AuthScope)8 Credentials (org.apache.hc.client5.http.auth.Credentials)8 BasicCredentialsProvider (org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider)6 IOException (java.io.IOException)5 HttpGet (org.apache.hc.client5.http.classic.methods.HttpGet)5 RequestConfig (org.apache.hc.client5.http.config.RequestConfig)5 CloseableHttpClient (org.apache.hc.client5.http.impl.classic.CloseableHttpClient)5 CloseableHttpResponse (org.apache.hc.client5.http.impl.classic.CloseableHttpResponse)5 NTCredentials (org.apache.hc.client5.http.auth.NTCredentials)4 HttpHost (org.apache.hc.core5.http.HttpHost)4 CredentialsStore (org.apache.hc.client5.http.auth.CredentialsStore)3 HttpEntity (org.apache.hc.core5.http.HttpEntity)3 AltiriaGwException (com.altiria.app.exception.AltiriaGwException)2 ConnectionException (com.altiria.app.exception.ConnectionException)2 GeneralAltiriaException (com.altiria.app.exception.GeneralAltiriaException)2 JsonException (com.altiria.app.exception.JsonException)2 JsonObject (com.google.gson.JsonObject)2 TypeToken (com.google.gson.reflect.TypeToken)2 SocketTimeoutException (java.net.SocketTimeoutException)2