Example usage for org.apache.http.impl.client HttpClientBuilder setDefaultCredentialsProvider

List of usage examples for org.apache.http.impl.client HttpClientBuilder setDefaultCredentialsProvider

Introduction

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

Prototype

public final HttpClientBuilder setDefaultCredentialsProvider(final CredentialsProvider credentialsProvider) 

Source Link

Document

Assigns default CredentialsProvider instance which will be used for request execution if not explicitly set in the client execution context.

Usage

From source file:com.seyren.core.util.graphite.GraphiteHttpClient.java

private HttpClient createHttpClient() {
    HttpClientBuilder clientBuilder = HttpClientBuilder.create().useSystemProperties()
            .setConnectionManager(createConnectionManager())
            .setDefaultRequestConfig(RequestConfig.custom()
                    .setConnectionRequestTimeout(graphiteConnectionRequestTimeout)
                    .setConnectTimeout(graphiteConnectTimeout).setSocketTimeout(graphiteSocketTimeout).build());

    // Set auth header for graphite if username and password are provided
    if (!StringUtils.isEmpty(graphiteUsername) && !StringUtils.isEmpty(graphitePassword)) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(graphiteUsername, graphitePassword));
        clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        context.setAttribute("preemptive-auth", new BasicScheme());
        clientBuilder.addInterceptorFirst(new PreemptiveAuth());
    }/*  w ww  . j  a  v a2 s.co m*/

    return clientBuilder.build();
}

From source file:org.openscore.content.httpclient.ScoreHttpClient.java

