Search in sources :

Example 1 with HttpException

use of io.helidon.webserver.HttpException in project helidon by oracle.

the class Main method errorHandling.

/**
 * Request processing can cause error represented by {@link Throwable}. It is possible to register custom
 * {@link io.helidon.webserver.ErrorHandler ErrorHandlers} for specific processing.
 * <p>
 * If error is not processed by a custom {@link io.helidon.webserver.ErrorHandler ErrorHandler} than default one is used.
 * It respond with <i>HTTP 500 code</i> unless error is not represented
 * by {@link HttpException HttpException}. In such case it reflects its content.
 */
public void errorHandling() {
    Routing routing = Routing.builder().post("/compute", Handler.create(String.class, (req, res, str) -> {
        int result = 100 / Integer.parseInt(str);
        res.send(String.valueOf("100 / " + str + " = " + result));
    })).error(Throwable.class, (req, res, ex) -> {
        ex.printStackTrace(System.out);
        req.next();
    }).error(NumberFormatException.class, (req, res, ex) -> res.status(Http.Status.BAD_REQUEST_400).send()).error(ArithmeticException.class, (req, res, ex) -> res.status(Http.Status.PRECONDITION_FAILED_412).send()).build();
    startServer(routing);
}
Also used : JerseySupport(io.helidon.webserver.jersey.JerseySupport) DataChunk(io.helidon.common.http.DataChunk) RequestPredicate(io.helidon.webserver.RequestPredicate) JsonBuilderFactory(jakarta.json.JsonBuilderFactory) MediaContext(io.helidon.media.common.MediaContext) MessageBodyReader(io.helidon.media.common.MessageBodyReader) InvocationTargetException(java.lang.reflect.InvocationTargetException) MediaType(io.helidon.common.http.MediaType) Json(jakarta.json.Json) JsonpSupport(io.helidon.media.jsonp.JsonpSupport) Handler(io.helidon.webserver.Handler) StaticContentSupport(io.helidon.webserver.staticcontent.StaticContentSupport) Modifier(java.lang.reflect.Modifier) Parameters(io.helidon.common.http.Parameters) HttpException(io.helidon.webserver.HttpException) WebServer(io.helidon.webserver.WebServer) Http(io.helidon.common.http.Http) Routing(io.helidon.webserver.Routing) Method(java.lang.reflect.Method) Collections(java.util.Collections) Routing(io.helidon.webserver.Routing)

Example 2 with HttpException

use of io.helidon.webserver.HttpException in project helidon by oracle.

the class FileBasedContentHandler method sendFile.

void sendFile(Http.RequestMethod method, Path pathParam, ServerRequest request, ServerResponse response, String welcomePage) throws IOException {
    LOGGER.fine(() -> "Sending static content from file: " + pathParam);
    Path path = pathParam;
    // First doHandle a directory case
    if (Files.isDirectory(path)) {
        String rawFullPath = request.uri().getRawPath();
        if (rawFullPath.endsWith("/")) {
            // Try to found welcome file
            path = resolveWelcomeFile(path, welcomePage);
        } else {
            // Or redirect to slash ended
            redirect(request, response, rawFullPath + "/");
            return;
        }
    }
    // now it exists and is a file
    if (!Files.isRegularFile(path) || !Files.isReadable(path) || Files.isHidden(path)) {
        throw new HttpException("File is not accessible", Http.Status.FORBIDDEN_403);
    }
    // Caching headers support
    try {
        Instant lastMod = Files.getLastModifiedTime(path).toInstant();
        processEtag(String.valueOf(lastMod.toEpochMilli()), request.headers(), response.headers());
        processModifyHeaders(lastMod, request.headers(), response.headers());
    } catch (IOException | SecurityException e) {
    // Cannot get mod time or size - well, we cannot tell if it was modified or not. Don't support cache headers
    }
    processContentType(fileName(path), request.headers(), response.headers());
    if (method == Http.Method.HEAD) {
        response.send();
    } else {
        send(response, path);
    }
}
Also used : Path(java.nio.file.Path) Instant(java.time.Instant) HttpException(io.helidon.webserver.HttpException) IOException(java.io.IOException)

Example 3 with HttpException

use of io.helidon.webserver.HttpException in project helidon by oracle.

the class FileBasedContentHandler method detectType.

private MediaType detectType(String fileName, RequestHeaders requestHeaders) {
    Objects.requireNonNull(fileName);
    Objects.requireNonNull(requestHeaders);
    // then check the type is accepted by the request
    return findCustomMediaType(fileName).or(() -> MediaTypes.detectType(fileName).map(MediaType::parse)).map(it -> {
        if (requestHeaders.isAccepted(it)) {
            return it;
        }
        throw new HttpException("Media type " + it + " is not accepted by request", Http.Status.UNSUPPORTED_MEDIA_TYPE_415);
    }).orElseGet(() -> {
        List<MediaType> acceptedTypes = requestHeaders.acceptedTypes();
        if (acceptedTypes.isEmpty()) {
            return MediaType.APPLICATION_OCTET_STREAM;
        } else {
            return acceptedTypes.iterator().next();
        }
    });
}
Also used : MessageBodyWriter(io.helidon.media.common.MessageBodyWriter) DefaultMediaSupport(io.helidon.media.common.DefaultMediaSupport) Files(java.nio.file.Files) MediaTypes(io.helidon.common.media.type.MediaTypes) IOException(java.io.IOException) Instant(java.time.Instant) Logger(java.util.logging.Logger) RequestHeaders(io.helidon.webserver.RequestHeaders) MediaType(io.helidon.common.http.MediaType) ServerRequest(io.helidon.webserver.ServerRequest) Objects(java.util.Objects) List(java.util.List) ResponseHeaders(io.helidon.webserver.ResponseHeaders) Map(java.util.Map) HttpException(io.helidon.webserver.HttpException) ServerResponse(io.helidon.webserver.ServerResponse) Optional(java.util.Optional) Http(io.helidon.common.http.Http) Path(java.nio.file.Path) MediaType(io.helidon.common.http.MediaType) HttpException(io.helidon.webserver.HttpException)

