Search in sources :

Example 1 with BasicScheme

use of org.apache.hc.client5.http.impl.auth.BasicScheme in project geo-platform by geosdi.

the class GeoSDIHttpClient5 method post.

/**
 * Executes an HTTP POST request against the provided URL, sending the contents of {@code
 * postContent} as the POST method body and setting the Content-Type request header to {@code
 * postContentType} if given, and returns the server response.
 *
 * <p>If an HTTP authentication {@link #getUser() user} and {@link #getPassword() password} is
 * set, the appropriate authentication HTTP header will be sent with the request.
 *
 * <p>If a {@link #getConnectTimeout() connection timeout} is set, the http connection will be
 * set to respect that timeout.
 *
 * <p>If a {@link #getReadTimeout() read timeout} is set, the http connection will be set to
 * respect it.
 *
 * @param url the URL against which to execute the POST request
 * @param postContent an input stream with the contents of the POST body
 * @param postContentType the MIME type of the contents sent as the request POST body, can be
 * {@code null}
 * @return the {@link HTTPResponse} encapsulating the response to the HTTP POST request
 */
@Override
public HTTPResponse post(URL url, InputStream postContent, String postContentType) throws IOException {
    HttpPost httpPost = new HttpPost(url.toExternalForm());
    logger.info("Inject OpenAM Cookie");
    if ((this.headers != null) && !(this.headers.isEmpty())) {
        List<String> values = this.headers.stream().map(value -> String.join("=", value.getHeaderKey(), value.getHeaderValue())).collect(toList());
        httpPost.setHeader("Cookie", String.join(";", values));
    }
    HttpEntity requestEntity = new InputStreamEntity(postContent, ContentType.create(postContentType));
    httpPost.setEntity(requestEntity);
    CloseableHttpResponse response = null;
    if (((this.user != null) && !(this.user.trim().isEmpty())) && ((this.password != null) && !(this.password.trim().isEmpty()))) {
        try {
            URI uri = url.toURI();
            HttpClientContext localContext = create();
            HttpHost targetHost = new HttpHost(uri.getScheme(), uri.getHost(), this.retrieveNoSetPort(uri));
            BasicScheme basicAuth = new BasicScheme();
            basicAuth.initPreemptive(new UsernamePasswordCredentials(this.user, this.password.toCharArray()));
            localContext.resetAuthExchange(targetHost, basicAuth);
            response = this.httpClient.execute(targetHost, httpPost, localContext);
        } catch (URISyntaxException ex) {
            throw new IOException("URISyntaxException error : " + ex.getMessage() + " for URL " + url.toExternalForm());
        }
    } else {
        response = this.httpClient.execute(httpPost);
    }
    int responseCode = response.getCode();
    if (200 != responseCode) {
        response.close();
        throw new IOException("Server returned HTTP error code " + responseCode + " for URL " + url.toExternalForm());
    } else {
        return new GeoSDIHttpClient5.HttpMethodResponse(response);
    }
}
Also used : GZIPInputStream(java.util.zip.GZIPInputStream) URL(java.net.URL) URISyntaxException(java.net.URISyntaxException) LoggerFactory(org.slf4j.LoggerFactory) ConnectionSocketFactory(org.apache.hc.client5.http.socket.ConnectionSocketFactory) BasicCredentialsProvider(org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider) URI(java.net.URI) TimeValue(org.apache.hc.core5.util.TimeValue) HttpRequestExecutor(org.apache.hc.core5.http.impl.io.HttpRequestExecutor) RegistryBuilder(org.apache.hc.core5.http.config.RegistryBuilder) HTTPClient(org.geotools.http.HTTPClient) List(java.util.List) HttpEntity(org.apache.hc.core5.http.HttpEntity) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) DefaultConnectionReuseStrategy(org.apache.hc.core5.http.impl.DefaultConnectionReuseStrategy) TRUE(java.lang.Boolean.TRUE) Timeout.of(org.apache.hc.core5.util.Timeout.of) HttpClientContext(org.apache.hc.client5.http.protocol.HttpClientContext) BasicScheme(org.apache.hc.client5.http.impl.auth.BasicScheme) MINUTES(java.util.concurrent.TimeUnit.MINUTES) HttpGet(org.apache.hc.client5.http.classic.methods.HttpGet) HttpClientConnectionManager(org.apache.hc.client5.http.io.HttpClientConnectionManager) InputStreamEntity(org.apache.hc.core5.http.io.entity.InputStreamEntity) Lists(com.google.common.collect.Lists) Charset(java.nio.charset.Charset) HTTPResponse(org.geotools.http.HTTPResponse) CloseableHttpResponse(org.apache.hc.client5.http.impl.classic.CloseableHttpResponse) RequestConfig(org.apache.hc.client5.http.config.RequestConfig) HttpClients(org.apache.hc.client5.http.impl.classic.HttpClients) Logger(org.slf4j.Logger) UsernamePasswordCredentials(org.apache.hc.client5.http.auth.UsernamePasswordCredentials) WMSHeaderParam(org.geosdi.geoplatform.services.request.WMSHeaderParam) UTF_8(java.nio.charset.StandardCharsets.UTF_8) Header(org.apache.hc.core5.http.Header) NoopHostnameVerifier(org.apache.hc.client5.http.ssl.NoopHostnameVerifier) IOException(java.io.IOException) PoolingHttpClientConnectionManager(org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager) HttpPost(org.apache.hc.client5.http.classic.methods.HttpPost) SSLConnectionSocketFactory(org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory) TimeUnit(java.util.concurrent.TimeUnit) SSLContextBuilder(org.apache.hc.core5.ssl.SSLContextBuilder) Collectors.toList(java.util.stream.Collectors.toList) HttpHost(org.apache.hc.core5.http.HttpHost) ContentType(org.apache.hc.core5.http.ContentType) PlainConnectionSocketFactory(org.apache.hc.client5.http.socket.PlainConnectionSocketFactory) Long.valueOf(java.lang.Long.valueOf) HttpClientContext.create(org.apache.hc.client5.http.protocol.HttpClientContext.create) CloseableHttpClient(org.apache.hc.client5.http.impl.classic.CloseableHttpClient) SECONDS(java.util.concurrent.TimeUnit.SECONDS) InputStream(java.io.InputStream) HttpPost(org.apache.hc.client5.http.classic.methods.HttpPost) BasicScheme(org.apache.hc.client5.http.impl.auth.BasicScheme) HttpEntity(org.apache.hc.core5.http.HttpEntity) HttpClientContext(org.apache.hc.client5.http.protocol.HttpClientContext) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) URI(java.net.URI) InputStreamEntity(org.apache.hc.core5.http.io.entity.InputStreamEntity) UsernamePasswordCredentials(org.apache.hc.client5.http.auth.UsernamePasswordCredentials) HttpHost(org.apache.hc.core5.http.HttpHost) CloseableHttpResponse(org.apache.hc.client5.http.impl.classic.CloseableHttpResponse)