public HttpComponents buildHttpComponents(HttpClientInputs httpClientInputs) {
    buildDefaultServices();//from w ww .j  a  v  a  2s  .c om

    URI uri = uriBuilder.setUrl(httpClientInputs.getUrl()).setQueryParams(httpClientInputs.getQueryParams())
            .setQueryParamsAreURLEncoded(httpClientInputs.getQueryParamsAreURLEncoded()).buildURI();

    ContentType theContentType = contentTypeBuilder.setContentType(httpClientInputs.getContentType())
            .setRequestCharacterSet(httpClientInputs.getRequestCharacterSet()).buildContentType();

    HttpEntity httpEntity = httpEntityBuilder.setFormParams(httpClientInputs.getFormParams())
            .setFormParamsAreURLEncoded(httpClientInputs.getFormParamsAreURLEncoded())
            .setBody(httpClientInputs.getBody()).setFilePath(httpClientInputs.getSourceFile())
            .setContentType(theContentType)
            .setMultipartValuesAreURLEncoded(httpClientInputs.getMultipartValuesAreURLEncoded())
            .setMultipartBodies(httpClientInputs.getMultipartBodies())
            .setMultipartFiles(httpClientInputs.getMultipartFiles())
            .setMultipartBodiesContentType(httpClientInputs.getMultipartBodiesContentType())
            .setMultipartFilesContentType(httpClientInputs.getMultipartFilesContentType())
            .setChunkedRequestEntity(httpClientInputs.getChunkedRequestEntity()).buildEntity();

    HttpRequestBase httpRequestBase = requestBuilder.setMethod(httpClientInputs.getMethod()).setUri(uri)
            .setEntity(httpEntity).build();

    List<Header> theHeaders = headersBuilder.setHeaders(httpClientInputs.getHeaders())
            .setContentType(theContentType)
            .setEntityContentType(httpEntity != null ? httpEntity.getContentType() : null).buildHeaders();

    RequestConfig requestConfig = requestConfigBuilder
            .setConnectionTimeout(httpClientInputs.getConnectTimeout())
            .setSocketTimeout(httpClientInputs.getSocketTimeout())
            .setFollowRedirects(httpClientInputs.getFollowRedirects())
            .setProxyHost(httpClientInputs.getProxyHost()).setProxyPort(httpClientInputs.getProxyPort())
            .buildRequestConfig();
    httpRequestBase.setConfig(requestConfig);

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    AuthTypes authTypes = new AuthTypes(httpClientInputs.getAuthType());

    CredentialsProvider credentialsProvider = credentialsProviderBuilder.setAuthTypes(authTypes)
            .setUsername(httpClientInputs.getUsername()).setPassword(httpClientInputs.getPassword())
            .setHost(uri.getHost()).setPort(String.valueOf(uri.getPort()))
            .setProxyUsername(httpClientInputs.getProxyUsername())
            .setProxyPassword(httpClientInputs.getProxyPassword()).setProxyHost(httpClientInputs.getProxyHost())
            .setProxyPort(httpClientInputs.getProxyPort()).buildCredentialsProvider();
    httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);

    Lookup<AuthSchemeProvider> authSchemeLookup = authSchemeProviderLookupBuilder.setAuthTypes(authTypes)
            .setHost(uri.getHost()).setHeaders(theHeaders)
            .setSkipPortAtKerberosDatabaseLookup(httpClientInputs.getKerberosSkipPortCheck())
            .setKerberosConfigFile(httpClientInputs.getKerberosConfFile())
            .setKerberosLoginConfigFile(httpClientInputs.getKerberosLoginConfFile())
            .setUsername(httpClientInputs.getUsername()).setPassword(httpClientInputs.getPassword())
            .buildAuthSchemeProviderLookup();
    httpClientBuilder.setDefaultAuthSchemeRegistry(authSchemeLookup);

    httpRequestBase.setHeaders(theHeaders.toArray(new Header[theHeaders.size()]));

    CookieStore cookieStore = httpClientInputs.getCookieStoreSessionObject() == null ? null
            : cookieStoreBuilder.setUseCookies(httpClientInputs.getUseCookies())
                    .setCookieStoreSessionObject(httpClientInputs.getCookieStoreSessionObject())
                    .buildCookieStore();
    if (cookieStore != null) {
        httpClientBuilder.setDefaultCookieStore(cookieStore);
    }

    SSLConnectionSocketFactory sslConnectionSocketFactory = sslConnectionSocketFactoryBuilder
            .setTrustAllRoots(httpClientInputs.getTrustAllRoots()).setKeystore(httpClientInputs.getKeystore())
            .setKeystorePassword(httpClientInputs.getKeystorePassword())
            .setTrustKeystore(httpClientInputs.getTrustKeystore())
            .setTrustPassword(httpClientInputs.getTrustPassword())
            .setX509HostnameVerifier(httpClientInputs.getX509HostnameVerifier()).build();

    String connectionKey = ConnectionManagerBuilder.buildConnectionManagerMapKey(
            httpClientInputs.getTrustAllRoots(), httpClientInputs.getX509HostnameVerifier(),
            httpClientInputs.getKeystore(), httpClientInputs.getTrustKeystore());
    PoolingHttpClientConnectionManager connManager = poolingHttpClientConnectionManagerBuilder
            .setConnectionManagerMapKey(connectionKey)
            .setConnectionPoolHolder(httpClientInputs.getConnectionPoolSessionObject())
            .setSslsf(sslConnectionSocketFactory)
            .setDefaultMaxPerRoute(httpClientInputs.getConnectionsMaxPerRoute())
            .setTotalMax(httpClientInputs.getConnectionsMaxTotal()).buildConnectionManager();

    httpClientBuilder.setConnectionManager(connManager);

    if (StringUtils.isEmpty(httpClientInputs.getKeepAlive())
            || Boolean.parseBoolean(httpClientInputs.getKeepAlive())) {
        httpClientBuilder.setConnectionReuseStrategy(DefaultConnectionReuseStrategy.INSTANCE);
    } else {
        httpClientBuilder.setConnectionReuseStrategy(NoConnectionReuseStrategy.INSTANCE);
    }

    CloseableHttpClient closeableHttpClient = httpClientBuilder.build();

    HttpClientContext context = contextBuilder.setAuthSchemeLookup(authSchemeLookup).setAuthTypes(authTypes)
            .setCredentialsProvider(credentialsProvider).setUri(uri)
            .setPreemptiveAuth(httpClientInputs.getPreemptiveAuth()).build();

    HttpComponents result = new HttpComponents();
    result.setCloseableHttpClient(closeableHttpClient);
    result.setHttpRequestBase(httpRequestBase);
    result.setHttpClientContext(context);
    result.setUri(uri);
    result.setConnManager(connManager);
    result.setCookieStore(cookieStore);
    return result;
}

From source file:com.urswolfer.gerrit.client.rest.http.GerritRestClient.java

