Exception Handler method not getting invoked spring boot - spring

#ControllerAdvice
public class CustomGlobalExceptionHandler extends ResponseEntityExceptionHandler{
#ExceptionHandler
public final ResponseEntity<Object> handleOrgIdException(OrgIdException ex, WebRequest request){
GeneralExceptionResponse exceptionResponse = new GeneralExceptionResponse("-1", ex.getMessage());
return new ResponseEntity(exceptionResponse, HttpStatus.BAD_REQUEST);
}
}
public class OrgIdException extends RuntimeException{
private static final long serialVersionUID = 1L;
public OrgIdException(String message){
super(message);
}
}
#RestController
#Api(tags = "sample")
#RequestMapping(path = "v1", produces = { MediaType.APPLICATION_JSON_VALUE})
public class SampleEndpoint extends AbstractEndpoint {
#GetMapping("badrequest")
public ResponseEntity<SampleObject> doBadRequest(Principal p) throws Exception {
throw new OrgIdException("exception thrown.....");
}
}
Server Logs :
2020-01-27 19:16:34,708 INFO [http-nio-8080-exec-1] [] [] [] org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-01-27 19:16:34,713 INFO [http-nio-8080-exec-1] [] [] [] org.springframework.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-01-27 19:16:34,748 INFO [http-nio-8080-exec-1] [] [] [] org.springframework.web.servlet.DispatcherServlet : Completed initialization in 34 ms
2020-01-27 19:16:34,893 ERROR [http-nio-8080-exec-1] [] [LOCAL] [] com.mckesson.lib.spring.controller.RestController : Failed to process the request
com.mckesson.ms.template.v1.exception.OrgIdException: exception thrown.....
at com.mckesson.ms.template.v1.endpoint.SampleEndpoint.doBadRequest(SampleEndpoint.java:32) ~[main/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_221]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_221]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_221]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_221]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189) ~[spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) ~[spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895) ~[spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800) ~[spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038) ~[spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942) ~[spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005) [spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897) [spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:645) [javax.servlet-api-4.0.1.jar:4.0.1]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882) [spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:750) [javax.servlet-api-4.0.1.jar:4.0.1]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) [tomcat-embed-core-9.0.16.jar:9.0.16]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.16.jar:9.0.16]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) [tomcat-embed-websocket-9.0.16.jar:9.0.16]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.16.jar:9.0.16]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.16.jar:9.0.16]
I am using spring boot application. Can anyone please suggest, why Exception handler method is not getting called? When I add the exception handler method to my controller itself then it works fine.

Just try with a simple class like this.
#ControllerAdvice
public class MyControllerAdvice {
#ResponseBody
#ExceptionHandler(OrgIdException.class)
#ResponseStatus(HttpStatus.BAD_REQUEST)
public GeneralExceptionResponse handlePersonNotFound(OrgIdException ex) {
return new GeneralExceptionResponse("-1", ex.getMessage());
}
}

Can create one global exception handler to handle http exception via extent ResponseEntityExceptionHandler
#ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
#Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers,
HttpStatus status,
WebRequest request) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("timestamp", new Date());
body.put("status", status.value());
//Get all errors
List<String> errors = ex.getBindingResult()
.getFieldErrors()
.stream()
.map(x -> x.getDefaultMessage())
.collect(Collectors.toList());
body.put("errors", errors);
return new ResponseEntity<>(body, headers, status);
}

Related

Invalid property 'id' of bean class Could not find field for property during fallback access

