Search in sources :

Example 21 with URIAuthority

use of org.apache.hc.core5.net.URIAuthority in project httpcomponents-core by apache.

the class RequestTargetHost method process.

@Override
public void process(final HttpRequest request, final EntityDetails entity, final HttpContext context) throws HttpException, IOException {
    Args.notNull(request, "HTTP request");
    Args.notNull(context, "HTTP context");
    final ProtocolVersion ver = context.getProtocolVersion();
    final String method = request.getMethod();
    if (Method.CONNECT.isSame(method) && ver.lessEquals(HttpVersion.HTTP_1_0)) {
        return;
    }
    if (!request.containsHeader(HttpHeaders.HOST)) {
        URIAuthority authority = request.getAuthority();
        if (authority == null) {
            if (ver.lessEquals(HttpVersion.HTTP_1_0)) {
                return;
            }
            throw new ProtocolException("Target host is unknown");
        }
        if (authority.getUserInfo() != null) {
            authority = new URIAuthority(authority.getHostName(), authority.getPort());
        }
        request.addHeader(HttpHeaders.HOST, authority);
    }
}
Also used : ProtocolException(org.apache.hc.core5.http.ProtocolException) URIAuthority(org.apache.hc.core5.net.URIAuthority) ProtocolVersion(org.apache.hc.core5.http.ProtocolVersion)

Example 22 with URIAuthority

use of org.apache.hc.core5.net.URIAuthority in project httpcomponents-core by apache.

the class ClassicServerFilterExample method main.

public static void main(final String[] args) throws Exception {
    int port = 8080;
    if (args.length >= 1) {
        port = Integer.parseInt(args[0]);
    }
    final SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(15, TimeUnit.SECONDS).setTcpNoDelay(true).build();
    final HttpServer server = ServerBootstrap.bootstrap().setListenerPort(port).setSocketConfig(socketConfig).replaceFilter(StandardFilter.EXPECT_CONTINUE.name(), new AbstractHttpServerAuthFilter<String>(false) {

        @Override
        protected String parseChallengeResponse(final String authorizationValue, final HttpContext context) throws HttpException {
            return authorizationValue;
        }

        @Override
        protected boolean authenticate(final String challengeResponse, final URIAuthority authority, final String requestUri, final HttpContext context) {
            return "let me pass".equals(challengeResponse);
        }

        @Override
        protected String generateChallenge(final String challengeResponse, final URIAuthority authority, final String requestUri, final HttpContext context) {
            return "who goes there?";
        }
    }).addFilterFirst("my-filter", (request, responseTrigger, context, chain) -> {
        if (request.getRequestUri().equals("/back-door")) {
            final ClassicHttpResponse response = new BasicClassicHttpResponse(HttpStatus.SC_OK);
            response.setEntity(new StringEntity("Welcome", ContentType.TEXT_PLAIN));
            responseTrigger.submitResponse(response);
        } else {
            chain.proceed(request, new HttpFilterChain.ResponseTrigger() {

                @Override
                public void sendInformation(final ClassicHttpResponse response) throws HttpException, IOException {
                    responseTrigger.sendInformation(response);
                }

                @Override
                public void submitResponse(final ClassicHttpResponse response) throws HttpException, IOException {
                    response.addHeader("X-Filter", "My-Filter");
                    responseTrigger.submitResponse(response);
                }
            }, context);
        }
    }).register("*", (request, response, context) -> {
        // do something useful
        response.setCode(HttpStatus.SC_OK);
        response.setEntity(new StringEntity("Hello"));
    }).create();
    server.start();
    Runtime.getRuntime().addShutdownHook(new Thread(() -> server.close(CloseMode.GRACEFUL)));
    System.out.println("Listening on port " + port);
    server.awaitTermination(TimeValue.MAX_VALUE);
}
Also used : BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) HttpException(org.apache.hc.core5.http.HttpException) TimeValue(org.apache.hc.core5.util.TimeValue) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) IOException(java.io.IOException) SocketConfig(org.apache.hc.core5.http.io.SocketConfig) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse) TimeUnit(java.util.concurrent.TimeUnit) HttpServer(org.apache.hc.core5.http.impl.bootstrap.HttpServer) AbstractHttpServerAuthFilter(org.apache.hc.core5.http.io.support.AbstractHttpServerAuthFilter) URIAuthority(org.apache.hc.core5.net.URIAuthority) ServerBootstrap(org.apache.hc.core5.http.impl.bootstrap.ServerBootstrap) ContentType(org.apache.hc.core5.http.ContentType) ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) HttpFilterChain(org.apache.hc.core5.http.io.HttpFilterChain) CloseMode(org.apache.hc.core5.io.CloseMode) StringEntity(org.apache.hc.core5.http.io.entity.StringEntity) HttpStatus(org.apache.hc.core5.http.HttpStatus) StandardFilter(org.apache.hc.core5.http.impl.bootstrap.StandardFilter) URIAuthority(org.apache.hc.core5.net.URIAuthority) SocketConfig(org.apache.hc.core5.http.io.SocketConfig) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) IOException(java.io.IOException) AbstractHttpServerAuthFilter(org.apache.hc.core5.http.io.support.AbstractHttpServerAuthFilter) StringEntity(org.apache.hc.core5.http.io.entity.StringEntity) HttpServer(org.apache.hc.core5.http.impl.bootstrap.HttpServer) HttpException(org.apache.hc.core5.http.HttpException) HttpFilterChain(org.apache.hc.core5.http.io.HttpFilterChain) BasicClassicHttpResponse(org.apache.hc.core5.http.message.BasicClassicHttpResponse)

