Search in sources :

Example 96 with CredentialsProvider

use of org.graylog.shaded.elasticsearch7.org.apache.http.client.CredentialsProvider in project midpoint by Evolveum.

the class LegacySimpleSmsTransport method send.

@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 = TransportUtil.getSystemConfiguration(repositoryService, 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);
        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();
    int optionsForFilteringRecipient = TransportUtil.optionsForFilteringRecipient(smsConfigurationType);
    List<String> allowedRecipientTo = new ArrayList<>();
    List<String> forbiddenRecipientTo = new ArrayList<>();
    if (optionsForFilteringRecipient != 0) {
        TransportUtil.validateRecipient(allowedRecipientTo, forbiddenRecipientTo, message.getTo(), smsConfigurationType, task, result, expressionFactory, MiscSchemaUtil.getExpressionProfile(), LOGGER);
        if (file != null) {
            if (!forbiddenRecipientTo.isEmpty()) {
                message.setTo(forbiddenRecipientTo);
                writeToFile(message, file, null, emptyList(), null, result);
            }
            message.setTo(allowedRecipientTo);
        }
    } else 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()) {
        if (optionsForFilteringRecipient != 0) {
            String msg = "After recipient validation there is no recipient to send the notification to.";
            LOGGER.debug(msg);
            result.recordSuccess();
        } else {
            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 {
            VariablesMap variables = getDefaultVariables(from, to, message);
            HttpMethodType method = defaultIfNull(smsGatewayConfigurationType.getMethod(), HttpMethodType.GET);
            ExpressionType urlExpression = defaultIfNull(smsGatewayConfigurationType.getUrlExpression(), null);
            String url = evaluateExpressionChecked(urlExpression, variables, "sms gateway request url", task, result);
            String proxyHost = smsGatewayConfigurationType.getProxyHost();
            String proxyPort = smsGatewayConfigurationType.getProxyPort();
            LOGGER.debug("Sending SMS to URL {} via proxy host {} and port {} (method {})", url, proxyHost, proxyPort, 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();
                CredentialsProvider provider = new BasicCredentialsProvider();
                if (username != null) {
                    String plainPassword = password != null ? protector.decryptString(password) : null;
                    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, plainPassword);
                    provider.setCredentials(AuthScope.ANY, credentials);
                    builder = builder.setDefaultCredentialsProvider(provider);
                }
                String proxyUsername = smsGatewayConfigurationType.getProxyUsername();
                ProtectedStringType proxyPassword = smsGatewayConfigurationType.getProxyPassword();
                if (StringUtils.isNotBlank(proxyHost)) {
                    HttpHost proxy;
                    if (StringUtils.isNotBlank(proxyPort) && isInteger(proxyPort)) {
                        int port = Integer.parseInt(proxyPort);
                        proxy = new HttpHost(proxyHost, port);
                    } else {
                        proxy = new HttpHost(proxyHost);
                    }
                    if (StringUtils.isNotBlank(proxyUsername)) {
                        String plainProxyPassword = proxyPassword != null ? protector.decryptString(proxyPassword) : null;
                        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(proxyUsername, plainProxyPassword);
                        provider.setCredentials(new AuthScope(proxy), credentials);
                    }
                    builder = builder.setDefaultCredentialsProvider(provider);
                    builder = builder.setProxy(proxy);
                }
                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.debug("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.");
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) ArrayList(java.util.ArrayList) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) ClientHttpRequest(org.springframework.http.client.ClientHttpRequest) URI(java.net.URI) HttpHost(org.apache.http.HttpHost) VariablesMap(com.evolveum.midpoint.schema.expression.VariablesMap) HttpComponentsClientHttpRequestFactory(org.springframework.http.client.HttpComponentsClientHttpRequestFactory) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) HttpClient(org.apache.http.client.HttpClient) AuthScope(org.apache.http.auth.AuthScope) ProtectedStringType(com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType) ClientHttpResponse(org.springframework.http.client.ClientHttpResponse)

Example 97 with CredentialsProvider

use of org.graylog.shaded.elasticsearch7.org.apache.http.client.CredentialsProvider in project Signal-Android by WhisperSystems.

the class LegacyMmsConnection method constructHttpClient.