Below is my Controller
#PostMapping(value="/shoppingcart")
ResponseEntity<ResponseDTO<ShoppingCartItem>>
insertItems(#RequestParam("cartId")Long cartId, #RequestParam ("itemsKey")
Long itemkey) {
ResponseDTO<ShoppingCartItem> responseDTO = new ResponseDTO<>();
Meta meta = new Meta();
ShoppingCartItem cartItem = null;
ShoppingCartItem saveItem = new ShoppingCartItem();
ShoppingCart cart = new ShoppingCart();
cart.setId(cartId);
Items item = new Items();
item.setId(itemkey);
saveItem.setCart(cart);
saveItem.setItem(item);
cartItem = shoppingCartItemService.save(saveItem);
return new ResponseEntity<ResponseDTO<ShoppingCartItem>>(responseDTO, HttpStatus.OK);
}
This is my Entity Class:
#Entity
#Table(name = "tb_shoppingcart_items")
public class ShoppingCartItem implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long cartItemId;
#ManyToOne
#MapsId("shoppingcartId")
private ShoppingCart cart;
#ManyToOne
#MapsId("itemsId")
private Items item;
#Column(name = "quantity")
private boolean quantity;
public Long getCartItemId() {
return cartItemId;
}
public void setCartItemId(Long cartItemId) {
this.cartItemId = cartItemId;
}
public ShoppingCart getCart() {
return cart;
}
public void setCart(ShoppingCart cart) {
this.cart = cart;
}
public Items getItem() {
return item;
}
public void setItem(Items item) {
this.item = item;
}
public boolean isQuantity() {
return quantity;
}
public void setQuantity(boolean quantity) {
this.quantity = quantity;
}
}
#Entity
#Table(name = "tb_shoppingcart")
public class ShoppingCart implements Serializable {
/**
*
*/
private static final long serialVersionUID = -2114870327410506836L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
#Column(name = "dateCreated")
private Date datecreated;
/*
* #JsonIgnore
*
* #OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) List<Items> items
* = new ArrayList<>();
*/
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getDatecreated() {
return datecreated;
}
public void setDatecreated(Date datecreated) {
this.datecreated = datecreated;
}
/*
* public List<Items> getItems() { return items; }
*
* public void setItems(List<Items> items) { this.items = items; }
*/
}
I am getting the below exception while saving my shoppingcartItem in the databse:
ERROR [http-nio-8090-exec-2] org.apache.juli.logging.DirectJDKLog: Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.beans.NotReadablePropertyException: Invalid property 'id' of bean class [com.epam.item.model.ShoppingCartItem]: Could not find field for property during fallback access!] with root cause
org.springframework.beans.NotReadablePropertyException: Invalid property 'id' of bean class [com.epam.item.model.ShoppingCartItem]: Could not find field for property during fallback access!
at org.springframework.data.util.DirectFieldAccessFallbackBeanWrapper.getPropertyValue(DirectFieldAccessFallbackBeanWrapper.java:58)
at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.getId(JpaMetamodelEntityInformation.java:154)
at org.springframework.data.repository.core.support.AbstractEntityInformation.isNew(AbstractEntityInformation.java:42)
at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.isNew(JpaMetamodelEntityInformation.java:233)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:488)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:359)
at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:200)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:644)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:608)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$invoke$3(RepositoryFactorySupport.java:595)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:595)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:59)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:135)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:61)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
at com.sun.proxy.$Proxy105.save(Unknown Source)
at com.epam.item.service.impl.ShoppingCartItemServiceImpl.save(ShoppingCartItemServiceImpl.java:19)
at com.epam.item.controller.ItemController.insertItems(ItemController.java:180)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:908)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:791)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1417)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)

PUT request resulted in 500 (Server Error); invoking error handler