private HttpClientBuilder getHttpClient(HttpContext httpContext) {
    HttpClientBuilder client = HttpClients.custom();

    client.useSystemProperties(); // see also: com.intellij.util.net.ssl.CertificateManager

    OkHttpClient c = new OkHttpClient();
    c.setFollowRedirects(true);// w ww.ja  va  2  s .c o m
    // we need to get redirected result after login (which is done with POST) for extracting xGerritAuth
    client.setRedirectStrategy(new LaxRedirectStrategy());

    c.setCookieHandler(cookieManager);

    c.setConnectTimeout(CONNECTION_TIMEOUT_MS, TimeUnit.MILLISECONDS);
    c.setReadTimeout(CONNECTION_TIMEOUT_MS, TimeUnit.MILLISECONDS);
    c.setWriteTimeout(CONNECTION_TIMEOUT_MS, TimeUnit.MILLISECONDS);

    CredentialsProvider credentialsProvider = getCredentialsProvider();
    client.setDefaultCredentialsProvider(credentialsProvider);

    if (authData.isLoginAndPasswordAvailable()) {
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(authData.getLogin(), authData.getPassword()));

        BasicScheme basicAuth = new BasicScheme();
        httpContext.setAttribute(PREEMPTIVE_AUTH, basicAuth);
        client.addInterceptorFirst(new PreemptiveAuthHttpRequestInterceptor(authData));
    }

    client.addInterceptorLast(new UserAgentHttpRequestInterceptor());

    for (HttpClientBuilderExtension httpClientBuilderExtension : httpClientBuilderExtensions) {
        client = httpClientBuilderExtension.extend(client, authData);
        credentialsProvider = httpClientBuilderExtension.extendCredentialProvider(client, credentialsProvider,
                authData);
    }

    return client;
}

From source file:io.cloudslang.content.httpclient.ScoreHttpClient.java