protected CloseableHttpClient constructHttpClient() throws IOException {
    RequestConfig config = RequestConfig.custom().setConnectTimeout(20 * 1000).setConnectionRequestTimeout(20 * 1000).setSocketTimeout(20 * 1000).setMaxRedirects(20).build();
    URL mmsc = new URL(apn.getMmsc());
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    if (apn.hasAuthentication()) {
        credsProvider.setCredentials(new AuthScope(mmsc.getHost(), mmsc.getPort() > -1 ? mmsc.getPort() : mmsc.getDefaultPort()), new UsernamePasswordCredentials(apn.getUsername(), apn.getPassword()));
    }
    return HttpClients.custom().setConnectionReuseStrategy(new NoConnectionReuseStrategyHC4()).setRedirectStrategy(new LaxRedirectStrategy()).setUserAgent(TextSecurePreferences.getMmsUserAgent(context, USER_AGENT)).setConnectionManager(new BasicHttpClientConnectionManager()).setDefaultRequestConfig(config).setDefaultCredentialsProvider(credsProvider).build();
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) NoConnectionReuseStrategyHC4(org.apache.http.impl.NoConnectionReuseStrategyHC4) AuthScope(org.apache.http.auth.AuthScope) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) LaxRedirectStrategy(org.apache.http.impl.client.LaxRedirectStrategy) URL(java.net.URL) BasicHttpClientConnectionManager(org.apache.http.impl.conn.BasicHttpClientConnectionManager) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 98 with CredentialsProvider

use of org.graylog.shaded.elasticsearch7.org.apache.http.client.CredentialsProvider in project graylog2-server by Graylog2.

the class RestHighLevelClientProvider method buildClient.

private RestHighLevelClient buildClient(List<URI> hosts, Duration connectTimeout, Duration socketTimeout, int maxTotalConnections, int maxTotalConnectionsPerRoute, boolean useExpectContinue, boolean muteElasticsearchDeprecationWarnings, CredentialsProvider credentialsProvider) {
    final HttpHost[] esHosts = hosts.stream().map(uri -> new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme())).toArray(HttpHost[]::new);
    final RestClientBuilder restClientBuilder = RestClient.builder(esHosts).setRequestConfigCallback(requestConfig -> requestConfig.setConnectTimeout(Math.toIntExact(connectTimeout.toMilliseconds())).setSocketTimeout(Math.toIntExact(socketTimeout.toMilliseconds())).setExpectContinueEnabled(useExpectContinue).setAuthenticationEnabled(true)).setHttpClientConfigCallback(httpClientConfig -> {
        httpClientConfig.setMaxConnTotal(maxTotalConnections).setMaxConnPerRoute(maxTotalConnectionsPerRoute).setDefaultCredentialsProvider(credentialsProvider);
        if (muteElasticsearchDeprecationWarnings) {
            httpClientConfig.addInterceptorFirst(new ElasticsearchFilterDeprecationWarningsInterceptor());
        }
        return httpClientConfig;
    });
    return new RestHighLevelClient(restClientBuilder);
}
Also used : GracefulShutdownService(org.graylog2.system.shutdown.GracefulShutdownService) Provider(javax.inject.Provider) ElasticsearchNodesSniffer(org.graylog.shaded.elasticsearch7.org.elasticsearch.client.sniff.ElasticsearchNodesSniffer) Singleton(javax.inject.Singleton) Supplier(java.util.function.Supplier) RestClientBuilder(org.graylog.shaded.elasticsearch7.org.elasticsearch.client.RestClientBuilder) Inject(javax.inject.Inject) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) CredentialsProvider(org.graylog.shaded.elasticsearch7.org.apache.http.client.CredentialsProvider) Locale(java.util.Locale) RestClient(org.graylog.shaded.elasticsearch7.org.elasticsearch.client.RestClient) Sniffer(org.graylog.shaded.elasticsearch7.org.elasticsearch.client.sniff.Sniffer) Suppliers(com.google.common.base.Suppliers) Duration(com.github.joschi.jadconfig.util.Duration) Named(javax.inject.Named) URI(java.net.URI) RestHighLevelClient(org.graylog.shaded.elasticsearch7.org.elasticsearch.client.RestHighLevelClient) HttpHost(org.graylog.shaded.elasticsearch7.org.apache.http.HttpHost) NodesSniffer(org.graylog.shaded.elasticsearch7.org.elasticsearch.client.sniff.NodesSniffer) Nullable(javax.annotation.Nullable) HttpHost(org.graylog.shaded.elasticsearch7.org.apache.http.HttpHost) RestClientBuilder(org.graylog.shaded.elasticsearch7.org.elasticsearch.client.RestClientBuilder) RestHighLevelClient(org.graylog.shaded.elasticsearch7.org.elasticsearch.client.RestHighLevelClient)

Example 99 with CredentialsProvider

use of org.graylog.shaded.elasticsearch7.org.apache.http.client.CredentialsProvider in project openolat by klemens.

the class HttpClientFactory method getHttpClientInstance.

/**
 * @param host For basic authentication
 * @param port For basic authentication
 * @param user For basic authentication
 * @param password For basic authentication
 * @param redirect If redirect is allowed
 * @return CloseableHttpClient
 */