Method to update metadata info of my model through Rest client
my requirement is to do a PUT operation based on a key,along ith this i am sending request parameter for my model which is ProjectMetadata here.
#RequestMapping(value = "/api/di/v1/app/{projectKey}/metadata", method = RequestMethod.PUT, consumes = "application/json")
public ResponseEntity<?> updateProject(#PathVariable(value = "projectKey")
String projectKey,
#RequestBody ProjectMetadata metadata) throws JSONException {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Authorization", "Basic <aut key>");
JSONObject requestBody = new JSONObject();
requestBody.put("label", metadata.getLabel());
requestBody.put("description", metadata.getDescription());
requestBody.put("shortDesc", metadata.getShortDesc());
requestBody.put("tag", metadata.getTags());
logger.debug("requestBody" + requestBody);
HttpEntity<String> requestEntity = new HttpEntity<String>(requestBody.toString(), headers);
logger.debug("requestentity" + requestEntity.toString());
RestTemplate restTemplate = new RestTemplate();
String url = "http://<>/public/api/projects/{projectKey}/metadata";
logger.debug("trying to send request to create project");
ResponseEntity<?> createResponse = null;
try {
createResponse = restTemplate.exchange(url, HttpMethod.PUT, requestEntity, String.class, projectKey);
// restTemplate.put(url, requestEntity,projectKey);
} catch (HttpClientErrorException e) {
logger.error("Exceptions occurred while processing the request::");
return new ResponseEntity<String>(e.getResponseBodyAsString(), HttpStatus.BAD_REQUEST);
}
return createResponse;
}
ProjectMetadata Model
public class ProjectMetadata
{
private String label;
private String description;
private String shortDesc;
private List<String> tags;
public ProjectMetadata() {
super();
}
public ProjectMetadata(String label, String description, String shortDesc, List<String> tags) {
super();
this.label = label;
this.description = description;
this.shortDesc = shortDesc;
this.tags = tags;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getShortDesc() {
return shortDesc;
}
public void setShortDesc(String shortDesc) {
this.shortDesc = shortDesc;
}
public List<String> getTags() {
return tags;
}
public void setTags(List<String> tags) {
this.tags = tags;
}
}
error stack
>2018-04-10 11:48:00,342 11345 [http-nio-9080-exec-1] DEBUG o.s.core.annotation.AnnotationUtils - Failed to meta-introspect annotation [interface org.springframework.web.bind.annotation.RequestBody]: java.lang.NullPointerException
2018-04-10 11:48:00,350 11353 [http-nio-9080-exec-1] DEBUG c.p.controller.ProjectController - requestBody{"description":"adsfy","shortDesc":"nsfdf","label":"testapp","tag":["tag12"]}
2018-04-10 11:48:00,354 11357 [http-nio-9080-exec-1] DEBUG c.p.controller.ProjectController - requestentity<{"description":"adsfy","shortDesc":"nsfdf","label":"testapp","tag":["tag12"]},{Content-Type=[application/json], Authorization=[Basic <>]}>
2018-04-10 11:48:00,366 11369 [http-nio-9080-exec-1] DEBUG c.p.controller.ProjectController - trying to send request to create project
2018-04-10 11:48:00,394 11397 [http-nio-9080-exec-1] DEBUG o.s.web.client.RestTemplate - Created PUT request for "http://<>/public/api/projects/abcde/metadata"
2018-04-10 11:48:00,394 11397 [http-nio-9080-exec-1] DEBUG o.s.web.client.RestTemplate - Setting request Accept header to [text/plain, application/json, application/*+json, */*]
2018-04-10 11:48:00,394 11397 [http-nio-9080-exec-1] DEBUG o.s.web.client.RestTemplate - Writing [{"description":"adsfy","shortDesc":"nsfdf","label":"testapp","tag":["tag12"]}] as "application/json" using [org.springframework.http.converter.StringHttpMessageConverter#6c0f36de]
2018-04-10 11:48:00,954 11957 [http-nio-9080-exec-1] DEBUG o.s.web.client.RestTemplate - PUT request for "http://<>/public/api/projects/abcde/metadata" resulted in 500 (Server Error); invoking error handler
2018-04-10 11:48:00,954 11957 [http-nio-9080-exec-1] DEBUG o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver - Resolving exception from handler [public org.springframework.http.ResponseEntity<?> com.project.controller.ProjectController.updateProject(java.lang.String,com.model.project.ProjectMetadata) throws org.json.JSONException]: org.springframework.web.client.HttpServerErrorException: 500 Server Error
2018-04-10 11:48:00,958 11961 [http-nio-9080-exec-1] DEBUG o.s.w.s.m.a.ResponseStatusExceptionResolver - Resolving exception from handler [public org.springframework.http.ResponseEntity<?> com.project.controller.ProjectController.updateProject(java.lang.String,com.model.project.ProjectMetadata) throws org.json.JSONException]: org.springframework.web.client.HttpServerErrorException: 500 Server Error
2018-04-10 11:48:00,958 11961 [http-nio-9080-exec-1] DEBUG o.s.w.s.m.s.DefaultHandlerExceptionResolver - Resolving exception from handler [public org.springframework.http.ResponseEntity<?> com.project.controller.ProjectController.updateProject(java.lang.String,com.model.project.ProjectMetadata) throws org.json.JSONException]: org.springframework.web.client.HttpServerErrorException: 500 Server Error
2018-04-10 11:48:00,962 11965 [http-nio-9080-exec-1] DEBUG o.s.web.servlet.DispatcherServlet - Could not complete request
org.springframework.web.client.HttpServerErrorException: 500 Server Error
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:97)
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:79)
at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:777)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:730)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:686)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:602)
at com.project.controller.ProjectController.updateProject(ProjectController.java:120)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:870)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:776)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
at org.springframework.web.servlet.FrameworkServlet.doPut(FrameworkServlet.java:892)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:664)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:496)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
2018-04-10 11:48:00,962 11965 [http-nio-9080-exec-1] DEBUG o.s.b.w.s.f.OrderedRequestContextFilter - Cleared thread-bound request context: org.apache.catalina.connector.RequestFacade#440e2d74
2018-04-10 11:48:00,966 11969 [http-nio-9080-exec-1] ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.client.HttpServerErrorException: 500 Server Error] with root cause
org.springframework.web.client.HttpServerErrorException: 500 Server Error
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:97)
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:79)
at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:777)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:730)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:686)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:602)
at com.project.controller.ProjectController.updateProject(ProjectController.java:120)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:870)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:776)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
at org.springframework.web.servlet.FrameworkServlet.doPut(FrameworkServlet.java:892)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:664)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:496)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
2018-04-10 11:48:00,970 11973 [http-nio-9080-exec-1] DEBUG o.s.web.servlet.DispatcherServlet - DispatcherServlet with name 'dispatcherServlet' processing PUT request for [/error]
2018-04-10 11:48:00,970 11973 [http-nio-9080-exec-1] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Looking up handler method for path /error
2018-04-10 11:48:00,974 11977 [http-nio-9080-exec-1] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Returning handler method [public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)]
2018-04-10 11:48:00,974 11977 [http-nio-9080-exec-1] DEBUG o.s.b.f.s.DefaultListableBeanFactory - Returning cached instance of singleton bean 'basicErrorController'
2018-04-10 11:48:01,006 12009 [http-nio-9080-exec-1] DEBUG o.s.w.s.m.m.a.HttpEntityMethodProcessor - Written [{timestamp=Tue Apr 10 11:48:00 IST 2018, status=500, error=Internal Server Error, message=500 Server Error, path=/rfi/api/di/v1/app/abcde/metadata/}] as "application/json" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter#4e9658b5]
2018-04-10 11:48:01,006 12009 [http-nio-9080-exec-1] DEBUG o.s.web.servlet.DispatcherServlet - Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2018-04-10 11:48:01,006 12009 [http-nio-9080-exec-1] DEBUG o.s.web.servlet.DispatcherServlet - Successfully completed request
What is causing this error?Plase help
request and response image
headers
request
The error is not linked to your code.
The 500 error is returned from the external service your are calling.
Try to call your external service using another client like postman to be sure the service works the way you are using it .
Based on the conversation we had in the comments.
The only thing that is different between your code and the screenshot of your request via postman is the missing s in "tags" (in the code in your question you wrote "tag" instead of "tags")

