Search in sources :

Example 76 with HttpHost

use of org.graylog.shaded.elasticsearch7.org.apache.http.HttpHost in project geode by apache.

the class GeodeRestClient method doRequest.

public HttpResponse doRequest(HttpRequestBase request, String username, String password) throws Exception {
    HttpHost targetHost = new HttpHost(bindAddress, restPort, protocol);
    HttpClientBuilder clientBuilder = HttpClients.custom();
    HttpClientContext clientContext = HttpClientContext.create();
    // configures the clientBuilder and clientContext
    if (username != null) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(username, password));
        clientBuilder.setDefaultCredentialsProvider(credsProvider);
    }
    if (useHttps) {
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
        clientBuilder.setSSLContext(ctx);
        clientBuilder.setSSLHostnameVerifier(new NoopHostnameVerifier());
    }
    return clientBuilder.build().execute(targetHost, request, clientContext);
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) SecureRandom(java.security.SecureRandom) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) SSLContext(javax.net.ssl.SSLContext) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 77 with HttpHost

use of org.graylog.shaded.elasticsearch7.org.apache.http.HttpHost in project opennms by OpenNMS.

the class HttpClientWrapper method enablePreemptiveAuth.

protected void enablePreemptiveAuth(final HttpClientBuilder builder) {
    /**
     * Add an HttpRequestInterceptor that will perform preemptive authentication
     * @see http://hc.apache.org/httpcomponents-client-4.0.1/tutorial/html/authentication.html
     */
    final HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {

        @Override
        public void process(final HttpRequest request, final HttpContext context) throws IOException {
            if (context instanceof HttpClientContext) {
                final HttpClientContext clientContext = (HttpClientContext) context;
                final AuthState authState = clientContext.getTargetAuthState();
                final CredentialsProvider credsProvider = clientContext.getCredentialsProvider();
                final HttpHost targetHost = clientContext.getTargetHost();
                // If not authentication scheme has been initialized yet
                if (authState.getAuthScheme() == null) {
                    final AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                    // Obtain credentials matching the target host
                    final Credentials creds = credsProvider.getCredentials(authScope);
                    // If found, generate BasicScheme preemptively
                    if (creds != null) {
                        authState.update(new BasicScheme(), creds);
                    }
                }
            } else {
                throw new IllegalArgumentException("Not sure how to handle a non-HttpClientContext context.");
            }
        }
    };
    builder.addInterceptorFirst(preemptiveAuth);
}
Also used : HttpRequest(org.apache.http.HttpRequest) BasicScheme(org.apache.http.impl.auth.BasicScheme) AuthState(org.apache.http.auth.AuthState) HttpHost(org.apache.http.HttpHost) HttpRequestInterceptor(org.apache.http.HttpRequestInterceptor) HttpContext(org.apache.http.protocol.HttpContext) AuthScope(org.apache.http.auth.AuthScope) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) Credentials(org.apache.http.auth.Credentials) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 78 with HttpHost

use of org.graylog.shaded.elasticsearch7.org.apache.http.HttpHost in project knime-core by knime.

the class ProfileManager method downloadProfiles.