Example 2 with BasicScheme

use of org.apache.hc.client5.http.impl.auth.BasicScheme in project wiremock by wiremock.

the class WireMockTestClient method getWithPreemptiveCredentials.

public WireMockResponse getWithPreemptiveCredentials(String url, int port, String username, String password) {
    HttpHost target = new HttpHost("localhost", port);
    CloseableHttpClient httpClient = httpClientWithPreemptiveAuth(target, username, password);
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(target, basicAuth);
    HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);
    try {
        HttpGet httpget = new HttpGet(url);
        ClassicHttpResponse response = httpClient.execute(target, httpget, localContext);
        return new WireMockResponse(response);
    } catch (IOException e) {
        return throwUnchecked(e, WireMockResponse.class);
    }
}
Also used : ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) CloseableHttpClient(org.apache.hc.client5.http.impl.classic.CloseableHttpClient) BasicScheme(org.apache.hc.client5.http.impl.auth.BasicScheme) HttpHost(org.apache.hc.core5.http.HttpHost) BasicAuthCache(org.apache.hc.client5.http.impl.auth.BasicAuthCache) AuthCache(org.apache.hc.client5.http.auth.AuthCache) HttpClientContext(org.apache.hc.client5.http.protocol.HttpClientContext) BasicAuthCache(org.apache.hc.client5.http.impl.auth.BasicAuthCache) IOException(java.io.IOException)

Example 3 with BasicScheme

use of org.apache.hc.client5.http.impl.auth.BasicScheme in project alfresco-process-services-project-sdk by OpenPj.

the class IntegrationTestUtils method importApp.

/**
 * This method will import and publish an APS application against an APS
 * instance
 *
 * @param appZipFile is the filename of the app that should be available in the
 *                   target/apps folder of the Integration Test module
 * @param username   is the username of a user that can import new applications
 *                   in APS
 * @param password   is the password of a user that can import new applications
 *                   in APS
 * @param protocol   of the APS instance
 * @param hostname   of the APS instance
 * @param port       of the APS instance
 */