public HttpComponents buildHttpComponents(HttpClientInputs httpClientInputs) {
    buildDefaultServices();/*from w ww  . j  a  v  a2  s. c  o m*/

    URI uri = uriBuilder.setUrl(httpClientInputs.getUrl()).setQueryParams(httpClientInputs.getQueryParams())
            .setQueryParamsAreURLEncoded(httpClientInputs.getQueryParamsAreURLEncoded())
            .setQueryParamsAreFormEncoded(httpClientInputs.getQueryParamsAreFormEncoded()).buildURI();

    ContentType theContentType = contentTypeBuilder.setContentType(httpClientInputs.getContentType())
            .setRequestCharacterSet(httpClientInputs.getRequestCharacterSet()).buildContentType();

    HttpEntity httpEntity = httpEntityBuilder.setFormParams(httpClientInputs.getFormParams())
            .setFormParamsAreURLEncoded(httpClientInputs.getFormParamsAreURLEncoded())
            .setBody(httpClientInputs.getBody()).setFilePath(httpClientInputs.getSourceFile())
            .setContentType(theContentType)
            .setMultipartValuesAreURLEncoded(httpClientInputs.getMultipartValuesAreURLEncoded())
            .setMultipartBodies(httpClientInputs.getMultipartBodies())
            .setMultipartFiles(httpClientInputs.getMultipartFiles())
            .setMultipartBodiesContentType(httpClientInputs.getMultipartBodiesContentType())
            .setMultipartFilesContentType(httpClientInputs.getMultipartFilesContentType())
            .setChunkedRequestEntity(httpClientInputs.getChunkedRequestEntity()).buildEntity();

    HttpRequestBase httpRequestBase = requestBuilder.setMethod(httpClientInputs.getMethod()).setUri(uri)
            .setEntity(httpEntity).build();

    List<Header> theHeaders = headersBuilder.setHeaders(httpClientInputs.getHeaders())
            .setContentType(theContentType)
            .setEntityContentType(httpEntity != null ? httpEntity.getContentType() : null).buildHeaders();

    RequestConfig requestConfig = requestConfigBuilder
            .setConnectionTimeout(httpClientInputs.getConnectTimeout())
            .setSocketTimeout(httpClientInputs.getSocketTimeout())
            .setFollowRedirects(httpClientInputs.getFollowRedirects())
            .setProxyHost(httpClientInputs.getProxyHost()).setProxyPort(httpClientInputs.getProxyPort())
            .buildRequestConfig();
    httpRequestBase.setConfig(requestConfig);

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    AuthTypes authTypes = new AuthTypes(httpClientInputs.getAuthType());

    CredentialsProvider credentialsProvider = credentialsProviderBuilder.setAuthTypes(authTypes)
            .setUsername(httpClientInputs.getUsername()).setPassword(httpClientInputs.getPassword())
            .setHost(uri.getHost()).setPort(String.valueOf(uri.getPort()))
            .setProxyUsername(httpClientInputs.getProxyUsername())
            .setProxyPassword(httpClientInputs.getProxyPassword()).setProxyHost(httpClientInputs.getProxyHost())
            .setProxyPort(httpClientInputs.getProxyPort()).buildCredentialsProvider();
    httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);

    Lookup<AuthSchemeProvider> authSchemeLookup = authSchemeProviderLookupBuilder.setAuthTypes(authTypes)
            .setHost(uri.getHost()).setHeaders(theHeaders)
            .setSkipPortAtKerberosDatabaseLookup(httpClientInputs.getKerberosSkipPortCheck())
            .setKerberosConfigFile(httpClientInputs.getKerberosConfFile())
            .setKerberosLoginConfigFile(httpClientInputs.getKerberosLoginConfFile())
            .setUsername(httpClientInputs.getUsername()).setPassword(httpClientInputs.getPassword())
            .buildAuthSchemeProviderLookup();
    httpClientBuilder.setDefaultAuthSchemeRegistry(authSchemeLookup);

    httpRequestBase.setHeaders(theHeaders.toArray(new Header[theHeaders.size()]));

    CookieStore cookieStore = cookieStoreBuilder.setUseCookies(httpClientInputs.getUseCookies())
            .setCookieStoreSessionObject(httpClientInputs.getCookieStoreSessionObject()).buildCookieStore();
    if (cookieStore != null) {
        httpClientBuilder.setDefaultCookieStore(cookieStore);
    }

    SSLConnectionSocketFactory sslConnectionSocketFactory = sslConnectionSocketFactoryBuilder
            .setTrustAllRoots(httpClientInputs.getTrustAllRoots()).setKeystore(httpClientInputs.getKeystore())
            .setKeystorePassword(httpClientInputs.getKeystorePassword())
            .setTrustKeystore(httpClientInputs.getTrustKeystore())
            .setTrustPassword(httpClientInputs.getTrustPassword())
            .setX509HostnameVerifier(httpClientInputs.getX509HostnameVerifier()).build();

    String connectionKey = ConnectionManagerBuilder.buildConnectionManagerMapKey(
            httpClientInputs.getTrustAllRoots(), httpClientInputs.getX509HostnameVerifier(),
            httpClientInputs.getKeystore(), httpClientInputs.getTrustKeystore());
    PoolingHttpClientConnectionManager connManager = poolingHttpClientConnectionManagerBuilder
            .setConnectionManagerMapKey(connectionKey)
            .setConnectionPoolHolder(httpClientInputs.getConnectionPoolSessionObject())
            .setSslsf(sslConnectionSocketFactory)
            .setDefaultMaxPerRoute(httpClientInputs.getConnectionsMaxPerRoute())
            .setTotalMax(httpClientInputs.getConnectionsMaxTotal()).buildConnectionManager();

    httpClientBuilder.setConnectionManager(connManager);

    if (StringUtils.isEmpty(httpClientInputs.getKeepAlive())
            || Boolean.parseBoolean(httpClientInputs.getKeepAlive())) {
        httpClientBuilder.setConnectionReuseStrategy(DefaultConnectionReuseStrategy.INSTANCE);
    } else {
        httpClientBuilder.setConnectionReuseStrategy(NoConnectionReuseStrategy.INSTANCE);
    }

    CloseableHttpClient closeableHttpClient = httpClientBuilder.build();

    HttpClientContext context = contextBuilder.setAuthSchemeLookup(authSchemeLookup).setAuthTypes(authTypes)
            .setCredentialsProvider(credentialsProvider).setUri(uri)
            .setPreemptiveAuth(httpClientInputs.getPreemptiveAuth()).build();

    HttpComponents result = new HttpComponents();
    result.setCloseableHttpClient(closeableHttpClient);
    result.setHttpRequestBase(httpRequestBase);
    result.setHttpClientContext(context);
    result.setUri(uri);
    result.setConnManager(connManager);
    result.setCookieStore(cookieStore);
    result.setHttpClientBuilder(httpClientBuilder);
    return result;
}