Example 23 with URIAuthority

use of org.apache.hc.core5.net.URIAuthority in project httpcomponents-core by apache.

the class BasicHttpRequest method setUri.

@Override
public void setUri(final URI requestUri) {
    this.scheme = requestUri.getScheme();
    if (requestUri.getHost() != null) {
        this.authority = new URIAuthority(requestUri.getRawUserInfo(), requestUri.getHost(), requestUri.getPort());
    } else if (requestUri.getRawAuthority() != null) {
        try {
            this.authority = URIAuthority.create(requestUri.getRawAuthority());
        } catch (final URISyntaxException ignore) {
            this.authority = null;
        }
    } else {
        this.authority = null;
    }
    final StringBuilder buf = new StringBuilder();
    final String rawPath = requestUri.getRawPath();
    if (!TextUtils.isBlank(rawPath)) {
        Args.check(!rawPath.startsWith("//"), "URI path begins with multiple slashes");
        buf.append(rawPath);
    } else {
        buf.append("/");
    }
    final String query = requestUri.getRawQuery();
    if (query != null) {
        buf.append('?').append(query);
    }
    this.path = buf.toString();
}
Also used : URIAuthority(org.apache.hc.core5.net.URIAuthority) URISyntaxException(java.net.URISyntaxException)

Example 24 with URIAuthority

use of org.apache.hc.core5.net.URIAuthority in project opentelemetry-java-instrumentation by open-telemetry.

the class ApacheHttpClientHttpAttributesGetter method url.

@Override
public String url(ClassicHttpRequest request) {
    // similar to org.apache.hc.core5.http.message.BasicHttpRequest.getUri()
    // not calling getUri() to avoid unnecessary conversion
    StringBuilder url = new StringBuilder();
    URIAuthority authority = request.getAuthority();
    if (authority != null) {
        String scheme = request.getScheme();
        if (scheme != null) {
            url.append(scheme);
            url.append("://");
        } else {
            url.append("http://");
        }
        url.append(authority.getHostName());
        int port = authority.getPort();
        if (port >= 0) {
            url.append(":");
            url.append(port);
        }
    }
    String path = request.getPath();
    if (path != null) {
        if (url.length() > 0 && !path.startsWith("/")) {
            url.append("/");
        }
        url.append(path);
    } else {
        url.append("/");
    }
    return url.toString();
}
Also used : URIAuthority(org.apache.hc.core5.net.URIAuthority)

Example 25 with URIAuthority

use of org.apache.hc.core5.net.URIAuthority in project httpcomponents-client by apache.

the class TestClientAuthentication method testReauthentication.