public static void importApp(String appZipFile, String username, String password, String protocol, String hostname, Integer port) {
    Path resourceFourEyesAppZip = Paths.get("target", "apps", appZipFile);
    File file = resourceFourEyesAppZip.toFile();
    try {
        final BasicScheme basicAuth = new BasicScheme();
        basicAuth.initPreemptive(new UsernamePasswordCredentials(username, password.toCharArray()));
        final HttpHost target = new HttpHost(protocol, hostname, port);
        final HttpClientContext localContext = HttpClientContext.create();
        localContext.resetAuthExchange(target, basicAuth);
        try (final CloseableHttpClient httpclient = HttpClients.createDefault()) {
            final String publishAppUrl = protocol + "://" + hostname + ":" + port.toString() + PUBLISH_APP_ENDPOINT;
            final HttpPost httppost = new HttpPost(publishAppUrl);
            final FileBody binaryFile = new FileBody(file);
            final HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("file", binaryFile).build();
            httppost.setEntity(reqEntity);
            System.out.println("Importing app " + httppost);
            try (final CloseableHttpResponse response = httpclient.execute(httppost, localContext)) {
                System.out.println("----------------------------------------");
                System.out.println(response);
                final HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    System.out.println("Response content length: " + resEntity.getContentLength());
                }
                EntityUtils.consume(resEntity);
            }
        }
    } catch (FileNotFoundException e) {
        fail(e.getMessage(), e);
    } catch (IOException e) {
        fail(e.getMessage(), e);
    }
}
Also used : Path(java.nio.file.Path) BasicScheme(org.apache.hc.client5.http.impl.auth.BasicScheme) CloseableHttpClient(org.apache.hc.client5.http.impl.classic.CloseableHttpClient) HttpPost(org.apache.hc.client5.http.classic.methods.HttpPost) FileBody(org.apache.hc.client5.http.entity.mime.FileBody) HttpEntity(org.apache.hc.core5.http.HttpEntity) FileNotFoundException(java.io.FileNotFoundException) HttpClientContext(org.apache.hc.client5.http.protocol.HttpClientContext) IOException(java.io.IOException) UsernamePasswordCredentials(org.apache.hc.client5.http.auth.UsernamePasswordCredentials) HttpHost(org.apache.hc.core5.http.HttpHost) CloseableHttpResponse(org.apache.hc.client5.http.impl.classic.CloseableHttpResponse) File(java.io.File)

Example 4 with BasicScheme

use of org.apache.hc.client5.http.impl.auth.BasicScheme in project wiremock by wiremock.

the class WireMockTestClient method getWithPreemptiveCredentials.

public WireMockResponse getWithPreemptiveCredentials(String url, int port, String username, String password) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    BasicScheme basicAuth = new BasicScheme();
    basicAuth.initPreemptive(new UsernamePasswordCredentials(username, password.toCharArray()));
    HttpClientContext localContext = HttpClientContext.create();
    HttpHost target = new HttpHost("localhost", port);
    localContext.resetAuthExchange(target, basicAuth);
    try {
        HttpGet httpget = new HttpGet(url);
        ClassicHttpResponse response = httpClient.execute(target, httpget, localContext);
        return new WireMockResponse(response);
    } catch (IOException e) {
        return throwUnchecked(e, WireMockResponse.class);
    }
}
Also used : ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) CloseableHttpClient(org.apache.hc.client5.http.impl.classic.CloseableHttpClient) BasicScheme(org.apache.hc.client5.http.impl.auth.BasicScheme) HttpHost(org.apache.hc.core5.http.HttpHost) HttpClientContext(org.apache.hc.client5.http.protocol.HttpClientContext) IOException(java.io.IOException) UsernamePasswordCredentials(org.apache.hc.client5.http.auth.UsernamePasswordCredentials)

Example 5 with BasicScheme

use of org.apache.hc.client5.http.impl.auth.BasicScheme in project commons-vfs by apache.

the class Http5FileProvider method createHttpClientContext.

/**
 * Create an {@link HttpClientContext} object for an http4 file system.
 *
 * @param builder Configuration options builder for http4 provider
 * @param rootName The root path
 * @param fileSystemOptions The FileSystem options
 * @param authData The {@code UserAuthentiationData} object
 * @return an {@link HttpClientContext} object
 */