Spring Boot 1.4.3 / servlet api 3.1 Request cannot be cast to custom CustomServletRequestWrapper which extends standard HttpServletRequestWrapper

I have implemented a custom servlet request wrapper which extends standard HttpServletRequestWrapper for XSS security vulnerabilities.
However when I hit my application URL configured via Spring Boot 1.4.3 both (Jetty or Undertow) display error message as :
Request cannot be cast to com.example.rest.security.api.DemoServletRequestWrapper.
Not sure what is causing this issue as my custom servlet request wrapper is extending standard HttpServletRequestWrapper.
I have tried both with latest Jetty and Undertow spring boot starters. However I still get similar exception stack trace message.
Any pointers as How to resolve this issue and what is the root cause of the issue?
My application is a Spring Boot RESTFul web service flat jar.
Below are my Spring Boot / Jetty dependencies.
dependencies {
compile('org.springframework.boot:spring-boot-starter')
compile("org.springframework.boot:spring-boot-starter-web:1.4.3.RELEASE")
compile("org.springframework.boot:spring-boot-starter-jetty:1.4.3.RELEASE")
OR Undertow
compile("org.springframework.boot:spring-boot-starter-undertow:1.4.3.RELEASE")
compile("org.springframework.boot:spring-boot-starter-jersey:1.4.3.RELEASE")
compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.5'
testCompile('org.springframework.boot:spring-boot-starter-test')
}
Below is Jetty stack trace
2017-01-12 11:17:28.054 INFO 6340 --- [main] com.example.DemoApplication : Started DemoApplication in 5.198 seconds (JVM running for 5.771)
2017-01-12 11:19:15.505 WARN 6340 --- [qtp1991294891-13] o.eclipse.jetty.servlet.ServletHandler : /demo/v1.0/api/gateway
java.lang.ClassCastException: org.eclipse.jetty.server.Request cannot be cast to com.example.api.rest.security.api.DemoServletRequestWrapper
at com.example.api.filters.XSSFilter.doFilter(XSSFilter.java:30) ~[classes!/:na]
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1699) ~[jetty-servlet-9.3.14.v20161028.jar!/:9.3.14.v20161028]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-4.3.5.RELEASE.jar!/:4.3.5.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.5.RELEASE.jar!/:4.3.5.RELEASE]
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1699) ~[jetty-servlet-9.3.14.v20161028.jar!/:9.3.14.v20161028]
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:89) ~[spring-web-4.3.5.RELEASE.jar!/:4.3.5.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.5.RELEASE.jar!/:4.3.5.RELEASE]
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1699) ~[jetty-servlet-9.3.14.v20161028.jar!/:9.3.14.v20161028]
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77) ~[spring-web-4.3.5.RELEASE.jar!/:4.3.5.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.5.RELEASE.jar!/:4.3.5.RELEASE]
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1699) ~[jetty-servlet-9.3.14.v20161028.jar!/:9.3.14.v20161028]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) ~[spring-web-4.3.5.RELEASE.jar!/:4.3.5.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.5.RELEASE.jar!/:4.3.5.RELEASE]
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1699) ~[jetty-servlet-9.3.14.v20161028.jar!/:9.3.14.v20161028]
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:582) [jetty-servlet-9.3.14.v20161028.jar!/:9.3.14.v20161028]
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143) [jetty-server-9.3.14.v20161028.jar!/:9.3.14.v20161028]
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:548) [jetty-security-9.3.14.v20161028.jar!/:9.3.14.v20161028]
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:226) [jetty-server-9.3.14.v20161028.jar!/:9.3.14.v20161028]
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1180) [jetty-server-9.3.14.v20161028.jar!/:9.3.14.v20161028]
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:512) [jetty-servlet-9.3.14.v20161028.jar!/:9.3.14.v20161028]
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185) [jetty-server-9.3.14.v20161028.jar!/:9.3.14.v20161028]
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1112) [jetty-server-9.3.14.v20161028.jar!/:9.3.14.v20161028]
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141) [jetty-server-9.3.14.v20161028.jar!/:9.3.14.v20161028]
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134) [jetty-server-9.3.14.v20161028.jar!/:9.3.14.v20161028]
at org.eclipse.jetty.server.Server.handle(Server.java:534) [jetty-server-9.3.14.v20161028.jar!/:9.3.14.v20161028]
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:320) [jetty-server-9.3.14.v20161028.jar!/:9.3.14.v20161028]
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:251) [jetty-server-9.3.14.v20161028.jar!/:9.3.14.v20161028]
at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:273) [jetty-io-9.3.14.v20161028.jar!/:9.3.14.v20161028]
at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:95) [jetty-io-9.3.14.v20161028.jar!/:9.3.14.v20161028]
at org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:93) [jetty-io-9.3.14.v20161028.jar!/:9.3.14.v20161028]
at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.executeProduceConsume(ExecuteProduceConsume.java:303) [jetty-util-9.3.14.v20161028.jar!/:9.3.14.v20161028]
at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceConsume(ExecuteProduceConsume.java:148) [jetty-util-9.3.14.v20161028.jar!/:9.3.14.v20161028]
at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:136) [jetty-util-9.3.14.v20161028.jar!/:9.3.14.v20161028]
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:671) [jetty-util-9.3.14.v20161028.jar!/:9.3.14.v20161028]
at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:589) [jetty-util-9.3.14.v20161028.jar!/:9.3.14.v20161028]
at java.lang.Thread.run(Unknown Source) [na:1.8.0_112]
Below is undertow stack trace
2017-01-11 16:26:15.486 INFO 12372 --- [main] com.example.DemoApplication : Started DemoApplication in 3.805 seconds (JVM running for 4.325)
2017-01-11 16:26:24.680 ERROR 12372 --- [XNIO-3 task-1] io.undertow.request : UT005023: Exception handling request to /demo/v1.0/api/gateway
java.lang.ClassCastException: io.undertow.servlet.spec.HttpServletRequestImpl cannot be cast to com.example.api.rest.security.api.DemoServletRequestWrapper
at com.example.api.filters.XSSFilter.doFilter(XSSFilter.java:30) ~[classes!/:na]
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61) ~[undertow-servlet-1.3.25.Final.jar!/:1.3.25.Final]
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131) ~[undertow-servlet-1.3.25.Final.jar!/:1.3.25.Final]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-4.3.5.RELEASE.jar!/:4.3.5.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.5.RELEASE.jar!/:4.3.5.RELEASE]
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61) ~[undertow-servlet-1.3.25.Final.jar!/:1.3.25.Final]
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131) ~[undertow-servlet-1.3.25.Final.jar!/:1.3.25.Final]
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:89) ~[spring-web-4.3.5.RELEASE.jar!/:4.3.5.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.5.RELEASE.jar!/:4.3.5.RELEASE]
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61) ~[undertow-servlet-1.3.25.Final.jar!/:1.3.25.Final]
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131) ~[undertow-servlet-1.3.25.Final.jar!/:1.3.25.Final]
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77) ~[spring-web-4.3.5.RELEASE.jar!/:4.3.5.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.5.RELEASE.jar!/:4.3.5.RELEASE]
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61) ~[undertow-servlet-1.3.25.Final.jar!/:1.3.25.Final]
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131) ~[undertow-servlet-1.3.25.Final.jar!/:1.3.25.Final]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) ~[spring-web-4.3.5.RELEASE.jar!/:4.3.5.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.5.RELEASE.jar!/:4.3.5.RELEASE]
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61) ~[undertow-servlet-1.3.25.Final.jar!/:1.3.25.Final]
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131) ~[undertow-servlet-1.3.25.Final.jar!/:1.3.25.Final]
at io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84) ~[undertow-servlet-1.3.25.Final.jar!/:1.3.25.Final]
at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62) ~[undertow-servlet-1.3.25.Final.jar!/:1.3.25.Final]
at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36) ~[undertow-servlet-1.3.25.Final.jar!/:1.3.25.Final]
at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131) ~[undertow-servlet-1.3.25.Final.jar!/:1.3.25.Final]
at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57) ~[undertow-servlet-1.3.25.Final.jar!/:1.3.25.Final]
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) ~[undertow-core-1.3.25.Final.jar!/:1.3.25.Final]
at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46) ~[undertow-core-1.3.25.Final.jar!/:1.3.25.Final]
at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64) ~[undertow-servlet-1.3.25.Final.jar!/:1.3.25.Final]
at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60) ~[undertow-core-1.3.25.Final.jar!/:1.3.25.Final]
at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77) ~[undertow-servlet-1.3.25.Final.jar!/:1.3.25.Final]
at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43) ~[undertow-core-1.3.25.Final.jar!/:1.3.25.Final]
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) ~[undertow-core-1.3.25.Final.jar!/:1.3.25.Final]
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43) ~[undertow-core-1.3.25.Final.jar!/:1.3.25.Final]
at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:285) ~[undertow-servlet-1.3.25.Final.jar!/:1.3.25.Final]
at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:264) ~[undertow-servlet-1.3.25.Final.jar!/:1.3.25.Final]
at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81) ~[undertow-servlet-1.3.25.Final.jar!/:1.3.25.Final]
at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:175) ~[undertow-servlet-1.3.25.Final.jar!/:1.3.25.Final]
at io.undertow.server.Connectors.executeRootHandler(Connectors.java:207) ~[undertow-core-1.3.25.Final.jar!/:1.3.25.Final]
at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:802) [undertow-core-1.3.25.Final.jar!/:1.3.25.Final]
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_112]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_112]
at java.lang.Thread.run(Unknown Source) [na:1.8.0_112]
Below is the source code.
/* Main Spring Boot application */
#SpringBootApplication
#Import(AppConfig.class)
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
App configuration with XSS Filter registration bean
#Configuration
public class AppConfig {
#Bean
public FilterRegistrationBean xssFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
XSSFilter xssFilter = new XSSFilter();
registration.setFilter(xssFilter);
registration.setName("XSSFilter");
registration.addUrlPatterns("/v1.0/*");
return registration;
}
}
Spring Boot Jersey Config for RESTful services implementation
#Component
public class JerseyConfig extends ResourceConfig {
public JerseyConfig() {
registerEndpoints();
}
private void registerEndpoints() {
register(DemoEndPoint.class);
}
}
Demo End Point REST service
#Component
#Path("/api")
public class DemoEndPoint {
#GET
#Path("/gateway")
public String test() {
return "API Gateway!";
}
}
XSS Filter implementation
public class XSSFilter implements Filter {
private static final Logger LOGGER = LoggerFactory.getLogger(XSSFilter.class);
#Override
public void init(final FilterConfig filterConfig) throws ServletException {
}
#Override
public void doFilter(final ServletRequest request, final ServletResponse response,
final FilterChain chain) throws IOException, ServletException
{
LOGGER.debug("doFilter - Entry");
LOGGER.debug("doFilter - Checking http request body for XSS vulnerabilities");
final DemoServletRequestWrapper requestWrapper = (DemoServletRequestWrapper)request;
LOGGER.debug("doFilter - Request body = {}", requestWrapper.getBody());
final String body = EncodeHtmlContent(requestWrapper.getBody());
LOGGER.debug("doFilter - Request body encoded to {}", body);
requestWrapper.setBody(body);
chain.doFilter(requestWrapper, response);
}
}
/* DemoServletRequestWrapper extends HttpServletRequestWrapper */
I have implemented all the methods of standard `HttpServletRequestWrapper` in this class. For brevity I am displaying only one method in my stack query.
public class DemoServletRequestWrapper extends HttpServletRequestWrapper implements
HttpServletRequest {
private String body;
private static final Logger LOGGER = LoggerFactory.getLogger(DemoServletRequestWrapper.class);
public MifidServletRequestWrapper(final HttpServletRequest request) throws IOException {
super(request);
final StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;
try {
final InputStream inputStream = request.getInputStream();
if (inputStream != null) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
final char[] charBuffer = new char[128];
int bytesRead = -1;
while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
stringBuilder.append(charBuffer, 0, bytesRead);
}
} else {
stringBuilder.append("");
}
} catch (final IOException ex) {
LOGGER.error("Error whilst creating the DemoServletRequestWrapper", ex);
throw ex;
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (final IOException ex) {
LOGGER.error("Error whilst creating the DemoServletRequestWrapper", ex);
throw ex;
}
}
}
body = stringBuilder.toString();
}
Implemented all the methods and able to compile my build successfully

