I have written some exception mappers to catch and handle the in-built rest easy exceptions like NotFoundException,MethodNotAllowedException, etc., Sample code as shown:
#Provider
public class NotFoundExceptionMapper implements ExceptionMapper<org.jboss.resteasy.spi.NotFoundException>
{
#Override
Response toResponse(org.jboss.resteasy.spi.NotFoundException exception) {
return Response.status(500).build();
}
}
I have also written a try catch block in my web filter class. Whenever a NotFoundException occurs, it is not caught in the mapper, but it goes to the catch block in the Filter.
Whereas I have tried another exception mapper class to handle JsonParsingException. This is working correctly and giving a proper response from the mapper whenever a Json Parse exception occurs.
The issue is only with the case of resteasy exceptions.
Also, the Provider has been registered in the application context using the include-filter tag inside component scan.
Please guide me as to what needs to be done to catch rest easy in-built exceptions in the mapper class itself.
Regards,
RM
I had the same problem. Annotating the NotFoundExceptionMapper with #Component should fix it (or adding NotFoundExceptionMapper as a bean to your application context (xml-file)).
When your Spring context is started the NotFoundExceptionMapper should be registered (you should something like "Pre-instantiating singletons in ... " in your logging)
Here is my demo project
1) a simple RESTful app with 3 java files:
1.1) RestNotFoundExceptionHandler.java
package demo.app;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
#Provider
public class RestNotFoundExceptionHandler implements ExceptionMapper<NotFoundException> {
#Override
public Response toResponse(NotFoundException e) {
return Response.ok().entity(e.toString() + "\n").type(MediaType.TEXT_PLAIN).build();
}
}
1.2) AppRest.java
package demo.app;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
#Path("/")
public class AppRest {
#GET
#Path("millis")
#Produces(MediaType.TEXT_PLAIN)
public String refresh(#Context HttpServletRequest request) {
try {
return Long.toString(System.currentTimeMillis()) + "\n";
} catch (Exception e) {
return e.toString() + "\n";
}
}
}
1.3) AppMain.java
package demo.app;
import javax.ws.rs.NotFoundException;
import org.jboss.resteasy.plugins.server.tjws.TJWSEmbeddedJaxrsServer;
public class AppMain {
private static final int PORT = 8080;
public static void main(String[] args) {
AppRest appRest = new AppRest();
TJWSEmbeddedJaxrsServer tjws = new TJWSEmbeddedJaxrsServer();
tjws.setPort(PORT);
tjws.setRootResourcePath("/rest");
tjws.start();
tjws.getDeployment().getRegistry().addSingletonResource(appRest);
tjws.getDeployment().getProviderFactory().getExceptionMappers()
.put(NotFoundException.class, new RestNotFoundExceptionHandler());
}
}
2) project dependencies, 4 jar files
jaxrs-api-3.0.9.Final.jar
resteasy-jaxrs-3.0.9.Final.jar
servlet-api-2.5.jar
tjws-3.0.9.Final.jar
3) curl test cases:
3.1) normal case:
$ curl http://127.0.0.1:8080/rest/millis
1419167594504
3.2) RestNotFoundExceptionHandler case:
$ curl http://127.0.0.1:8080/rest/bad
javax.ws.rs.NotFoundException: Could not find resource for full path: http://127.0.0.1:8080/rest/bad
I tried the same thing and fell into trouble while trying to map UnsupportedMediaTypeException.
According to http://docs.jboss.org/resteasy/docs/1.1.GA/userguide/html/ExceptionHandling.html and the first line under Exception Mappers section it seems you can only map application Exceptions.
Related
I have the following implementation to consume the message from Azure Service Bus using Spring Boot application however I want to be able to control the ServiceBusConsumer from automatically start listening to the Topic using Spring boot profile property
something like this in the application.yaml
servicebus.consumer.enable=false
it should disable the ServiceBusConsumer from listening to the Topic(s) as well as I should be able to start the ServiceBusConsumer using a REST API - eg: ./api/servicebus/consumer/start?
import com.microsoft.azure.servicebus.ExceptionPhase;
import com.microsoft.azure.servicebus.IMessage;
import com.microsoft.azure.servicebus.IMessageHandler;
import com.microsoft.azure.servicebus.ISubscriptionClient;
import lombok.extern.log4j.Log4j2;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import java.util.concurrent.CompletableFuture;
#Log4j2
#Component
class ServiceBusConsumer implements Ordered {
private final ISubscriptionClient iSubscriptionClient;
ServiceBusConsumer(ISubscriptionClient isc) {
this.iSubscriptionClient = isc;
}
#EventListener(ApplicationReadyEvent.class)
public void consume() throws Exception {
this.iSubscriptionClient.registerMessageHandler(new IMessageHandler() {
#Override
public CompletableFuture<Void> onMessageAsync(IMessage message) {
log.info("received message " + new String(message.getBody()) + " with body ID " + message.getMessageId());
return CompletableFuture.completedFuture(null);
}
#Override
public void notifyException(Throwable exception, ExceptionPhase phase) {
log.error("eeks!", exception);
}
});
}
#Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE;
}
}
You can create the ServiceBusConsumer bean conditionally by adding the #ConditionalOnProperty annotation like so, to make sure the bean is created only when servicebus.consumer.enabled=true:
#Log4j2
#Component
#ConditionalOnProperty(prefix = "servicebus.consumer", name = "enabled")
class ServiceBusConsumer implements Ordered {
...
}
I have configured spring boot to load Jersey as a filter.
spring.jersey.type=filter
I have set my Jersey property to allow static content:
property(ServletProperties.FILTER_FORWARD_ON_404, true);
I have read in spring boot that I can put my content inside my resources dir, under directories named 'static', 'public' folders. Yet, I can never reach my index.html page. The only way I have gotten this to work is to create a webapp dir under src/main and put my index.html file in there. I am deploying the app as a jar.
The problem occurs when there is a usage of exception jersey provider handler like:
package com.product.api.endpoint;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import org.springframework.stereotype.Component;
import com.product.api.entity.DefaultError;
import com.product.api.exception.DefaultException;
#Component
#Provider
public class DefaultExceptionHandler implements ExceptionMapper<RuntimeException> {
#Override
public Response toResponse(RuntimeException ex) {
if(ex instanceof DefaultException) {
DefaultException dex = (DefaultException) ex;
return Response.status(dex.getCode())
.entity(new DefaultError(dex.getMessage()))
.type(MediaType.APPLICATION_JSON)
.build();
} else {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(new DefaultError(ex.getMessage()))
.type(MediaType.APPLICATION_JSON)
.build();
}
}
}
If the #Provider it is not defined the static content works like a charm.
I ran into exact the same issue, and I solved it by adding these lines:
public Response toResponse(RuntimeException exception) {
if (exception.getMessage().equals("HTTP 404 Not Found")) {
// allow ServletProperties.FILTER_FORWARD_ON_404 to work
return Response.status(404).build(); // don't change content type or set entity
}
//...
}
I have an spring app which is using tomcat with websockets. I would like to use the DelegatingSecurityContextRunnable to be executed every time when tomcat creates a new thread, i.e. warp the tomcat thread. Does anyone know how this is done. The reason for the question can be found.here
Maybe this can be done with using AOP and some advice?
In Spring boot you can configure a Wrapper by hooking into the Tomcat connector. See this as an example:
#Bean
public EmbeddedServletContainerFactory servletContainerFactory() {
TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory();
factory.addConnectorCustomizers(new TomcatConnectorCustomizer() {
#Override
public void customize(Connector connector) {
AbstractProtocol protocolHandler = (AbstractProtocol) connector.getProtocolHandler();
TaskQueue taskqueue = new TaskQueue() {
#Override
public boolean offer(Runnable e, long timeout, TimeUnit unit) throws InterruptedException {
return super.offer(new MyRunnable(e), timeout, unit);
}
#Override
public boolean offer(Runnable o) {
return super.offer(new MyRunnable(o));
}
};
TaskThreadFactory tf = new TaskThreadFactory("artur-" + "-exec-", false, 0);
ThreadPoolExecutor e = new ThreadPoolExecutor(10, 10, 1000, TimeUnit.SECONDS, taskqueue);
taskqueue.setParent(e);
protocolHandler.setExecutor(e);
}
});
return factory;
}
And here is my custom Runable (this can be any wrapper, i did not bother implementing exactly yours):
static class MyRunnable implements Runnable {
private Runnable r;
public MyRunnable(Runnable r) {
this.r = r;
}
#Override
public void run() {
System.out.println("Custom runable");
runInner();
}
void runInner() {
r.run();
}
}
And here are my imports:
import java.util.concurrent.TimeUnit;
import org.apache.catalina.connector.Connector;
import org.apache.coyote.AbstractProtocol;
import org.apache.tomcat.util.threads.TaskQueue;
import org.apache.tomcat.util.threads.TaskThreadFactory;
import org.apache.tomcat.util.threads.ThreadPoolExecutor;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatConnectorCustomizer;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.annotation.PropertySource;
What this does:
The Tomcat connector initialises itself. You can set the executor to use, in which case Tomcat will stop creating its own configuration and instead use yours.
By overwriting the offer methods in the queue, you have the chance to wrap your Runnable in any custom Runnable. In my case, for testing, I simply added a Sysout to see that everything is working correctly.
The Threadpool implementation I used is an exact copy of the tomcat default (minus the properties). This way, behaviour stays the same, except that any Runnable is now your delegating wrapper.
When I test that, my console prints:
Custom runable
I hope this is what you were looking for.
I use spring boot, but this is essentially a tomcat issue not a spring issue. You can adapt the solution to your specific scenario.
-- Artur
I am getting following error in my weblogic console when i am starting my server.
SEVERE: Missing dependency for constructor
public com.test.mine.exception.JsonExceptionMapper(java.lang.String,com.fasterxml.jackson.core.JsonLocation) at parameter index 0
SEVERE: Missing dependency for constructor public com.test.mine.exception.JsonExceptionMapper(java.lang.String,com.fasterxml.jackson.core.JsonLocation) at parameter index 1
Below is my java code.
package com.test.mine.exception;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.core.JsonLocation;
import com.fasterxml.jackson.core.JsonParseException;
#Provider
#Service
public class JsonExceptionMapper extends JsonParseException implements ExceptionMapper {
public JsonExceptionMapper(String msg, JsonLocation loc) {
super(msg, loc);
// TODO Auto-generated constructor stub
}
private static final Logger LOGGER = LoggerFactory.getLogger(JsonExceptionMapper.class);
protected Logger getLogger() {
return LOGGER;
}
public Status getStatus(JsonParseException thr) {
return Status.BAD_REQUEST;
}
#Override
public Response toResponse(Throwable arg0) {
// TODO Auto-generated method stub
return Response.status(Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).build();
}
}
The annotation #Service tells spring to create a singleton of the annotated class. At startup spring tries to create that instance and to provide the required constructor args String msg, JsonLocation loc which it does not find, so the exception.
JsonExceptionMapper does not look like a service, and it should not be a singleton. Instead it must be created whenever an exception is created.
I have never worked with that class, so sorry, cannot give you any advice on how to do that.
I bumped into a similar problem while configuring swagger to work with Jersey. After searching various forums found that Jersey scanning require a constructor without parameters. I added a a constructor and it worked for me.
I'm working with Spring 3.2. In order to validate double values globally, I use CustomNumberEditor. The validation is indeed performed.
But when I input a number like 1234aaa, 123aa45 and so forth, I expect the NumberFormatException to be thrown but it doesn't. The docs says,
ParseException is caused, if the beginning of the specified string cannot be
parsed
Therefore, such values as mentioned above are parsed up to they are represented as numbers and the rest of the string is then omitted.
To avoid this, and to make it throw an exception, when such values are fed, I need to implement my own Property Editor by extending the PropertyEditorSupport class as mentioned in this question.
package numeric.format;
import java.beans.PropertyEditorSupport;
public final class StrictNumericFormat extends PropertyEditorSupport
{
#Override
public String getAsText()
{
System.out.println("value = "+this.getValue());
return ((Number)this.getValue()).toString();
}
#Override
public void setAsText(String text) throws IllegalArgumentException
{
System.out.println("value = "+text);
super.setValue(Double.parseDouble(text));
}
}
The editors I have specified inside a method annotated with the #InitBinder annotation are as follows.
package spring.databinder;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.Format;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.context.request.WebRequest;
#ControllerAdvice
public final class GlobalDataBinder
{
#InitBinder
public void initBinder(WebDataBinder binder, WebRequest request)
{
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
dateFormat.setLenient(false);
binder.setIgnoreInvalidFields(true);
binder.setIgnoreUnknownFields(true);
//binder.setAllowedFields("startDate");
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
//The following is the CustomNumberEditor
NumberFormat numberFormat = NumberFormat.getInstance();
numberFormat.setGroupingUsed(false);
binder.registerCustomEditor(Double.class, new CustomNumberEditor(Double.class, numberFormat, false));
}
}
Since I'm using Spring 3.2, I can take advantage of #ControllerAdvice
Out of curiosity, the overridden methods from the PropertyEditorSupport class in the StrictNumericFormat class are never invoked and the statements that redirect the output to the console as specified inside of those methods (getAsText() and setAsText()) don't print anything on the server console.
I have tried all the approaches described in all the answers of that question but none worked for me. What am I missing here? Is this required to configure in some xml file(s)?
Clearly you have nowhere passed the StrictNumericFormat reference. You should register your editor like:
binder.registerCustomEditor(Double.class, new StrictNumericFormat());
BTW Spring 3.X introduced a new way achieving conversion:Converters