Search in sources :

Example 1 with ResourceInfo

use of jakarta.ws.rs.container.ResourceInfo in project org.openntf.xsp.jakartaee by OpenNTF.

the class GenericThrowableMapper method createResponseFromException.

protected Response createResponseFromException(final Throwable throwable, final int status, ResourceInfo resourceInfo, HttpServletRequest req) {
    MediaType type = getMediaType(resourceInfo);
    if (MediaType.TEXT_HTML_TYPE.isCompatible(type)) {
        // Handle as HTML
        return Response.status(status).type(MediaType.TEXT_HTML_TYPE).entity((StreamingOutput) out -> {
            try (PrintWriter w = new PrintWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8))) {
                XSPErrorPage.handleException(w, throwable, req.getRequestURL().toString(), false);
            } catch (ServletException e) {
                throw new IOException(e);
            }
        }).build();
    } else {
        // Handle as JSON
        return Response.status(status).type(MediaType.APPLICATION_JSON_TYPE).entity((StreamingOutput) out -> {
            Objects.requireNonNull(out);
            String message = "";
            Throwable t = throwable;
            while ((message == null || message.length() == 0) && t != null) {
                if (t instanceof NotesException) {
                    message = ((NotesException) t).text;
                } else if (t instanceof ConstraintViolationException) {
                    message = t.getMessage();
                    if (message == null || message.isEmpty()) {
                        List<String> cvMsgList = new ArrayList<>();
                        for (@SuppressWarnings("rawtypes") ConstraintViolation cv : ((ConstraintViolationException) t).getConstraintViolations()) {
                            String cvMsg = cv.getPropertyPath() + ": " + cv.getMessage();
                            cvMsgList.add(cvMsg);
                        }
                        message = String.join(",", cvMsgList);
                    }
                } else {
                    message = t.getMessage();
                }
                t = t.getCause();
            }
            JsonGeneratorFactory jsonFac = Json.createGeneratorFactory(Collections.singletonMap(JsonGenerator.PRETTY_PRINTING, true));
            try (JsonGenerator json = jsonFac.createGenerator(out)) {
                json.writeStartObject();
                json.write("message", throwable.getClass().getName() + ": " + message);
                json.writeKey("stackTrace");
                json.writeStartArray();
                for (Throwable cause = throwable; cause != null; cause = cause.getCause()) {
                    json.writeStartArray();
                    json.write(cause.getClass().getName() + ": " + cause.getLocalizedMessage());
                    Arrays.stream(cause.getStackTrace()).map(String::valueOf).map(line -> "  at " + line).forEach(json::write);
                    json.writeEnd();
                }
                json.writeEnd();
                json.writeEnd();
            }
        }).build();
    }
}
Also used : Arrays(java.util.Arrays) XSPErrorPage(com.ibm.designer.runtime.domino.adapter.util.XSPErrorPage) Context(jakarta.ws.rs.core.Context) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) JsonGeneratorFactory(jakarta.json.stream.JsonGeneratorFactory) WebApplicationException(jakarta.ws.rs.WebApplicationException) ArrayList(java.util.ArrayList) Response(jakarta.ws.rs.core.Response) Controller(jakarta.mvc.Controller) OutputStreamWriter(java.io.OutputStreamWriter) Priority(jakarta.annotation.Priority) Produces(jakarta.ws.rs.Produces) Request(jakarta.ws.rs.core.Request) Method(java.lang.reflect.Method) StreamingOutput(jakarta.ws.rs.core.StreamingOutput) NotesException(lotus.domino.NotesException) PrintWriter(java.io.PrintWriter) ConstraintViolation(jakarta.validation.ConstraintViolation) NotFoundException(jakarta.ws.rs.NotFoundException) IOException(java.io.IOException) ConstraintViolationException(jakarta.validation.ConstraintViolationException) UriInfo(jakarta.ws.rs.core.UriInfo) JsonGenerator(jakarta.json.stream.JsonGenerator) StandardCharsets(java.nio.charset.StandardCharsets) Json(jakarta.json.Json) Priorities(jakarta.ws.rs.Priorities) Objects(java.util.Objects) List(java.util.List) MediaType(jakarta.ws.rs.core.MediaType) ExceptionMapper(jakarta.ws.rs.ext.ExceptionMapper) ResourceInfo(jakarta.ws.rs.container.ResourceInfo) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) Collections(java.util.Collections) StreamingOutput(jakarta.ws.rs.core.StreamingOutput) IOException(java.io.IOException) JsonGeneratorFactory(jakarta.json.stream.JsonGeneratorFactory) ServletException(javax.servlet.ServletException) NotesException(lotus.domino.NotesException) ConstraintViolation(jakarta.validation.ConstraintViolation) MediaType(jakarta.ws.rs.core.MediaType) ConstraintViolationException(jakarta.validation.ConstraintViolationException) JsonGenerator(jakarta.json.stream.JsonGenerator) OutputStreamWriter(java.io.OutputStreamWriter) ArrayList(java.util.ArrayList) List(java.util.List) PrintWriter(java.io.PrintWriter)