@Test
public void testReauthentication() throws Exception {
    this.server.registerHandler("*", new EchoHandler());
    final BasicSchemeFactory myBasicAuthSchemeFactory = new BasicSchemeFactory() {

        @Override
        public AuthScheme create(final HttpContext context) {
            return new BasicScheme() {

                private static final long serialVersionUID = 1L;

                @Override
                public String getName() {
                    return "MyBasic";
                }
            };
        }
    };
    final CredentialsProvider credsProvider = Mockito.mock(CredentialsProvider.class);
    Mockito.when(credsProvider.getCredentials(Mockito.any(), Mockito.any())).thenReturn(new UsernamePasswordCredentials("test", "test".toCharArray()));
    final RequestConfig config = RequestConfig.custom().setTargetPreferredAuthSchemes(Collections.singletonList("MyBasic")).build();
    final Registry<AuthSchemeFactory> authSchemeRegistry = RegistryBuilder.<AuthSchemeFactory>create().register("MyBasic", myBasicAuthSchemeFactory).build();
    this.httpclient = this.clientBuilder.setDefaultAuthSchemeRegistry(authSchemeRegistry).setDefaultCredentialsProvider(credsProvider).build();
    final Authenticator authenticator = new BasicTestAuthenticator("test:test", "test realm") {

        private final AtomicLong count = new AtomicLong(0);

        @Override
        public boolean authenticate(final URIAuthority authority, final String requestUri, final String credentials) {
            final boolean authenticated = super.authenticate(authority, requestUri, credentials);
            if (authenticated) {
                return this.count.incrementAndGet() % 4 != 0;
            }
            return false;
        }
    };
    final HttpHost target = start(HttpProcessors.server(), requestHandler -> new AuthenticatingDecorator(requestHandler, authenticator) {

        @Override
        protected void customizeUnauthorizedResponse(final ClassicHttpResponse unauthorized) {
            unauthorized.removeHeaders(HttpHeaders.WWW_AUTHENTICATE);
            unauthorized.addHeader(HttpHeaders.WWW_AUTHENTICATE, "MyBasic realm=\"test realm\"");
        }
    });
    final HttpClientContext context = HttpClientContext.create();
    for (int i = 0; i < 10; i++) {
        final HttpGet httpget = new HttpGet("/");
        httpget.setConfig(config);
        this.httpclient.execute(target, httpget, context, response -> {
            final HttpEntity entity = response.getEntity();
            Assertions.assertEquals(HttpStatus.SC_OK, response.getCode());
            Assertions.assertNotNull(entity);
            EntityUtils.consume(entity);
            return null;
        });
    }
}
Also used : ClassicHttpResponse(org.apache.hc.core5.http.ClassicHttpResponse) BasicScheme(org.apache.hc.client5.http.impl.auth.BasicScheme) RequestConfig(org.apache.hc.client5.http.config.RequestConfig) AuthSchemeFactory(org.apache.hc.client5.http.auth.AuthSchemeFactory) URIAuthority(org.apache.hc.core5.net.URIAuthority) HttpEntity(org.apache.hc.core5.http.HttpEntity) BasicTestAuthenticator(org.apache.hc.client5.testing.BasicTestAuthenticator) BasicSchemeFactory(org.apache.hc.client5.http.impl.auth.BasicSchemeFactory) HttpGet(org.apache.hc.client5.http.classic.methods.HttpGet) HttpContext(org.apache.hc.core5.http.protocol.HttpContext) HttpClientContext(org.apache.hc.client5.http.protocol.HttpClientContext) CredentialsProvider(org.apache.hc.client5.http.auth.CredentialsProvider) UsernamePasswordCredentials(org.apache.hc.client5.http.auth.UsernamePasswordCredentials) AtomicLong(java.util.concurrent.atomic.AtomicLong) HttpHost(org.apache.hc.core5.http.HttpHost) EchoHandler(org.apache.hc.client5.testing.classic.EchoHandler) AuthenticatingDecorator(org.apache.hc.client5.testing.classic.AuthenticatingDecorator) Authenticator(org.apache.hc.client5.testing.auth.Authenticator) BasicTestAuthenticator(org.apache.hc.client5.testing.BasicTestAuthenticator) Test(org.junit.Test)

Aggregations

URIAuthority (org.apache.hc.core5.net.URIAuthority)63 Test (org.junit.jupiter.api.Test)32 HttpRequest (org.apache.hc.core5.http.HttpRequest)21 HttpHost (org.apache.hc.core5.http.HttpHost)17 Header (org.apache.hc.core5.http.Header)15 URI (java.net.URI)14 BasicHeader (org.apache.hc.core5.http.message.BasicHeader)11 HttpClientContext (org.apache.hc.client5.http.protocol.HttpClientContext)10 HttpException (org.apache.hc.core5.http.HttpException)9 IOException (java.io.IOException)8 ClassicHttpResponse (org.apache.hc.core5.http.ClassicHttpResponse)8 ProtocolException (org.apache.hc.core5.http.ProtocolException)8 HttpResponse (org.apache.hc.core5.http.HttpResponse)7 BasicClassicHttpResponse (org.apache.hc.core5.http.message.BasicClassicHttpResponse)7 HttpEntity (org.apache.hc.core5.http.HttpEntity)6 BasicHttpRequest (org.apache.hc.core5.http.message.BasicHttpRequest)6 HttpContext (org.apache.hc.core5.http.protocol.HttpContext)6 HttpRoute (org.apache.hc.client5.http.HttpRoute)5 SimpleHttpResponse (org.apache.hc.client5.http.async.methods.SimpleHttpResponse)5 BasicClassicHttpRequest (org.apache.hc.core5.http.message.BasicClassicHttpRequest)5