Example 4 with HttpException

use of io.helidon.webserver.HttpException in project helidon by oracle.

the class TestClientTest method advancingToDefaultErrorHandler.

@Test
public void advancingToDefaultErrorHandler() throws Exception {
    StringBuffer sb = new StringBuffer();
    HttpException exception = new HttpException("test-exception", Http.ResponseStatus.create(777));
    Routing routing = Routing.builder().any((req, res) -> {
        sb.append("any-");
        req.next(exception);
    }).error(IllegalStateException.class, (req, res, ex) -> {
        fail("Should not be called");
    }).error(Exception.class, (req, res, ex) -> {
        sb.append("exceptionHandler-");
        req.next(ex);
    }).error(IllegalArgumentException.class, (req, res, ex) -> {
        fail("Should not be called");
    }).error(HttpException.class, (req, res, ex) -> {
        sb.append("httpExceptionHandler-");
        req.next();
    }).error(Throwable.class, (req, res, ex) -> {
        sb.append("throwableHandler");
        req.next();
    }).build();
    TestResponse response = TestClient.create(routing).path("/anything/anywhere").get();
    assertThat(sb.toString(), is("any-exceptionHandler-httpExceptionHandler-throwableHandler"));
    assertThat(response.status().code(), is(777));
}
Also used : TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) CoreMatchers.is(org.hamcrest.CoreMatchers.is) Assertions.fail(org.junit.jupiter.api.Assertions.fail) CountDownLatch(java.util.concurrent.CountDownLatch) NotFoundException(io.helidon.webserver.NotFoundException) HttpException(io.helidon.webserver.HttpException) SERVICE_UNAVAILABLE_503(io.helidon.common.http.Http.Status.SERVICE_UNAVAILABLE_503) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Http(io.helidon.common.http.Http) Routing(io.helidon.webserver.Routing) Routing(io.helidon.webserver.Routing) HttpException(io.helidon.webserver.HttpException) Test(org.junit.jupiter.api.Test)

Example 5 with HttpException

use of io.helidon.webserver.HttpException in project helidon by oracle.

the class StaticContentHandler method handle.

/**
 * Do handle for GET and HEAD HTTP methods. It is filtering implementation, prefers {@code response.next()} before NOT_FOUND.
 *
 * @param method   an HTTP method
 * @param request  an HTTP request
 * @param response an HTTP response
 */
void handle(Http.RequestMethod method, ServerRequest request, ServerResponse response) {
    // Check method
    if ((method != Http.Method.GET) && (method != Http.Method.HEAD)) {
        request.next();
        return;
    }
    // Resolve path
    String requestPath = request.path().toString();
    if (requestPath.startsWith("/")) {
        requestPath = requestPath.substring(1);
    }
    requestPath = resolvePathFunction.apply(requestPath);
    // Call doHandle
    try {
        if (!doHandle(method, requestPath, request, response)) {
            request.next();
        }
    } catch (HttpException httpException) {
        if (httpException.status().code() == Http.Status.NOT_FOUND_404.code()) {
            // Prefer to next() before NOT_FOUND
            request.next();
        } else {
            throw httpException;
        }
    } catch (Exception e) {
        LOGGER.log(Level.FINE, "Failed to access static resource", e);
        throw new HttpException("Cannot access static resource!", Http.Status.INTERNAL_SERVER_ERROR_500, e);
    }
}
Also used : HttpException(io.helidon.webserver.HttpException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) HttpException(io.helidon.webserver.HttpException)

Aggregations

HttpException (io.helidon.webserver.HttpException)9 Http (io.helidon.common.http.Http)6 NotFoundException (io.helidon.webserver.NotFoundException)4 Routing (io.helidon.webserver.Routing)4 IOException (java.io.IOException)4 SERVICE_UNAVAILABLE_503 (io.helidon.common.http.Http.Status.SERVICE_UNAVAILABLE_503)3 Path (java.nio.file.Path)3 Instant (java.time.Instant)3 CountDownLatch (java.util.concurrent.CountDownLatch)3 TimeUnit (java.util.concurrent.TimeUnit)3 Test (org.junit.jupiter.api.Test)3 MediaType (io.helidon.common.http.MediaType)2 CoreMatchers.is (org.hamcrest.CoreMatchers.is)2 MatcherAssert.assertThat (org.hamcrest.MatcherAssert.assertThat)2 Assertions.fail (org.junit.jupiter.api.Assertions.fail)2 DataChunk (io.helidon.common.http.DataChunk)1 Parameters (io.helidon.common.http.Parameters)1 MediaTypes (io.helidon.common.media.type.MediaTypes)1 DefaultMediaSupport (io.helidon.media.common.DefaultMediaSupport)1 MediaContext (io.helidon.media.common.MediaContext)1