Example 2 with ResourceInfo

use of jakarta.ws.rs.container.ResourceInfo in project tomee by apache.

the class Contexts method bind.

/**
 * Using a set ensures we don't set the thread local twice or more,
 * there may be super classes with injection points of identical types
 *
 * Also allows us to get context references from other sources such as interceptors
 *
 * @param exchange Exchange
 * @param types    Collection
 */
public static void bind(final Exchange exchange, final Collection<Class<?>> types) {
    // used in lazy mode by RESTResourceFinder if cdi beans uses @Context, === initThreadLocal
    EXCHANGE.set(exchange);
    CdiAppContextsService.pushRequestReleasable(CleanUpThreadLocal.INSTANCE);
    for (final Class<?> type : types) {
        if (Request.class.equals(type)) {
            final Request binding = JAXRSUtils.createContextValue(exchange.getInMessage(), null, Request.class);
            ThreadLocalContextManager.REQUEST.set(binding);
        } else if (UriInfo.class.equals(type)) {
            final UriInfo binding = JAXRSUtils.createContextValue(exchange.getInMessage(), null, UriInfo.class);
            ThreadLocalContextManager.URI_INFO.set(binding);
        } else if (HttpHeaders.class.equals(type)) {
            final HttpHeaders binding = JAXRSUtils.createContextValue(exchange.getInMessage(), null, HttpHeaders.class);
            ThreadLocalContextManager.HTTP_HEADERS.set(binding);
        } else if (SecurityContext.class.equals(type)) {
            final SecurityContext binding = JAXRSUtils.createContextValue(exchange.getInMessage(), null, SecurityContext.class);
            ThreadLocalContextManager.SECURITY_CONTEXT.set(binding);
        } else if (ContextResolver.class.equals(type)) {
            final ContextResolver<?> binding = JAXRSUtils.createContextValue(exchange.getInMessage(), type, ContextResolver.class);
            ThreadLocalContextManager.CONTEXT_RESOLVER.set(binding);
        } else if (Providers.class.equals(type)) {
            final Providers providers = JAXRSUtils.createContextValue(exchange.getInMessage(), null, Providers.class);
            ThreadLocalContextManager.PROVIDERS.set(providers);
        } else if (ServletRequest.class.equals(type)) {
            ServletRequest servletRequest = JAXRSUtils.createContextValue(exchange.getInMessage(), null, ServletRequest.class);
            if (servletRequest == null) {
                // probably the case with CXF
                servletRequest = JAXRSUtils.createContextValue(exchange.getInMessage(), null, HttpServletRequest.class);
            }
            ThreadLocalContextManager.SERVLET_REQUEST.set(servletRequest);
        } else if (HttpServletRequest.class.equals(type)) {
            final HttpServletRequest httpServletRequest = JAXRSUtils.createContextValue(exchange.getInMessage(), null, HttpServletRequest.class);
            ThreadLocalContextManager.HTTP_SERVLET_REQUEST.set(httpServletRequest);
        } else if (HttpServletResponse.class.equals(type)) {
            final HttpServletResponse httpServletResponse = JAXRSUtils.createContextValue(exchange.getInMessage(), null, HttpServletResponse.class);
            ThreadLocalContextManager.HTTP_SERVLET_RESPONSE.set(httpServletResponse);
        } else if (ServletConfig.class.equals(type)) {
            final ServletConfig servletConfig = JAXRSUtils.createContextValue(exchange.getInMessage(), null, ServletConfig.class);
            ThreadLocalContextManager.SERVLET_CONFIG.set(servletConfig);
        } else if (Configuration.class.equals(type)) {
            final Configuration config = JAXRSUtils.createContextValue(exchange.getInMessage(), null, Configuration.class);
            ThreadLocalContextManager.CONFIGURATION.set(config);
        } else if (ResourceInfo.class.equals(type)) {
            final ResourceInfo config = JAXRSUtils.createContextValue(exchange.getInMessage(), null, ResourceInfo.class);
            ThreadLocalContextManager.RESOURCE_INFO.set(config);
        } else if (ResourceContext.class.equals(type)) {
            final ResourceContext config = JAXRSUtils.createContextValue(exchange.getInMessage(), null, ResourceContext.class);
            ThreadLocalContextManager.RESOURCE_CONTEXT.set(config);
        } else if (Application.class.equals(type)) {
            final Application config = JAXRSUtils.createContextValue(exchange.getInMessage(), null, Application.class);
            ThreadLocalContextManager.APPLICATION.set(config);
        } else {
            final Message message = exchange.getInMessage();
            final ContextProvider<?> provider = ProviderFactory.getInstance(message).createContextProvider(type, message);
            if (provider != null) {
                final Object value = provider.createContext(message);
                Map<String, Object> map = ThreadLocalContextManager.OTHERS.get();
                if (map == null) {
                    map = new HashMap<>();
                    ThreadLocalContextManager.OTHERS.set(map);
                }
                map.put(type.getName(), value);
            }
        }
    }
}
Also used : HttpHeaders(jakarta.ws.rs.core.HttpHeaders) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) ServletRequest(jakarta.servlet.ServletRequest) OperationResourceInfo(org.apache.cxf.jaxrs.model.OperationResourceInfo) ResourceInfo(jakarta.ws.rs.container.ResourceInfo) ClassResourceInfo(org.apache.cxf.jaxrs.model.ClassResourceInfo) ResourceContext(jakarta.ws.rs.container.ResourceContext) Configuration(jakarta.ws.rs.core.Configuration) Message(org.apache.cxf.message.Message) HashMap(java.util.HashMap) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) Request(jakarta.ws.rs.core.Request) ServletRequest(jakarta.servlet.ServletRequest) ServletConfig(jakarta.servlet.ServletConfig) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) ContextProvider(org.apache.cxf.jaxrs.ext.ContextProvider) Providers(jakarta.ws.rs.ext.Providers) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) SecurityContext(jakarta.ws.rs.core.SecurityContext) Application(jakarta.ws.rs.core.Application) HashMap(java.util.HashMap) Map(java.util.Map) UriInfo(jakarta.ws.rs.core.UriInfo)