From source file:org.openehealth.ipf.commons.ihe.fhir.SslAwareApacheRestfulClientFactory.java

protected synchronized HttpClient getNativeHttpClient() {
    if (httpClient == null) {

        // @formatter:off
        RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(getConnectTimeout())
                .setSocketTimeout(getSocketTimeout()).setConnectionRequestTimeout(getConnectionRequestTimeout())
                .setProxy(proxy).setStaleConnectionCheckEnabled(true).build();

        HttpClientBuilder builder = HttpClients.custom().useSystemProperties()
                .setDefaultRequestConfig(defaultRequestConfig).setMaxConnTotal(getPoolMaxTotal())
                .setMaxConnPerRoute(getPoolMaxPerRoute()).setConnectionTimeToLive(5, TimeUnit.SECONDS)
                .disableCookieManagement();

        if (securityInformation != null) {
            securityInformation.configureHttpClientBuilder(builder);
        }//from w ww  .  j av a  2s  .  co  m

        // Need to authenticate against proxy
        if (proxy != null && StringUtils.isNotBlank(getProxyUsername())
                && StringUtils.isNotBlank(getProxyPassword())) {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(new AuthScope(proxy.getHostName(), proxy.getPort()),
                    new UsernamePasswordCredentials(getProxyUsername(), getProxyPassword()));
            builder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
            builder.setDefaultCredentialsProvider(credentialsProvider);
        }

        httpClient = builder.build();
    }

    return httpClient;
}

From source file:org.asqatasun.util.http.HttpRequestHandler.java

private CloseableHttpClient getHttpClient(String url) {
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout)
            .setConnectTimeout(connectionTimeout).build();
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    httpClientBuilder.setDefaultRequestConfig(requestConfig);
    httpClientBuilder.setConnectionManager(new PoolingHttpClientConnectionManager());
    httpClientBuilder.setUserAgent(ASQATASUN_USER_AGENT);
    if (isProxySet(url)) {
        LOGGER.debug(("Set proxy with " + proxyHost + " and " + proxyPort));
        httpClientBuilder.setProxy(new HttpHost(proxyHost, Integer.valueOf(proxyPort)));
        if (isProxyCredentialSet()) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(proxyHost, Integer.valueOf(proxyPort)),
                    new UsernamePasswordCredentials(proxyUser, proxyPassword));
            httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
            LOGGER.debug(("Set proxy credentials " + proxyHost + " and " + proxyPort + " and " + proxyUser
                    + " and " + proxyPassword));
        }//  w w  w.java2 s .co m
    }
    return httpClientBuilder.build();
}

From source file:eu.europa.ec.markt.dss.validation102853.https.CommonsDataLoader.java

/**
 * Define the Credentials/*from w w w.  j  a  v a 2s  .c  o  m*/
 *
 * @param httpClientBuilder
 * @param url
 * @return
 * @throws java.net.MalformedURLException
 */
private HttpClientBuilder configCredentials(HttpClientBuilder httpClientBuilder, final String url)
        throws DSSException {

    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    for (final Map.Entry<HttpHost, UsernamePasswordCredentials> entry : authenticationMap.entrySet()) {

        final HttpHost httpHost = entry.getKey();
        final UsernamePasswordCredentials usernamePasswordCredentials = entry.getValue();
        credsProvider.setCredentials(new AuthScope(httpHost.getHostName(), httpHost.getPort()),
                usernamePasswordCredentials);
    }
    httpClientBuilder = httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
    httpClientBuilder = configureProxy(httpClientBuilder, credsProvider, url);
    return httpClientBuilder;
}

From source file:org.iipg.hurricane.jmx.client.JMXClientBuilder.java

