I'm using a REST service with CXF that does a GET request with an int parameter.
#Path("parkingservice")
public interface ParkingService {
/**
* #param id
* #return
*/
#GET
#Path("/parkings/{id}/parkingState")
#Produces(MediaType.APPLICATION_JSON)
ParkingState getStatus(#PathParam("id") int id);
}
I call my service this way :
http://domain.com:8087/services/rest/parkingservice/parkings/2805/parkingState
When I put a number, it works, but when I put a String, I have this exception :
WARNING: javax.ws.rs.NotFoundException: java.lang.NumberFormatException: For input string: "dd"
at org.apache.cxf.jaxrs.utils.InjectionUtils.handleParameter(InjectionUtils.java:322)
at org.apache.cxf.jaxrs.utils.InjectionUtils.createParameterObject(InjectionUtils.java:845)
at org.apache.cxf.jaxrs.utils.JAXRSUtils.readFromUriParam(JAXRSUtils.java:1041)
at org.apache.cxf.jaxrs.utils.JAXRSUtils.createHttpParameterValue(JAXRSUtils.java:733)
at org.apache.cxf.jaxrs.utils.JAXRSUtils.processParameter(JAXRSUtils.java:708)
at org.apache.cxf.jaxrs.utils.JAXRSUtils.processParameters(JAXRSUtils.java:655)
at org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor.processRequest(JAXRSInInterceptor.java:238)
at org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor.handleMessage(JAXRSInInterceptor.java:99)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:271)
at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:239)
at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:223)
at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:203)
at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:137)
at org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:158)
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:243)
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.doGet(AbstractHTTPServlet.java:168)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:219)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:947)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1009)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:680)
Caused by: java.lang.NumberFormatException: For input string: "dd"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:449)
at java.lang.Integer.valueOf(Integer.java:554)
at org.apache.cxf.common.util.PrimitiveUtils.read(PrimitiveUtils.java:60)
at org.apache.cxf.jaxrs.utils.InjectionUtils.handleParameter(InjectionUtils.java:310)
... 34 more
I'd like to avoid having this exception no matter what type I give..or to find a way to handle this exception with a message like "please provide a good Id"
Thanks a lot
Add an exception mapper to your rest layer. Code goes something like this :
package com.cxf.util;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
public class CustomExceptionMapper implements
ExceptionMapper<NotFoundException> {
public CustomExceptionMapper () {
}
#Override
public Response toResponse(NotFoundException arg0) {
//your logic and return accordingly
return Response.serverError().build();
}
}
And you if you are using Spring to maintain your service beans and cxf configuration then add this mapper as a bean under jaxrs:providers tag, where jaxrs is this : xmlns:jaxrs="http://cxf.apache.org/jaxrs"
Whenever your application will throw notfoundexception it will go in this class.
Second option is that you can take this parameter as String then parse it in your try catch block. On NumberformatException return 400 status code. Since you have a custom POJO as return, you can take a object of HttpServletResponse from org.apache.cxf.jaxrs.ext.MessageContext and set status in it. Below is a dummy code:
public class RestServiceImpl implements RestService{
#Context
MessageContext context;
public CustomPojo getData(String id){
HttpServletResponse httpResponse = context.getHttpServletResponse();
try{
}catch(NumberFormatException e){
httpResponse.setStatusCode(400);
}
}
}
Use the below signature for getStatus method, this would work both ways.
ParkingState getStatus(#PathParam("id") String id);
Your getStatus(#PathParam("id") int id); takes integer as an argument and you are trying to pass String instead of int, that's why it's throwing an exception of NumberFormatException.
You have to handle it,or make a Check is the incoming value is int if not then so a message "please provide a valid input".
Related
When I try to return a Uni with a typed java.util.List in Quarkus in dev mode, i get a ClassNotFound exception. I have read about Quarkus using different class loaders in different profiles, but I don't see that I do anything fancy.
Here's the sender
#Query("offers")
public Uni<List<OfferResponse>> getOffers(#PathParam("category") Integer categoryId) {
OfferRequest event = new OfferRequest();
event.setCategoryId(categoryId);
Uni<List<OfferResponse>> offers = bus.<List<OfferResponse>>request(OfferRequest.ADDRESS, event).onItem().transform(Message::body);
return offers;
}
And here's the consumer
#ConsumeEvent(OfferRequest.ADDRESS)
public Uni<List<OfferResponse>> onOfferQuery(OfferRequest request) {
List<KelkooOffer> offers = getOffers(request.getCategoryId());
List<OfferResponse> responses = new ArrayList<OfferResponse>();
for (KelkooOffer offer : offers) {
responses.add(offer.getEventResponse());
}
return Uni.createFrom().item(responses);
}
The bean I'm trying to return is just a POJO
and the error message
2021-08-18 11:11:16,186 ERROR [io.qua.run.Application] (Quarkus Main Thread) Failed to start application (with profile dev): java.lang.ClassNotFoundException: java.util.List<se.bryderi.events.OfferResponse>
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
at io.quarkus.bootstrap.classloading.QuarkusClassLoader.loadClass(QuarkusClassLoader.java:414)
at io.quarkus.bootstrap.classloading.QuarkusClassLoader.loadClass(QuarkusClassLoader.java:405)
at io.quarkus.bootstrap.classloading.QuarkusClassLoader.loadClass(QuarkusClassLoader.java:414)
at io.quarkus.bootstrap.classloading.QuarkusClassLoader.loadClass(QuarkusClassLoader.java:405)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:398)
at io.quarkus.deployment.steps.VertxProcessor$build609260703.deploy_0(VertxProcessor$build609260703.zig:142)
at io.quarkus.deployment.steps.VertxProcessor$build609260703.deploy(VertxProcessor$build609260703.zig:40)
at io.quarkus.runner.ApplicationImpl.doStart(ApplicationImpl.zig:784)
at io.quarkus.runtime.Application.start(Application.java:101)
at io.quarkus.runtime.ApplicationLifecycleManager.run(ApplicationLifecycleManager.java:101)
at io.quarkus.runtime.Quarkus.run(Quarkus.java:66)
at io.quarkus.runtime.Quarkus.run(Quarkus.java:42)
at io.quarkus.runtime.Quarkus.run(Quarkus.java:119)
at io.quarkus.runner.GeneratedMain.main(GeneratedMain.zig:29)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at io.quarkus.runner.bootstrap.StartupActionImpl$1.run(StartupActionImpl.java:98)
at java.base/java.lang.Thread.run(Thread.java:829)
I get the same result if I run the dev profile or if I run the packaged fast-jar.
Happy for any hint that will point me in the right direction
There is a limitation of the Vert.x EventBus which prevents to encode/decode lists or sets directly.
You could create a wrapper for your OfferResponse list:
import java.util.AbstractList;
import java.util.List;
public class OfferResponseList extends AbstractList<OfferResponse> {
private List<OfferResponse> wrapped;
private OfferResponseList(List<OfferResponse> wrapped) {
this.wrapped = wrapped;
}
public static OfferResponseList wrap(List<OfferResponse> list) {
return new OfferResponseList(list);
}
#Override
public OfferResponse get(int index) {
return wrapped.get(index);
}
#Override
public int size() {
return wrapped.size();
}
}
Then transform your consumer to:
#ConsumeEvent(OfferRequest.ADDRESS)
public Uni<OfferResponseList> onOfferQuery(OfferRequest request) {
List<KelkooOffer> offers = getOffers(request.getCategoryId());
List<OfferResponse> responses = new ArrayList<OfferResponse>();
for (KelkooOffer offer : offers) {
responses.add(offer.getEventResponse());
}
// Notice the call to OfferResponseList.wrap here
return Uni.createFrom().item(OfferResponseList.wrap(responses));
}
That's it. Quarkus will register a codec for OfferResponseList automatically.
On the client side, you do not need to change your code:
#Query("offers")
public Uni<List<OfferResponse>> getOffers(#PathParam("category") Integer categoryId) {
OfferRequest event = new OfferRequest();
event.setCategoryId(categoryId);
// You can use Uni<List<OfferResponse>> or Uni<OfferResponseList>
Uni<List<OfferResponse>> offers = bus.<List<OfferResponse>>request(OfferRequest.ADDRESS, event).onItem().transform(Message::body);
return offers;
}
I have a rest endpoint like below which is supposed to accept an XML input, do some processing on it and then return a response in XML as well.
#RequestMapping(value = "/rest/v1/test/listener", method = RequestMethod.POST)
public ResponseEntity<MyResponseType> processBooking(#RequestBody MyRequest myRequest) throws JAXBException {
MyResponseType response = myService.process(myRequest);
// ... do something with it and generate 'response'
return new ResponseEntity<>(response, HttpStatus.OK);
}
And MyRequest class looks like below which is autogenerated via jaxb and an external xsd which I cannot change (details omitted from the class)
/**
* MyRequest
*/
public class MyRequest {
#XmlElement(required = true)
#XmlSchemaType(name = "string")
protected SomeEnum someEnum;
...
#XmlType(name = "SomeEnum")
#XmlEnum
public enum SomeEnum {
ACTIVITY,
DEPOSIT,
EQUIPMENT,
FEE,
MISC,
PROTECTION,
RENTAL,
TAX,
DISCOUNT;
public static SomeEnum fromValue(String v) {
return valueOf(v);
}
public String value() {
return name();
}
}
}
The problem is that when I try to run it, I get the following error message
2018-04-09 11:47:59.378 WARN 2702 --- [ main]
.w.s.m.s.DefaultHandlerExceptionResolver : Failed to read HTTP
message:
org.springframework.http.converter.HttpMessageNotReadableException:
JSON parse error: Can not construct instance of MyRequest.SomeEnum: no
String-argument constructor/factory method to deserialize from String
value ('MISC'); nested exception is
com.fasterxml.jackson.databind.JsonMappingException: Can not construct
instance of MyRequest.SomeEnum: no String-argument constructor/factory
method to deserialize from String value ('MISC')
A sample xml that I send as input is
<myRequest>
...
<advertiserAssignedId>19ABC12331</advertiserAssignedId>
<listingExternalId>ABC123</listingExternalId>
<unitExternalId>ABC123</unitExternalId>
<someEnum>
<name>MISC</name>
<feeType>MISC</feeType>
...
</someEnum>
...
</myRequest>
You have to specify what is your endpoint consuming using the consumes attribut .
When you post the request to your endpoint, don't forget to set the Content-type header to application/xml
Using Feign to access services that I register on Eureka is a breeze. I am trying to use Feign to access external services and struggling with the basics.
I am playing with a service on Bluemix however to simplify the problem at hand, I am using a simple service.
My Proxy appears as follows:
//#FeignClient(name = "country-service-client", url = "https://country.io")
#FeignClient(name = "another-country-service-client", url = "http://restcountries.eu/rest/v2/name/Australia")
public interface SimpleServiceProxy {
//This one works
#RequestMapping(method = RequestMethod.GET, value = "/names.json", produces = "application/json")
String getCountries();
//This one does not work... This is used in conjunction where the url in the Fiegn Client annotation reads as - http://restcountries.eu/rest/v2
#RequestMapping(method = RequestMethod.GET, value = "/name/{country}", produces = "application/json")
public String getCountryInfo(#PathVariable("country") String country);
//This one doesn't work either
//#RequestMapping(method = RequestMethod.GET, value = "/name/Australia", produces = "application/json")
public String getCountryInfoHardcodedWithinMethod();
}
//This works however I would want to pass parameters and path variables to the URL
#RequestMapping(method = RequestMethod.GET, produces = "application/json")
public String getCountryInfoHardcodedAtFeignClientAnnotation();
}
I have tried a few variants (see the code above) and the last one where the URL is hardcoded at the Feign Client annotation works. The others throw a TimeoutException.
java.util.concurrent.TimeoutException: null
at com.netflix.hystrix.AbstractCommand.handleTimeoutViaFallback(AbstractCommand.java:958) ~[hystrix-core-1.5.3.jar:1.5.3]
at com.netflix.hystrix.AbstractCommand.access$400(AbstractCommand.java:59) ~[hystrix-core-1.5.3.jar:1.5.3]
at com.netflix.hystrix.AbstractCommand$11.call(AbstractCommand.java:573) ~[hystrix-core-1.5.3.jar:1.5.3]
at com.netflix.hystrix.AbstractCommand$11.call(AbstractCommand.java:565) ~[hystrix-core-1.5.3.jar:1.5.3]
at rx.internal.operators.OperatorOnErrorResumeNextViaFunction$4.onError(OperatorOnErrorResumeNextViaFunction.java:139) ~[rxjava-1.1.5.jar:1.1.5]
at rx.internal.operators.OperatorDoOnEach$1.onError(OperatorDoOnEach.java:71) ~[rxjava-1.1.5.jar:1.1.5]
at rx.internal.operators.OperatorDoOnEach$1.onError(OperatorDoOnEach.java:71) ~[rxjava-1.1.5.jar:1.1.5]
at com.netflix.hystrix.AbstractCommand$HystrixObservableTimeoutOperator$1.run(AbstractCommand.java:1099) ~[hystrix-core-1.5.3.jar:1.5.3]
at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable$1.call(HystrixContextRunnable.java:41) ~[hystrix-core-1.5.3.jar:1.5.3]
at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable$1.call(HystrixContextRunnable.java:37) ~[hystrix-core-1.5.3.jar:1.5.3]
at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable.run(HystrixContextRunnable.java:57) ~[hystrix-core-1.5.3.jar:1.5.3]
at com.netflix.hystrix.AbstractCommand$HystrixObservableTimeoutOperator$2.tick(AbstractCommand.java:1116) ~[hystrix-core-1.5.3.jar:1.5.3]
at com.netflix.hystrix.util.HystrixTimer$1.run(HystrixTimer.java:99) ~[hystrix-core-1.5.3.jar:1.5.3]
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) ~[na:1.8.0_112]
at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308) ~[na:1.8.0_112]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180) ~[na:1.8.0_112]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294) ~[na:1.8.0_112]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) ~[na:1.8.0_112]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) ~[na:1.8.0_112]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_112]
I am puzzled and trying to figure things out. I want to get the hardcoded methods working before trying to figure out why the PathVariables aren't working.
What am I missing? (or doing incorrectly here)?
I just tried this simple application and it worked fine for me using
Dalston.RC1
#SpringBootApplication
#EnableFeignClients
#RestController
public class DemoApplication {
#Autowired
SimpleServiceProxy proxy;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#RequestMapping("/")
public String getCountry() {
return proxy.getCountryInfo("Australia");
}
}
#FeignClient(name = "another-country-service-client", url ="http://restcountries.eu/rest/v2")
interface SimpleServiceProxy {
#RequestMapping(method = RequestMethod.GET, value = "/name/{country}", produces = "application/json")
public String getCountryInfo(#PathVariable("country") String country);
}
The exception in your question is indicating a timeout via Hystrix when making the request. You can try disabling Hystrix and seeing if it goes away using feign.hystrix.enabled=false.
I am using Jersey version 2.23.2 and I am unable to figure out how to use JerseyTest to test the responses for when validation fails. For some reason, the below test throws a ConstraintViolationException which is wrapped in a ProcessingException instead of returning 400 Bad Request. I could modify the test to check that the ProcessingException is thrown, but I really want to test the response. When I run HelloResource in Grizzly without JerseyTest, I get the appropriate 400 Bad Request response. Any ideas on how to fix the badRequestResponse() test below?
package example;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.ServerProperties;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Test;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import static org.junit.Assert.assertEquals;
public class BadRequestTest extends JerseyTest {
#XmlAccessorType(XmlAccessType.FIELD)
public static class Hello {
#NotNull(message = "Name is a required field.")
private final String name;
private Hello() {
this(null);
}
public Hello(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
#Path("hello")
public static class HelloResource {
#POST
public String sayHelloToMe(#Valid Hello hello) {
return "Hello " + hello.getName() + "!";
}
}
#Override
protected Application configure() {
return new ResourceConfig(HelloResource.class).property(ServerProperties.BV_SEND_ERROR_IN_RESPONSE, true);
}
/** Test OK Response. This Works!*/
#Test
public void okResponse() {
Response response = target("hello")
.request(MediaType.TEXT_PLAIN)
.post(Entity.json(new Hello("Tiny Tim")));
assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
assertEquals("Hello Tiny Tim!", response.readEntity(String.class));
}
/** Test Bad Request Response. This Fails! */
#Test
public void badRequestResponse() {
Response response = target("hello")
.request(MediaType.TEXT_PLAIN)
.post(Entity.json(new Hello(null)));
assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
}
Here's the exception I am getting:
javax.ws.rs.ProcessingException:
Exception Description: Constraints violated on marshalled bean:
example.BadRequestTest$Hello#456abb66
-->Violated constraint on property name: "Name is a required field.".
Internal Exception: javax.validation.ConstraintViolationException
at org.glassfish.jersey.client.ClientRuntime.invoke(ClientRuntime.java:261)
at org.glassfish.jersey.client.JerseyInvocation$1.call(JerseyInvocation.java:684)
at org.glassfish.jersey.client.JerseyInvocation$1.call(JerseyInvocation.java:681)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:444)
at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:681)
at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:437)
at org.glassfish.jersey.client.JerseyInvocation$Builder.post(JerseyInvocation.java:343)
at example.BadRequestTest.badRequestResponse(BadRequestTest.java:70)
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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:262)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)
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 com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: Exception [EclipseLink-7510] (Eclipse Persistence Services - 2.6.0.v20150309-bf26070): org.eclipse.persistence.exceptions.BeanValidationException
Exception Description: Constraints violated on marshalled bean:
example.BadRequestTest$Hello#456abb66
-->Violated constraint on property name: "Name is a required field.".
Internal Exception: javax.validation.ConstraintViolationException
at org.eclipse.persistence.exceptions.BeanValidationException.constraintViolation(BeanValidationException.java:53)
at org.eclipse.persistence.jaxb.JAXBBeanValidator.buildConstraintViolationException(JAXBBeanValidator.java:385)
at org.eclipse.persistence.jaxb.JAXBBeanValidator.validate(JAXBBeanValidator.java:273)
at org.eclipse.persistence.jaxb.JAXBMarshaller.validateAndTransformIfNeeded(JAXBMarshaller.java:588)
at org.eclipse.persistence.jaxb.JAXBMarshaller.marshal(JAXBMarshaller.java:481)
at org.eclipse.persistence.jaxb.rs.MOXyJsonProvider.writeTo(MOXyJsonProvider.java:949)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.invokeWriteTo(WriterInterceptorExecutor.java:265)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo(WriterInterceptorExecutor.java:250)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
at org.glassfish.jersey.message.internal.MessageBodyFactory.writeTo(MessageBodyFactory.java:1130)
at org.glassfish.jersey.client.ClientRequest.doWriteEntity(ClientRequest.java:517)
at org.glassfish.jersey.client.ClientRequest.writeEntity(ClientRequest.java:499)
at org.glassfish.jersey.client.internal.HttpUrlConnector._apply(HttpUrlConnector.java:388)
at org.glassfish.jersey.client.internal.HttpUrlConnector.apply(HttpUrlConnector.java:285)
at org.glassfish.jersey.client.ClientRuntime.invoke(ClientRuntime.java:252)
... 39 more
Caused by: javax.validation.ConstraintViolationException
at org.eclipse.persistence.jaxb.JAXBBeanValidator.buildConstraintViolationException(JAXBBeanValidator.java:383)
... 52 more
This is a client side problem. As you've discovered MOXy has bean validation on by default. So you are getting bean validation on the client. So the request is not even going through as the error is happening on the client. You could test this by just sending a string
Entity.json("{}")
That should get rid of the error. But if you want to use the bean, as you mentioned in the comment, you should disable the bean validation on the client with MOXy
#Override
protected void configureClient(final ClientConfig config) {
super.configureClient(config);
config.register(new MoxyJsonConfig()
.property(MarshallerProperties.BEAN_VALIDATION_MODE,
BeanValidationMode.NONE).resolver());
}
I am using gwt dispatch to communicate and get data from server to client.
In order to get user specific data I want to store the user object in httpsession and access application specific data from servlet context
but when I inject Provider<HttpSession> when the handler execute is called but the dispatchservlet the provider is null i.e it does not get injected.
following is the code from my action handler
#Inject
Provider<HttpSession> provider;
public ReadEntityHandler() {
}
#Override
public EntityResult execute(ReadEntityAction arg0, ExecutionContext arg1) throws DispatchException {
HttpSession session = null;
if (provider == null)
System.out.println("httpSession is null..");
else {
session = provider.get();
System.out.println("httpSession not null..");
}
System.out.println("reached execution");
return null;
}
and my Dispatch servlet
#Singleton
public class ActionDispatchServlet extends RemoteServiceServlet implements StandardDispatchService {
private Dispatch dispatch;
private Dispatch dispatch;
#Inject ReadEntityHandler readEntityHandler;
public ActionDispatchServlet() {
InstanceActionHandlerRegistry registry = new DefaultActionHandlerRegistry();
registry.addHandler(readEntityHandler);
dispatch = new SimpleDispatch(registry);
}
#Override
public Result execute(Action<?> action) throws DispatchException {
try {
return dispatch.execute(action);
}
catch (RuntimeException e) {
log("Exception while executing " + action.getClass().getName() + ": " + e.getMessage(), e);
throw e;
}
}
}
when I try to inject the ReadEntityHandler it throws the following exception
[WARN] failed guiceFilter
com.google.inject.ProvisionException: Guice provision errors:
1) Error injecting constructor, java.lang.NullPointerException
at com.ensarm.wikirealty.server.service.ActionDispatchServlet.<init>(ActionDispatchServlet.java:22)
at com.ensarm.wikirealty.server.service.ActionDispatchServlet.class(ActionDispatchServlet.java:22)
while locating com.ensarm.wikirealty.server.service.ActionDispatchServlet
1 error
at com.google.inject.internal.InjectorImpl$4.get(InjectorImpl.java:834)
at com.google.inject.internal.InjectorImpl.getInstance(InjectorImpl.java:856)
at com.google.inject.servlet.ServletDefinition.init(ServletDefinition.java:74)
at com.google.inject.servlet.ManagedServletPipeline.init(ManagedServletPipeline.java:84)
at com.google.inject.servlet.ManagedFilterPipeline.initPipeline(ManagedFilterPipeline.java:106)
at com.google.inject.servlet.GuiceFilter.init(GuiceFilter.java:168)
at org.mortbay.jetty.servlet.FilterHolder.doStart(FilterHolder.java:97)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:39)
at org.mortbay.jetty.servlet.ServletHandler.initialize(ServletHandler.java:593)
at org.mortbay.jetty.servlet.Context.startContext(Context.java:140)
at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1220)
at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:513)
at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:448)
at com.google.gwt.dev.shell.jetty.JettyLauncher$WebAppContextWithReload.doStart(JettyLauncher.java:468)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:39)
at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130)
at org.mortbay.jetty.handler.RequestLogHandler.doStart(RequestLogHandler.java:115)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:39)
at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130)
at org.mortbay.jetty.Server.doStart(Server.java:222)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:39)
at com.google.gwt.dev.shell.jetty.JettyLauncher.start(JettyLauncher.java:672)
at com.google.gwt.dev.DevMode.doStartUpServer(DevMode.java:509)
at com.google.gwt.dev.DevModeBase.startUp(DevModeBase.java:1068)
at com.google.gwt.dev.DevModeBase.run(DevModeBase.java:811)
at com.google.gwt.dev.DevMode.main(DevMode.java:311)
Caused by: java.lang.NullPointerException
at net.customware.gwt.dispatch.server.DefaultActionHandlerRegistry.addHandler(DefaultActionHandlerRegistry.java:21)
at com.ensarm.wikirealty.server.service.ActionDispatchServlet.<init>(ActionDispatchServlet.java:24)
at com.ensarm.wikirealty.server.service.ActionDispatchServlet$$FastClassByGuice$$e0a28a5d.newInstance(<generated>)
at com.google.inject.internal.cglib.reflect.FastConstructor.newInstance(FastConstructor.java:40)
at com.google.inject.internal.DefaultConstructionProxyFactory$1.newInstance(DefaultConstructionProxyFactory.java:58)
at com.google.inject.internal.ConstructorInjector.construct(ConstructorInjector.java:84)
at com.google.inject.internal.ConstructorBindingImpl$Factory.get(ConstructorBindingImpl.java:200)
at com.google.inject.internal.ProviderToInternalFactoryAdapter$1.call(ProviderToInternalFactoryAdapter.java:43)
at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:878)
at com.google.inject.internal.ProviderToInternalFactoryAdapter.get(ProviderToInternalFactoryAdapter.java:40)
at com.google.inject.Scopes$1$1.get(Scopes.java:64)
at com.google.inject.internal.InternalFactoryToProviderAdapter.get(InternalFactoryToProviderAdapter.java:40)
at com.google.inject.internal.InjectorImpl$4$1.call(InjectorImpl.java:825)
at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:871)
at com.google.inject.internal.InjectorImpl$4.get(InjectorImpl.java:821)
... 25 more
You create instance of ReadEntityHandler registry.addHandler(new ReadEntityHandler()); himself not by container.Provider<HttpSession> provider; is null
Try:
#Inject
public ActionDispatchServlet(ReadEntityHandler handler) {
InstanceActionHandlerRegistry registry = new DefaultActionHandlerRegistry();
registry.addHandler(handler);
dispatch = new SimpleDispatch(registry);
}
Caused by: java.lang.NullPointerException
at net.customware.gwt.dispatch.server.DefaultActionHandlerRegistry.addHandler(DefaultActionHandlerRegistry.java:21)
Is it possible that DefaultActionHandlerRegistry has a bug in it at line 21, and that the error is happening there? I don't see the code for that class, so it isn't clear if this is the cause of your issue, or just a symptom.