protected HttpClientContext createHttpClientContext(final Http5FileSystemConfigBuilder builder, final GenericFileName rootName, final FileSystemOptions fileSystemOptions, final UserAuthenticationData authData) {
    final HttpClientContext clientContext = HttpClientContext.create();
    final BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
    clientContext.setCredentialsProvider(credsProvider);
    final String username = UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData, UserAuthenticationData.USERNAME, UserAuthenticatorUtils.toChar(rootName.getUserName())));
    final char[] password = UserAuthenticatorUtils.getData(authData, UserAuthenticationData.PASSWORD, UserAuthenticatorUtils.toChar(rootName.getPassword()));
    if (!StringUtils.isEmpty(username)) {
        // set root port
        credsProvider.setCredentials(new AuthScope(rootName.getHostName(), rootName.getPort()), new UsernamePasswordCredentials(username, password));
    }
    final HttpHost proxyHost = getProxyHttpHost(builder, fileSystemOptions);
    if (proxyHost != null) {
        final UserAuthenticator proxyAuth = builder.getProxyAuthenticator(fileSystemOptions);
        if (proxyAuth != null) {
            final UserAuthenticationData proxyAuthData = UserAuthenticatorUtils.authenticate(proxyAuth, new UserAuthenticationData.Type[] { UserAuthenticationData.USERNAME, UserAuthenticationData.PASSWORD });
            if (proxyAuthData != null) {
                final UsernamePasswordCredentials proxyCreds = new UsernamePasswordCredentials(UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(proxyAuthData, UserAuthenticationData.USERNAME, null)), UserAuthenticatorUtils.getData(proxyAuthData, UserAuthenticationData.PASSWORD, null));
                // set proxy host port
                credsProvider.setCredentials(new AuthScope(proxyHost.getHostName(), proxyHost.getPort()), proxyCreds);
            }
            if (builder.isPreemptiveAuth(fileSystemOptions)) {
                final AuthCache authCache = new BasicAuthCache();
                final BasicScheme basicAuth = new BasicScheme();
                authCache.put(proxyHost, basicAuth);
                clientContext.setAuthCache(authCache);
            }
        }
    }
    return clientContext;
}
Also used : UserAuthenticationData(org.apache.commons.vfs2.UserAuthenticationData) BasicScheme(org.apache.hc.client5.http.impl.auth.BasicScheme) BasicCredentialsProvider(org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider) HttpHost(org.apache.hc.core5.http.HttpHost) UserAuthenticator(org.apache.commons.vfs2.UserAuthenticator) AuthScope(org.apache.hc.client5.http.auth.AuthScope) AuthCache(org.apache.hc.client5.http.auth.AuthCache) BasicAuthCache(org.apache.hc.client5.http.impl.auth.BasicAuthCache) HttpClientContext(org.apache.hc.client5.http.protocol.HttpClientContext) BasicAuthCache(org.apache.hc.client5.http.impl.auth.BasicAuthCache) UsernamePasswordCredentials(org.apache.hc.client5.http.auth.UsernamePasswordCredentials)

Aggregations

BasicScheme (org.apache.hc.client5.http.impl.auth.BasicScheme)9 HttpClientContext (org.apache.hc.client5.http.protocol.HttpClientContext)8 HttpHost (org.apache.hc.core5.http.HttpHost)8 UsernamePasswordCredentials (org.apache.hc.client5.http.auth.UsernamePasswordCredentials)7 IOException (java.io.IOException)6 CloseableHttpClient (org.apache.hc.client5.http.impl.classic.CloseableHttpClient)6 CloseableHttpResponse (org.apache.hc.client5.http.impl.classic.CloseableHttpResponse)5 HttpGet (org.apache.hc.client5.http.classic.methods.HttpGet)4 HttpEntity (org.apache.hc.core5.http.HttpEntity)3 FileNotFoundException (java.io.FileNotFoundException)2 URI (java.net.URI)2 URISyntaxException (java.net.URISyntaxException)2 AuthCache (org.apache.hc.client5.http.auth.AuthCache)2 HttpPost (org.apache.hc.client5.http.classic.methods.HttpPost)2 BasicAuthCache (org.apache.hc.client5.http.impl.auth.BasicAuthCache)2 BasicCredentialsProvider (org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider)2 Lists (com.google.common.collect.Lists)1 File (java.io.File)1 InputStream (java.io.InputStream)1 TRUE (java.lang.Boolean.TRUE)1