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);
}
}
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);
}
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();
}
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();
}
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;
});
}
}
Aggregations