Example 3 with ResourceInfo

use of jakarta.ws.rs.container.ResourceInfo in project resteasy by resteasy.

the class ProviderFactoryTest method testDeploymentStart.

@Test
public void testDeploymentStart() {
    ResteasyProviderFactory orig = ResteasyProviderFactory.peekInstance();
    try {
        ResteasyProviderFactory.setInstance(null);
        ResteasyProviderFactory rpf1 = ResteasyProviderFactory.newInstance();
        RegisterBuiltin.register(rpf1);
        rpf1.registerProvider(MyInterceptor.class);
        ResteasyDeployment dep1 = new ResteasyDeploymentImpl();
        dep1.setProviderFactory(rpf1);
        dep1.setDeploymentSensitiveFactoryEnabled(true);
        dep1.start();
        ResteasyProviderFactory rpf2 = ResteasyProviderFactory.newInstance();
        RegisterBuiltin.register(rpf2);
        rpf2.register(new DynamicFeature() {

            @Override
            public void configure(ResourceInfo resourceInfo, FeatureContext context) {
                if (ResteasyProviderFactory.getInstance().isRegistered(MyInterceptor.class)) {
                    Assert.fail("Second deployment consuming provider factory from first deployment");
                }
            }
        });
        ResteasyDeployment dep2 = new ResteasyDeploymentImpl();
        dep2.setProviderFactory(rpf2);
        dep2.setDeploymentSensitiveFactoryEnabled(true);
        dep2.start();
        dep1.stop();
        dep2.stop();
    } finally {
        ResteasyProviderFactory.setInstance(orig);
    }
}
Also used : ResteasyDeployment(org.jboss.resteasy.spi.ResteasyDeployment) ResourceInfo(jakarta.ws.rs.container.ResourceInfo) ResteasyDeploymentImpl(org.jboss.resteasy.core.ResteasyDeploymentImpl) ResteasyProviderFactory(org.jboss.resteasy.spi.ResteasyProviderFactory) DynamicFeature(jakarta.ws.rs.container.DynamicFeature) FeatureContext(jakarta.ws.rs.core.FeatureContext) Test(org.junit.Test)

Example 4 with ResourceInfo

use of jakarta.ws.rs.container.ResourceInfo in project helidon by oracle.

the class LraAnnotationHandler method handleJaxRsAfter.