private void setupProxyIfNeeded(HttpClientBuilder builder) {
    if (httpProxy != null) {
        builder.setProxy(new HttpHost(httpProxy.getHost(), httpProxy.getPort()));
        if (httpProxy.getUser() != null) {
            AuthScope proxyAuthScope = new AuthScope(httpProxy.getHost(), httpProxy.getPort());
            UsernamePasswordCredentials proxyCredentials = new UsernamePasswordCredentials(httpProxy.getUser(),
                    httpProxy.getPass());
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(proxyAuthScope, proxyCredentials);
            builder.setDefaultCredentialsProvider(credentialsProvider);
        }/*from  w w w.  j  av  a 2 s  .  c  o  m*/
    }
}

From source file:com.norconex.collector.http.client.impl.GenericHttpClientFactory.java

@Override
public HttpClient createHTTPClient(String userAgent) {
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setSslcontext(createSSLContext());
    builder.setSchemePortResolver(createSchemePortResolver());
    builder.setDefaultRequestConfig(createRequestConfig());
    builder.setProxy(createProxy());/*from w  w  w .j a va 2  s  .c  o  m*/
    builder.setDefaultCredentialsProvider(createCredentialsProvider());
    builder.setDefaultConnectionConfig(createConnectionConfig());
    builder.setUserAgent(userAgent);
    builder.setMaxConnTotal(maxConnections);
    //builder.setMaxConnPerRoute(maxConnPerRoute)
    buildCustomHttpClient(builder);

    //TODO Put in place a more permanent solution to the following
    //Fix GitHub #17 start
    RedirectStrategy strategy = createRedirectStrategy();
    if (strategy == null) {
        strategy = LaxRedirectStrategy.INSTANCE;
    }
    builder.setRedirectStrategy(new TargetURLRedirectStrategy(strategy));
    //Fix end

    HttpClient httpClient = builder.build();
    if (AUTH_METHOD_FORM.equalsIgnoreCase(authMethod)) {
        authenticateUsingForm(httpClient);
    }
    return httpClient;
}

From source file:com.evolveum.midpoint.notifications.impl.api.transports.SimpleSmsTransport.java