Spring-MVC does not call repository method

I am fairly new, and trying to make a query on my local database but the code throws a NullPointerException exception.
It is weird as it looks like it never calls the selected method of repository called findNamesByCat(String cat). It does not show the output of System.err.println("in repository"); that is located in this method.
Just after following line I called a method of another service and that works!!
List<Name> Names = myService.findNamesByCat(cat);
Error
Mar 18, 2015 1:29:07 PM
org.apache.catalina.core.StandardWrapperValve invoke
... threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at com.myproject.web.MyController.showCategoryNames(MyController.java:41)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:777)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:706)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1074)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Code
#Controller
public class myController {
#Autowired
private MyService myService;
#RequestMapping(value = "/{cat}", method = RequestMethod.GET)
public String showCategoryNames(#PathVariable String cat, Model model) {
System.err.println("in web"); //shows this
List<Name> Names = myService.findNamesByCat(cat);
System.err.println(Names.size()); //this is line 41
model.addAttribute("Names", Names);
model.addAttribute("cat", cat);
return "cat";
}
#Service
public class MyServiceImpl implements MyService {
#Autowired
private NameRepository nameRepository;
#Override
#Transactional(readOnly = true)
public List<Name> findListOfNamesByCat(String cat) {
System.err.println("in service"); //does not show this
return nameRepository.findNamesByCat(cat);
}
}
#Repository
public class NameRepositoryImp implements NameRepository {
#Autowired
SessionFactory sessionFactory;
#Override
public List<Name> findNamesByCat(String cat){
System.err.println("in repository"); //does not show this
try {
Criteria crit = sessionFactory.getCurrentSession().createCriteria(
Name.class);
crit.add(Restrictions.eq("category", cat));
return crit.list();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
Servlet
<context:annotation-config />
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/" />
<context:component-scan base-package="com.myproject" />
UPDATE
I made following changes as well but it does not work yet.
#Controller
public class myController {
#Autowired
#Qualifier("repositoryService")
private MyService myService;
#Service(value = "repositoryService")
public class MyServiceImpl implements MyService {
#Autowired
#Qualifier("repositoryMain")
private NameRepository nameRepository;
#Repository(value = "repositoryMain")
public class NameRepositoryImpl implements NameRepository {
#Autowired
SessionFactory sessionFactory;
You defined #PathVariable String cat, but didn't mark it correctly in #RequestMapping, add {} for PathVariable "cat", like this:
#RequestMapping(value = "/{cat}", method = RequestMethod.GET)
The issue was that, for some reasons the body of the methods that I was calling were empty and the correct bodies where replaced by body of other methods. After replacing the bodies and cleaning the project it started working. Thank you for your attempt to help and apologies for the confusion.

Strange issue with Mockito and Spring test MVC

I am unit testing the following Spring MVC controller method:
#RequestMapping(value = "/advertisement/family/edit/{advertisementId}", method = RequestMethod.GET, produces = "text/html")
#AdvertisementExistsAndBelongsToMemberCheck
public String editFamilyAdvertisementForm(#ModelAttribute FamilyAdvertisementInfo familyAdvertisementInfo, #PathVariable long advertisementId, Model model, #CurrentMember Member member) {
FamilyAdvertisement advertisement = advertisementService.findFamilyAdvertisement(advertisementId);
familyAdvertisementInfo.setFamilyAdvertisement(advertisement);
populateFamilyAdvertisementModel(model, familyAdvertisementInfo, member);
return "advertisement/family/edit";
}
The custom annotation (#AdvertisementExistsAndBelongsToMemberCheck) above basically is advised by an aspect as follows:
before(long advertisementId, Member member) : advertisementBelongsToMemberControllerCheck(advertisementId, member) {
if (!advertisementService.advertisementExistsAndBelongsToMember(advertisementId, member)) {
throw new AccessDeniedException("Advertisement does not belong to member!");
}
}
If an AccessDeniedException is thrown, then the following controller advice exception handler kicks in:
#ExceptionHandler(AccessDeniedException.class)
#ResponseStatus(value = HttpStatus.FORBIDDEN)
public String accessDeniedException(AccessDeniedException e) {
return "error/403";
}
Now, here is how I am trying to test the above controller method:
#ContextConfiguration
#WebAppConfiguration
#RunWith(SpringJUnit4ClassRunner.class)
public class AdvertisementControllerTest {
#Autowired
private WebApplicationContext ctx;
private MockMvc mockMvc;
#Autowired
private AdvertisementService advertisementService;
#Before
public void setup() {
mockMvc = webAppContextSetup(ctx).build();
when(advertisementService.advertisementExistsAndBelongsToMember(eq(111), any(Member.class))).thenReturn(Boolean.FALSE);
when(advertisementService.advertisementExistsAndBelongsToMember(eq(222), any(Member.class))).thenReturn(Boolean.TRUE);
}
#Test
public void shouldAllow() throws Exception {
mockMvc.perform(get("/advertisement/family/edit/222"))//
.andDo(print())//
.andExpect(status().isOk());
}
#Configuration
#EnableSpringConfigured
static class testConfiguration {
#Bean
public AdvertisementController advertisementController() {
return new AdvertisementController();
}
#Bean
public InternalResourceViewResolver getInternalResourceViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/pages/");
resolver.setSuffix(".jsp");
return resolver;
}
#Bean
public AdvertisementService advertisementService() {
return mock(AdvertisementService.class);
}
}
}
The test systematically fails with the following stacktrace:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.security.access.AccessDeniedException: Advertisement does not belong to member!
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:948)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:66)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:168)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:136)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:134)
at com.bignibou.tests.controller.advertisement.AdvertisementControllerTest.shouldAllow(AdvertisementControllerTest.java:64)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.springframework.security.access.AccessDeniedException: Advertisement does not belong to member!
at com.bignibou.aop.AdvertisementExistsAndBelongsToMemberCheckAspect.ajc$before$com_bignibou_aop_AdvertisementExistsAndBelongsToMemberCheckAspect$2$3edd453b(AdvertisementExistsAndBelongsToMemberCheckAspect.aj:34)
at com.bignibou.controller.advertisement.AdvertisementController.editFamilyAdvertisementForm(AdvertisementController.java:56)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:440)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:428)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
... 38 more
I am not sure what I am getting wrong with Mockito...
Note that I did specify /222 in the path, indicating that my mock should return true in the aspect and allow the controller method to proceed. However, this is not the case.
Can anyone please help?
Is the aspect injected with the same mocked instance of AdvertisementService?
The issue is that the type of the argument was a long and I passed an int.
Changing to:
when(advertisementService.advertisementExistsAndBelongsToMember(eq(222L), any(Member.class))).thenReturn(Boolean.TRUE);
and:
#Test
public void shouldAllow() throws Exception {
mockMvc.perform(get("/advertisement/family/edit/{advertisementId}", 222L))//
.andDo(print())//
.andExpect(status().isOk());
}
sorted the issue.

Resources