@Override
public void handleJaxRsAfter(ContainerRequestContext reqCtx, ContainerResponseContext resCtx, ResourceInfo resourceInfo) {
    Optional<URI> lraId = Optional.ofNullable((URI) reqCtx.getProperty(LRA_HTTP_CONTEXT_HEADER)).or(() -> Contexts.context().flatMap(c -> c.get(LRA_HTTP_CONTEXT_HEADER, URI.class)));
    PropagatedHeaders propagatedHeaders = participantService.prepareCustomHeaderPropagation(reqCtx.getHeaders());
    Response.Status resStatus = resCtx.getStatusInfo().toEnum();
    Response.Status.Family resFamily = resCtx.getStatusInfo().getFamily();
    boolean end = annotation.end();
    boolean cancel = annotation.cancelOnFamily().contains(resFamily) || annotation.cancelOn().contains(resStatus);
    lraId.ifPresent(id -> {
        if (cancel) {
            cancel(id, propagatedHeaders);
        } else if (end) {
            close(id, propagatedHeaders);
        }
        resCtx.getHeaders().putSingle(LRA_HTTP_CONTEXT_HEADER, id);
    });
    Optional.ofNullable(reqCtx.getProperty(LRA_HTTP_PARENT_CONTEXT_HEADER)).map(URI.class::cast).ifPresent(suppressedLra -> resCtx.getHeaders().putSingle(LRA_HTTP_CONTEXT_HEADER, suppressedLra));
}
Also used : LRA_HTTP_CONTEXT_HEADER(org.eclipse.microprofile.lra.annotation.ws.rs.LRA.LRA_HTTP_CONTEXT_HEADER) PropagatedHeaders(io.helidon.lra.coordinator.client.PropagatedHeaders) LRA_HTTP_RECOVERY_HEADER(org.eclipse.microprofile.lra.annotation.ws.rs.LRA.LRA_HTTP_RECOVERY_HEADER) Participant(io.helidon.lra.coordinator.client.Participant) CompletionException(java.util.concurrent.CompletionException) Logger(java.util.logging.Logger) WebApplicationException(jakarta.ws.rs.WebApplicationException) Contexts(io.helidon.common.context.Contexts) Response(jakarta.ws.rs.core.Response) ContainerRequestContext(jakarta.ws.rs.container.ContainerRequestContext) CoordinatorConnectionException(io.helidon.lra.coordinator.client.CoordinatorConnectionException) AnnotationInstance(org.jboss.jandex.AnnotationInstance) Duration(java.time.Duration) ResourceInfo(jakarta.ws.rs.container.ResourceInfo) Optional(java.util.Optional) Single(io.helidon.common.reactive.Single) CoordinatorClient(io.helidon.lra.coordinator.client.CoordinatorClient) ContainerResponseContext(jakarta.ws.rs.container.ContainerResponseContext) URI(java.net.URI) Method(java.lang.reflect.Method) LRA_HTTP_PARENT_CONTEXT_HEADER(org.eclipse.microprofile.lra.annotation.ws.rs.LRA.LRA_HTTP_PARENT_CONTEXT_HEADER) Response(jakarta.ws.rs.core.Response) PropagatedHeaders(io.helidon.lra.coordinator.client.PropagatedHeaders) URI(java.net.URI)

Example 5 with ResourceInfo

use of jakarta.ws.rs.container.ResourceInfo in project tessera by ConsenSys.

the class LoggingFilterTest method filterNullResourceInfoClass.

@Test
public void filterNullResourceInfoClass() {
    ResourceInfo resourceInfo = mock(ResourceInfo.class);
    loggingFilter.setResourceInfo(resourceInfo);
    when(resourceInfo.getResourceClass()).thenReturn(null);
    ContainerRequestContext request = mock(ContainerRequestContext.class);
    // if this doesn't throw exception then test passed
    loggingFilter.filter(request);
}
Also used : ResourceInfo(jakarta.ws.rs.container.ResourceInfo) ContainerRequestContext(jakarta.ws.rs.container.ContainerRequestContext) Test(org.junit.Test)

Aggregations

ResourceInfo (jakarta.ws.rs.container.ResourceInfo)5 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)2 HttpServletResponse (jakarta.servlet.http.HttpServletResponse)2 WebApplicationException (jakarta.ws.rs.WebApplicationException)2 ContainerRequestContext (jakarta.ws.rs.container.ContainerRequestContext)2 Request (jakarta.ws.rs.core.Request)2 Response (jakarta.ws.rs.core.Response)2 UriInfo (jakarta.ws.rs.core.UriInfo)2 Method (java.lang.reflect.Method)2 Test (org.junit.Test)2 XSPErrorPage (com.ibm.designer.runtime.domino.adapter.util.XSPErrorPage)1 Contexts (io.helidon.common.context.Contexts)1 Single (io.helidon.common.reactive.Single)1 CoordinatorClient (io.helidon.lra.coordinator.client.CoordinatorClient)1 CoordinatorConnectionException (io.helidon.lra.coordinator.client.CoordinatorConnectionException)1 Participant (io.helidon.lra.coordinator.client.Participant)1 PropagatedHeaders (io.helidon.lra.coordinator.client.PropagatedHeaders)1 Priority (jakarta.annotation.Priority)1 Json (jakarta.json.Json)1 JsonGenerator (jakarta.json.stream.JsonGenerator)1