@Override
public void send(Message message, String transportName, Event event, Task task, OperationResult parentResult) {

    OperationResult result = parentResult.createSubresult(DOT_CLASS + "send");
    result.addArbitraryObjectCollectionAsParam("message recipient(s)", message.getTo());
    result.addParam("message subject", message.getSubject());

    SystemConfigurationType systemConfiguration = NotificationFunctionsImpl
            .getSystemConfiguration(cacheRepositoryService, result);
    if (systemConfiguration == null || systemConfiguration.getNotificationConfiguration() == null) {
        String msg = "No notifications are configured. SMS notification to " + message.getTo()
                + " will not be sent.";
        LOGGER.warn(msg);/*  w ww  .j a  v a  2 s  .  co  m*/
        result.recordWarning(msg);
        return;
    }

    String smsConfigName = StringUtils.substringAfter(transportName, NAME + ":");
    SmsConfigurationType found = null;
    for (SmsConfigurationType smsConfigurationType : systemConfiguration.getNotificationConfiguration()
            .getSms()) {
        if (StringUtils.isEmpty(smsConfigName) && smsConfigurationType.getName() == null
                || StringUtils.isNotEmpty(smsConfigName)
                        && smsConfigName.equals(smsConfigurationType.getName())) {
            found = smsConfigurationType;
            break;
        }
    }

    if (found == null) {
        String msg = "SMS configuration '" + smsConfigName + "' not found. SMS notification to "
                + message.getTo() + " will not be sent.";
        LOGGER.warn(msg);
        result.recordWarning(msg);
        return;
    }

    SmsConfigurationType smsConfigurationType = found;
    String logToFile = smsConfigurationType.getLogToFile();
    if (logToFile != null) {
        TransportUtil.logToFile(logToFile, TransportUtil.formatToFileNew(message, transportName), LOGGER);
    }
    String file = smsConfigurationType.getRedirectToFile();
    if (file != null) {
        writeToFile(message, file, null, emptyList(), null, result);
        return;
    }

    if (smsConfigurationType.getGateway().isEmpty()) {
        String msg = "SMS gateway(s) are not defined, notification to " + message.getTo()
                + " will not be sent.";
        LOGGER.warn(msg);
        result.recordWarning(msg);
        return;
    }

    String from;
    if (message.getFrom() != null) {
        from = message.getFrom();
    } else if (smsConfigurationType.getDefaultFrom() != null) {
        from = smsConfigurationType.getDefaultFrom();
    } else {
        from = "";
    }

    if (message.getTo().isEmpty()) {
        String msg = "There is no recipient to send the notification to.";
        LOGGER.warn(msg);
        result.recordWarning(msg);
        return;
    }

    List<String> to = message.getTo();
    assert to.size() > 0;

    for (SmsGatewayConfigurationType smsGatewayConfigurationType : smsConfigurationType.getGateway()) {
        OperationResult resultForGateway = result.createSubresult(DOT_CLASS + "send.forGateway");
        resultForGateway.addContext("gateway name", smsGatewayConfigurationType.getName());
        try {
            ExpressionVariables variables = getDefaultVariables(from, to, message);
            HttpMethodType method = defaultIfNull(smsGatewayConfigurationType.getMethod(), HttpMethodType.GET);
            ExpressionType urlExpression = defaultIfNull(smsGatewayConfigurationType.getUrlExpression(),
                    smsGatewayConfigurationType.getUrl());
            String url = evaluateExpressionChecked(urlExpression, variables, "sms gateway request url", task,
                    result);
            LOGGER.debug("Sending SMS to URL {} (method {})", url, method);
            if (url == null) {
                throw new IllegalArgumentException("No URL specified");
            }

            List<String> headersList = evaluateExpressionsChecked(
                    smsGatewayConfigurationType.getHeadersExpression(), variables,
                    "sms gateway request headers", task, result);
            LOGGER.debug("Using request headers:\n{}", headersList);

            String encoding = defaultIfNull(smsGatewayConfigurationType.getBodyEncoding(),
                    StandardCharsets.ISO_8859_1.name());
            String body = evaluateExpressionChecked(smsGatewayConfigurationType.getBodyExpression(), variables,
                    "sms gateway request body", task, result);
            LOGGER.debug("Using request body text (encoding: {}):\n{}", encoding, body);

            if (smsGatewayConfigurationType.getLogToFile() != null) {
                TransportUtil.logToFile(smsGatewayConfigurationType.getLogToFile(),
                        formatToFile(message, url, headersList, body), LOGGER);
            }
            if (smsGatewayConfigurationType.getRedirectToFile() != null) {
                writeToFile(message, smsGatewayConfigurationType.getRedirectToFile(), url, headersList, body,
                        resultForGateway);
                result.computeStatus();
                return;
            } else {
                HttpClientBuilder builder = HttpClientBuilder.create();
                String username = smsGatewayConfigurationType.getUsername();
                ProtectedStringType password = smsGatewayConfigurationType.getPassword();
                if (username != null) {
                    CredentialsProvider provider = new BasicCredentialsProvider();
                    String plainPassword = password != null ? protector.decryptString(password) : null;
                    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username,
                            plainPassword);
                    provider.setCredentials(AuthScope.ANY, credentials);
                    builder = builder.setDefaultCredentialsProvider(provider);
                }
                HttpClient client = builder.build();
                HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
                        client);
                ClientHttpRequest request = requestFactory.createRequest(new URI(url),
                        HttpUtil.toHttpMethod(method));
                setHeaders(request, headersList);
                if (body != null) {
                    request.getBody().write(body.getBytes(encoding));
                }
                ClientHttpResponse response = request.execute();
                LOGGER.debug("Result: " + response.getStatusCode() + "/" + response.getStatusText());
                if (response.getStatusCode().series() != HttpStatus.Series.SUCCESSFUL) {
                    throw new SystemException("SMS gateway communication failed: " + response.getStatusCode()
                            + ": " + response.getStatusText());
                }
                LOGGER.info("Message sent successfully to {} via gateway {}.", message.getTo(),
                        smsGatewayConfigurationType.getName());
                resultForGateway.recordSuccess();
                result.recordSuccess();
                return;
            }
        } catch (Throwable t) {
            String msg = "Couldn't send SMS to " + message.getTo() + " via "
                    + smsGatewayConfigurationType.getName() + ", trying another gateway, if there is any";
            LoggingUtils.logException(LOGGER, msg, t);
            resultForGateway.recordFatalError(msg, t);
        }
    }
    LOGGER.warn("No more SMS gateways to try, notification to " + message.getTo() + " will not be sent.");
    result.recordWarning("Notification to " + message.getTo() + " could not be sent.");
}