private Path downloadProfiles(final URI profileLocation) {
    Path stateDir = getStateLocation();
    Path profileDir = stateDir.resolve("profiles");
    try {
        Files.createDirectories(stateDir);
        URIBuilder builder = new URIBuilder(profileLocation);
        builder.addParameter("profiles", String.join(",", m_provider.getRequestedProfiles()));
        URI profileUri = builder.build();
        m_collectedLogs.add(() -> NodeLogger.getLogger(ProfileManager.class).info("Downloading profiles from " + profileUri));
        // proxies
        HttpHost proxy = ProxySelector.getDefault().select(profileUri).stream().filter(p -> p.address() != null).findFirst().map(p -> new HttpHost(((InetSocketAddress) p.address()).getAddress())).orElse(null);
        // timeout; we cannot access KNIMEConstants here because that would acccess preferences
        int timeout = 2000;
        String to = System.getProperty("knime.url.timeout", Integer.toString(timeout));
        try {
            timeout = Integer.parseInt(to);
        } catch (NumberFormatException ex) {
            m_collectedLogs.add(() -> NodeLogger.getLogger(ProfileManager.class).warn("Illegal value for system property knime.url.timeout :" + to, ex));
        }
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeout).setProxy(proxy).setConnectionRequestTimeout(timeout).build();
        try (CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(requestConfig).setRedirectStrategy(new DefaultRedirectStrategy()).build()) {
            HttpGet get = new HttpGet(profileUri);
            if (Files.isDirectory(profileDir)) {
                Instant lastModified = Files.getLastModifiedTime(profileDir).toInstant();
                get.setHeader("If-Modified-Since", DateTimeFormatter.RFC_1123_DATE_TIME.format(lastModified.atZone(ZoneId.of("GMT"))));
            }
            try (CloseableHttpResponse response = client.execute(get)) {
                int code = response.getStatusLine().getStatusCode();
                if ((code >= 200) && (code < 300)) {
                    Header ct = response.getFirstHeader("Content-Type");
                    if ((ct == null) || (ct.getValue() == null) || !ct.getValue().startsWith("application/zip")) {
                        // no zip file - it just processes an empty zip
                        throw new IOException("Server did not return a ZIP file containing the selected profiles");
                    }
                    Path tempDir = PathUtils.createTempDir("profile-download", stateDir);
                    try (InputStream is = response.getEntity().getContent()) {
                        PathUtils.unzip(new ZipInputStream(is), tempDir);
                    }
                    // replace profiles only if new data has been downloaded successfully
                    PathUtils.deleteDirectoryIfExists(profileDir);
                    Files.move(tempDir, profileDir, StandardCopyOption.ATOMIC_MOVE);
                } else if (code != 304) {
                    // 304 = Not Modified
                    HttpEntity body = response.getEntity();
                    String msg;
                    if (body.getContentType().getValue().startsWith("text/")) {
                        byte[] buf = new byte[Math.min(4096, Math.max(4096, (int) body.getContentLength()))];
                        int read = body.getContent().read(buf);
                        msg = new String(buf, 0, read, "US-ASCII").trim();
                    } else if (!response.getStatusLine().getReasonPhrase().isEmpty()) {
                        msg = response.getStatusLine().getReasonPhrase();
                    } else {
                        msg = "Server returned status " + response.getStatusLine().getStatusCode();
                    }
                    throw new IOException(msg);
                }
            }
        }
    } catch (IOException | URISyntaxException ex) {
        String msg = "Could not download profiles from " + profileLocation + ": " + ex.getMessage() + ". " + (Files.isDirectory(profileDir) ? "Will use existing but potentially outdated profiles." : "No profiles will be applied.");
        m_collectedLogs.add(() -> NodeLogger.getLogger(ProfileManager.class).error(msg, ex));
    }
    return profileDir;
}
Also used : Path(java.nio.file.Path) Arrays(java.util.Arrays) ZipInputStream(java.util.zip.ZipInputStream) URISyntaxException(java.net.URISyntaxException) CoreException(org.eclipse.core.runtime.CoreException) RequestConfig(org.apache.http.client.config.RequestConfig) Supplier(java.util.function.Supplier) Header(org.apache.http.Header) StandardCopyOption(java.nio.file.StandardCopyOption) ArrayList(java.util.ArrayList) ProxySelector(java.net.ProxySelector) HashSet(java.util.HashSet) Charset(java.nio.charset.Charset) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) IExtensionRegistry(org.eclipse.core.runtime.IExtensionRegistry) NodeLogger(org.knime.core.node.NodeLogger) IConfigurationElement(org.eclipse.core.runtime.IConfigurationElement) PathUtils(org.knime.core.util.PathUtils) DefaultRedirectStrategy(org.apache.http.impl.client.DefaultRedirectStrategy) IExtensionPoint(org.eclipse.core.runtime.IExtensionPoint) URI(java.net.URI) Bundle(org.osgi.framework.Bundle) Path(java.nio.file.Path) OutputStream(java.io.OutputStream) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) Properties(java.util.Properties) Files(java.nio.file.Files) URIBuilder(org.apache.http.client.utils.URIBuilder) HttpEntity(org.apache.http.HttpEntity) IOException(java.io.IOException) Reader(java.io.Reader) Instant(java.time.Instant) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) ZoneId(java.time.ZoneId) List(java.util.List) Stream(java.util.stream.Stream) Paths(java.nio.file.Paths) HttpGet(org.apache.http.client.methods.HttpGet) DateTimeFormatter(java.time.format.DateTimeFormatter) DefaultPreferences(org.eclipse.core.internal.preferences.DefaultPreferences) Optional(java.util.Optional) Platform(org.eclipse.core.runtime.Platform) Collections(java.util.Collections) HttpHost(org.apache.http.HttpHost) FrameworkUtil(org.osgi.framework.FrameworkUtil) HttpClients(org.apache.http.impl.client.HttpClients) InputStream(java.io.InputStream) RequestConfig(org.apache.http.client.config.RequestConfig) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpEntity(org.apache.http.HttpEntity) ZipInputStream(java.util.zip.ZipInputStream) InputStream(java.io.InputStream) HttpGet(org.apache.http.client.methods.HttpGet) Instant(java.time.Instant) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) IExtensionPoint(org.eclipse.core.runtime.IExtensionPoint) URIBuilder(org.apache.http.client.utils.URIBuilder) ZipInputStream(java.util.zip.ZipInputStream) Header(org.apache.http.Header) HttpHost(org.apache.http.HttpHost) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) DefaultRedirectStrategy(org.apache.http.impl.client.DefaultRedirectStrategy)

