use of io.helidon.common.http.Http in project helidon by oracle.
the class RestApiBase method handleBytesResponse.
/**
* Handle bytes response for optional bytes entity.
* This method checks if this was a success and if the response should contain an entity.
* For success, it returns a response using the provided response builder.
* For failures, returns an error.
*
* @param path requested path
* @param request API request
* @param method HTTP method
* @param requestId request ID
* @param response the web client response
* @param responseBuilder builder to configure success response
* @param <R> type of the optional part of the response
* @param <T> type of the response
*
* @return future with response
*/
protected <R, T extends ApiOptionalResponse<R>> Single<T> handleBytesResponse(String path, ApiRequest<?> request, Http.RequestMethod method, String requestId, WebClientResponse response, ApiOptionalResponse.BuilderBase<?, T, byte[], R> responseBuilder) {
Http.ResponseStatus status = response.status();
boolean success = (Http.Status.Family.of(status.code()) == Http.ResponseStatus.Family.SUCCESSFUL) || isSuccess(path, request, method, requestId, status);
boolean isEntityExpected = (Http.Status.Family.of(status.code()) == Http.ResponseStatus.Family.SUCCESSFUL) || isEntityExpected(path, request, method, requestId, status);
if (success) {
if (isEntityExpected) {
return response.content().map(DataChunk::bytes).collect(new Collector<byte[], byte[]>() {
private final ByteArrayOutputStream baos = new ByteArrayOutputStream();
@Override
public void collect(byte[] item) {
baos.writeBytes(item);
}
@Override
public byte[] value() {
return baos.toByteArray();
}
}).map(it -> responseBuilder.headers(response.headers()).status(status).requestId(requestId).entity(it).build());
} else {
return emptyResponse(path, request, method, requestId, response, responseBuilder);
}
} else {
return errorResponse(path, request, method, requestId, response);
}
}
use of io.helidon.common.http.Http in project helidon by oracle.
the class RestApiBase method errorResponse.
/**
* Create an error response.
* This method attempts to read the response entity as a string, parse it into a JsonObject and
* depending on result, calls methods to create a proper exception.
*
* @param path requested path
* @param request original request
* @param method HTTP method
* @param requestId ID of the request
* @param response actual response where we do not expect an entity
* @param <T> type of the response
*
* @return future with error
*/
protected <T extends ApiResponse> Single<T> errorResponse(String path, ApiRequest<?> request, Http.RequestMethod method, String requestId, WebClientResponse response) {
if (response.headers().contentLength().orElse(-1L) == 0) {
// explicitly no content
return Single.error(readError(path, request, method, requestId, response));
} else {
AtomicBoolean processedError = new AtomicBoolean();
return response.content().as(String.class).flatMapSingle(string -> {
try {
JsonObject json = jsonReaderFactory.createReader(new StringReader(string)).readObject();
Single<T> error = Single.error(readError(path, request, method, requestId, response, json));
processedError.set(true);
return error;
} catch (Exception e) {
Single<T> error = Single.error(readError(path, request, method, requestId, response, string));
processedError.set(true);
return error;
}
}).onErrorResumeWithSingle(it -> {
if (processedError.get()) {
return Single.error(it);
}
return Single.error(readErrorFailedEntity(path, request, method, requestId, response, it));
});
}
}
use of io.helidon.common.http.Http in project helidon by oracle.
the class WebSecurityBuilderGateDefaultsTest method initClass.
@BeforeAll
public static void initClass() throws InterruptedException {
WebSecurityTestUtil.auditLogFinest();
myAuditProvider = new UnitTestAuditProvider();
Config config = Config.create();
Security security = Security.builder(config.get("security")).addAuditProvider(myAuditProvider).build();
Routing routing = Routing.builder().register(WebSecurity.create(security).securityDefaults(WebSecurity.rolesAllowed("admin").audit())).get("/noRoles", WebSecurity.enforce()).get("/user[/{*}]", WebSecurity.rolesAllowed("user")).get("/admin", WebSecurity.rolesAllowed("admin")).get("/deny", WebSecurity.rolesAllowed("deny")).get("/auditOnly", WebSecurity.enforce().skipAuthentication().skipAuthorization().auditEventType("unit_test").auditMessageFormat(WebSecurityTests.AUDIT_MESSAGE_FORMAT)).get("/{*}", (req, res) -> {
Optional<SecurityContext> securityContext = req.context().get(SecurityContext.class);
res.headers().contentType(MediaType.TEXT_PLAIN.withCharset("UTF-8"));
res.send("Hello, you are: \n" + securityContext.map(ctx -> ctx.user().orElse(SecurityContext.ANONYMOUS).toString()).orElse("Security context is null"));
}).build();
server = WebServer.create(routing);
long t = System.currentTimeMillis();
CountDownLatch cdl = new CountDownLatch(1);
server.start().thenAccept(webServer -> {
long time = System.currentTimeMillis() - t;
System.out.println("Started server on localhost:" + webServer.port() + " in " + time + " millis");
cdl.countDown();
});
// we must wait for server to start, so other tests are not triggered until it is ready!
assertThat("Timeout while waiting for server to start!", cdl.await(5, TimeUnit.SECONDS), is(true));
serverBaseUri = "http://localhost:" + server.port();
}
use of io.helidon.common.http.Http in project helidon by oracle.
the class WebSecurityProgrammaticTest method initClass.
@BeforeAll
public static void initClass() throws InterruptedException {
WebSecurityTestUtil.auditLogFinest();
myAuditProvider = new UnitTestAuditProvider();
Config config = Config.create();
Security security = Security.builder(config.get("security")).addAuditProvider(myAuditProvider).build();
Routing routing = Routing.builder().register(WebSecurity.create(security).securityDefaults(SecurityHandler.create().queryParam("jwt", TokenHandler.builder().tokenHeader("BEARER_TOKEN").tokenPattern(Pattern.compile("bearer (.*)")).build()).queryParam("name", TokenHandler.builder().tokenHeader("NAME_FROM_REQUEST").build()))).get("/noRoles", WebSecurity.secure()).get("/user[/{*}]", WebSecurity.rolesAllowed("user")).get("/admin", WebSecurity.rolesAllowed("admin")).get("/deny", WebSecurity.rolesAllowed("deny"), (req, res) -> {
res.status(Http.Status.INTERNAL_SERVER_ERROR_500);
res.send("Should not get here, this role doesn't exist");
}).get("/auditOnly", WebSecurity.audit().auditEventType("unit_test").auditMessageFormat(AUDIT_MESSAGE_FORMAT)).get("/{*}", (req, res) -> {
Optional<SecurityContext> securityContext = req.context().get(SecurityContext.class);
res.headers().contentType(MediaType.TEXT_PLAIN.withCharset("UTF-8"));
res.send("Hello, you are: \n" + securityContext.map(ctx -> ctx.user().orElse(SecurityContext.ANONYMOUS).toString()).orElse("Security context is null"));
}).build();
server = WebServer.create(routing);
long t = System.currentTimeMillis();
CountDownLatch cdl = new CountDownLatch(1);
server.start().thenAccept(webServer -> {
long time = System.currentTimeMillis() - t;
System.out.println("Started server on localhost:" + webServer.port() + " in " + time + " millis");
cdl.countDown();
});
// we must wait for server to start, so other tests are not triggered until it is ready!
assertThat("Timeout while waiting for server to start!", cdl.await(5, TimeUnit.SECONDS), is(true));
baseUri = "http://localhost:" + server.port();
}
use of io.helidon.common.http.Http in project helidon by oracle.
the class GreetService method basicAuthOutbound.
private void basicAuthOutbound(ServerRequest serverRequest, ServerResponse response) {
WebClient webClient = WebClient.builder().baseUri("http://localhost:" + Main.serverPort + "/greet/secure/basic").addService(WebClientSecurity.create()).build();
webClient.get().request().thenAccept(clientResponse -> {
response.status(clientResponse.status());
response.send(clientResponse.content());
}).exceptionally(throwable -> {
response.status(Http.Status.INTERNAL_SERVER_ERROR_500);
response.send();
return null;
});
}
Aggregations