public static CloseableHttpClient getHttpClientInstance(String host, int port, String user, String password, boolean redirect) {
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketRegistry);
    SocketConfig.Builder socketConfigBuilder = SocketConfig.copy(SocketConfig.DEFAULT);
    socketConfigBuilder.setSoTimeout(10000);
    cm.setDefaultSocketConfig(socketConfigBuilder.build());
    HttpClientBuilder clientBuilder = HttpClientBuilder.create().setConnectionManager(cm).setMaxConnTotal(10).setDefaultCookieStore(new BasicCookieStore());
    if (redirect) {
        clientBuilder.setRedirectStrategy(new LaxRedirectStrategy());
    } else {
        clientBuilder.setRedirectStrategy(new NoRedirectStrategy());
    }
    if (user != null && user.length() > 0) {
        CredentialsProvider provider = new BasicCredentialsProvider();
        provider.setCredentials(new AuthScope(host, port), new UsernamePasswordCredentials(user, password));
        clientBuilder.setDefaultCredentialsProvider(provider);
    }
    return clientBuilder.build();
}
Also used : BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) SocketConfig(org.apache.http.config.SocketConfig) AuthScope(org.apache.http.auth.AuthScope) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) LaxRedirectStrategy(org.apache.http.impl.client.LaxRedirectStrategy) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 100 with CredentialsProvider

use of org.graylog.shaded.elasticsearch7.org.apache.http.client.CredentialsProvider in project gora by apache.

the class ElasticsearchStore method createClient.

public static RestHighLevelClient createClient(ElasticsearchParameters parameters) {
    RestClientBuilder clientBuilder = RestClient.builder(new HttpHost(parameters.getHost(), parameters.getPort()));
    // Choosing the authentication method.
    switch(parameters.getAuthenticationType()) {
        case BASIC:
            if (parameters.getUsername() != null && parameters.getPassword() != null) {
                final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(parameters.getUsername(), parameters.getPassword()));
                clientBuilder.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
            } else {
                throw new IllegalArgumentException("Missing username or password for BASIC authentication.");
            }
            break;
        case TOKEN:
            if (parameters.getAuthorizationToken() != null) {
                Header[] defaultHeaders = new Header[] { new BasicHeader("Authorization", parameters.getAuthorizationToken()) };
                clientBuilder.setDefaultHeaders(defaultHeaders);
            } else {
                throw new IllegalArgumentException("Missing authorization token for TOKEN authentication.");
            }
            break;
        case APIKEY:
            if (parameters.getApiKeyId() != null && parameters.getApiKeySecret() != null) {
                String apiKeyAuth = Base64.getEncoder().encodeToString((parameters.getApiKeyId() + ":" + parameters.getApiKeySecret()).getBytes(StandardCharsets.UTF_8));
                Header[] defaultHeaders = new Header[] { new BasicHeader("Authorization", "ApiKey " + apiKeyAuth) };
                clientBuilder.setDefaultHeaders(defaultHeaders);
            } else {
                throw new IllegalArgumentException("Missing API Key ID or API Key Secret for APIKEY authentication.");
            }
            break;
    }
    if (parameters.getConnectTimeout() != 0) {
        clientBuilder.setRequestConfigCallback(requestConfigBuilder -> requestConfigBuilder.setConnectTimeout(parameters.getConnectTimeout()));
    }
    if (parameters.getSocketTimeout() != 0) {
        clientBuilder.setRequestConfigCallback(requestConfigBuilder -> requestConfigBuilder.setSocketTimeout(parameters.getSocketTimeout()));
    }
    if (parameters.getIoThreadCount() != 0) {
        clientBuilder.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultIOReactorConfig(IOReactorConfig.custom().setIoThreadCount(parameters.getIoThreadCount()).build()));
    }
    return new RestHighLevelClient(clientBuilder);
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) Header(org.apache.http.Header) BasicHeader(org.apache.http.message.BasicHeader) HttpHost(org.apache.http.HttpHost) RestClientBuilder(org.elasticsearch.client.RestClientBuilder) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) RestHighLevelClient(org.elasticsearch.client.RestHighLevelClient) BasicHeader(org.apache.http.message.BasicHeader) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Aggregations

CredentialsProvider (org.apache.http.client.CredentialsProvider)271 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)223 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)201 AuthScope (org.apache.http.auth.AuthScope)138 HttpHost (org.apache.http.HttpHost)104 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)73 HttpGet (org.apache.http.client.methods.HttpGet)62 BasicScheme (org.apache.http.impl.auth.BasicScheme)49 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)48 HttpResponse (org.apache.http.HttpResponse)45 Test (org.junit.Test)44 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)41 HttpClientContext (org.apache.http.client.protocol.HttpClientContext)40 IOException (java.io.IOException)39 URI (java.net.URI)36 Credentials (org.apache.http.auth.Credentials)36 AuthCache (org.apache.http.client.AuthCache)33 BasicAuthCache (org.apache.http.impl.client.BasicAuthCache)33 HttpClient (org.apache.http.client.HttpClient)31 RequestConfig (org.apache.http.client.config.RequestConfig)29