Example 79 with HttpHost

use of org.graylog.shaded.elasticsearch7.org.apache.http.HttpHost in project janusgraph by JanusGraph.

the class ElasticSearchMultiTypeIndexTest method clear.

private void clear() throws Exception {
    try (final CloseableHttpClient httpClient = HttpClients.createDefault()) {
        final HttpHost host = new HttpHost(InetAddress.getByName(esr.getHostname()), ElasticsearchRunner.PORT);
        IOUtils.closeQuietly(httpClient.execute(host, new HttpDelete("janusgraph*")));
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpDelete(org.apache.http.client.methods.HttpDelete) HttpHost(org.apache.http.HttpHost)

Example 80 with HttpHost

use of org.graylog.shaded.elasticsearch7.org.apache.http.HttpHost in project jaeger-client-java by jaegertracing.

the class SpanCreationRequestInterceptor method process.

@Override
public void process(HttpRequest httpRequest, HttpContext httpContext) throws HttpException, IOException {
    try {
        Span currentActiveSpan = tracer.activeSpan();
        Tracer.SpanBuilder clientSpanBuilder = tracer.buildSpan(getOperationName(httpRequest));
        if (currentActiveSpan != null) {
            clientSpanBuilder.asChildOf(currentActiveSpan);
        }
        Span clientSpan = clientSpanBuilder.start();
        RequestLine requestLine = httpRequest.getRequestLine();
        Tags.SPAN_KIND.set(clientSpan, Tags.SPAN_KIND_CLIENT);
        Tags.HTTP_URL.set(clientSpan, requestLine.getUri());
        if (httpContext instanceof HttpClientContext) {
            HttpHost host = ((HttpClientContext) httpContext).getTargetHost();
            Tags.PEER_HOSTNAME.set(clientSpan, host.getHostName());
            Tags.PEER_PORT.set(clientSpan, host.getPort());
        }
        onSpanStarted(clientSpan, httpRequest, httpContext);
        httpContext.setAttribute(Constants.CURRENT_SPAN_CONTEXT_KEY, clientSpan);
    } catch (Exception e) {
        log.error("Could not start client tracing span.", e);
    }
}
Also used : RequestLine(org.apache.http.RequestLine) Tracer(io.opentracing.Tracer) HttpHost(org.apache.http.HttpHost) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) Span(io.opentracing.Span) HttpException(org.apache.http.HttpException) IOException(java.io.IOException)

Aggregations

HttpHost (org.apache.http.HttpHost)598 IOException (java.io.IOException)111 CredentialsProvider (org.apache.http.client.CredentialsProvider)105 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)102 HttpResponse (org.apache.http.HttpResponse)101 AuthScope (org.apache.http.auth.AuthScope)101 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)99 Test (org.junit.Test)86 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)84 URI (java.net.URI)68 HttpGet (org.apache.http.client.methods.HttpGet)66 HttpRequest (org.apache.http.HttpRequest)60 Header (org.apache.http.Header)56 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)56 HttpClientContext (org.apache.http.client.protocol.HttpClientContext)48 HttpEntity (org.apache.http.HttpEntity)47 RequestConfig (org.apache.http.client.config.RequestConfig)45 BasicScheme (org.apache.http.impl.auth.BasicScheme)45 URISyntaxException (java.net.URISyntaxException)44 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)43