I am trying to build a CXF RESTFul service with JSON as input and output. I am using JAXRSServerFactoryBean to boot my service. When I try to hit the URL from a client program, I am getting the following exception. My program is very simple and attached the same at the bottom.
Please help.
May 19, 2015 11:03:30 PM org.apache.cxf.jaxrs.provider.AbstractJAXBProvider handleExceptionStart
WARNING: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[0,0]
Message: A JSONObject text must begin with '{' at character 0 of
at org.codehaus.jettison.mapped.MappedXMLInputFactory.createXMLStreamReader(MappedXMLInputFactory.java:51)
at org.codehaus.jettison.AbstractXMLInputFactory.createXMLStreamReader(AbstractXMLInputFactory.java:116)
at org.apache.cxf.jaxrs.provider.json.utils.JSONUtils.createStreamReader(JSONUtils.java:162)
at org.apache.cxf.jaxrs.provider.json.JSONProvider.createReader(JSONProvider.java:290)
at org.apache.cxf.jaxrs.provider.json.JSONProvider.createReader(JSONProvider.java:280)
at org.apache.cxf.jaxrs.provider.json.JSONProvider.readFrom(JSONProvider.java:233)
at org.apache.cxf.jaxrs.utils.JAXRSUtils.readFromMessageBodyReader(JAXRSUtils.java:1337)
at org.apache.cxf.jaxrs.utils.JAXRSUtils.readFromMessageBody(JAXRSUtils.java:1288)
at org.apache.cxf.jaxrs.utils.JAXRSUtils.processParameter(JAXRSUtils.java:824)
at org.apache.cxf.jaxrs.utils.JAXRSUtils.processParameters(JAXRSUtils.java:787)
at org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor.processRequest(JAXRSInInterceptor.java:212)
at org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor.handleMessage(JAXRSInInterceptor.java:77)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:307)
May 19, 2015 11:03:30 PM org.apache.cxf.jaxrs.impl.WebApplicationExceptionMapper toResponse
WARNING: javax.ws.rs.BadRequestException: HTTP 400 Bad Request
at org.apache.cxf.jaxrs.utils.SpecExceptions.toBadRequestException(SpecExceptions.java:84)
at org.apache.cxf.jaxrs.utils.ExceptionUtils.toBadRequestException(ExceptionUtils.java:114)
at org.apache.cxf.jaxrs.provider.AbstractJAXBProvider.handleExceptionEnd(AbstractJAXBProvider.java:705)
at org.apache.cxf.jaxrs.provider.AbstractJAXBProvider.handleXMLStreamException(AbstractJAXBProvider.java:734)
at org.apache.cxf.jaxrs.provider.json.JSONProvider.readFrom(JSONProvider.java:261)
at org.apache.cxf.jaxrs.utils.JAXRSUtils.readFromMessageBodyReader(JAXRSUtils.java:1337)
at org.apache.cxf.jaxrs.utils.JAXRSUtils.readFromMessageBody(JAXRSUtils.java:1288)
at org.apache.cxf.jaxrs.utils.JAXRSUtils.processParameter(JAXRSUtils.java:824)
at org.apache.cxf.jaxrs.utils.JAXRSUtils.processParameters(JAXRSUtils.java:787)
at org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor.processRequest(JAXRSInInterceptor.java:212)
at org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor.handleMessage(JAXRSInInterceptor.java:77)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:307)
at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:251)
at org.apache.cxf.transport.http_jetty.JettyHTTPDestination.doService(JettyHTTPDestination.java:234)
at org.apache.cxf.transport.http_jetty.JettyHTTPHandler.handle(JettyHTTPHandler.java:70)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1129)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1065)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:215)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
Caused by: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[0,0]
Message: A JSONObject text must begin with '{' at character 0 of
at org.codehaus.jettison.mapped.MappedXMLInputFactory.createXMLStreamReader(MappedXMLInputFactory.java:51)
at org.codehaus.jettison.AbstractXMLInputFactory.createXMLStreamReader(AbstractXMLInputFactory.java:116)
at org.apache.cxf.jaxrs.provider.json.utils.JSONUtils.createStreamReader(JSONUtils.java:162)
at org.apache.cxf.jaxrs.provider.json.JSONProvider.createReader(JSONProvider.java:290)
RestFulServiceStarter
public class RestFulServiceStarter {
public static void main(String[] args) {
JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean();
sf.setResourceClasses(ProfileService.class);
sf.setResourceProvider(ProfileService.class,
new SingletonResourceProvider(new ProfileServiceImpl()));
sf.setAddress("http://localhost:9999/");
Server server = sf.create();
}
}
ProfileService
#Path("/profile/")
public interface ProfileService {
#GET
#Path("/static/")
#Consumes({ MediaType.APPLICATION_JSON })
#Produces({ MediaType.APPLICATION_JSON })
public Response getStaticProfiles(ProfileRequest pr);
}
ProfileServiceImpl
public class ProfileServiceImpl implements ProfileService {
public Response getStaticProfiles(ProfileRequest pr) {
return Response.status(200).entity(pr).build();
}
}
ProfileRequest
#XmlRootElement ( name = "profile" )
public class ProfileRequest {
private String name="";
private String country="";
private String region="";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
}
Your interface method is annotated with a #GET method, yet it also has an entity parameter (ProfileRequest). Try #POST.
Related
This the NullPointerExceptionMapper class
package com.sample.Exceptionhandler;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import response.Message;
#Provider
public class NullPointerExceptionMapper implements ExceptionMapper<NullPointerException> {
public Response toResponse(NullPointerException ex) {
Message message=new Message(500,ex.getMessage(),200);
return Response.status(Status.NOT_FOUND).entity(message)
.build();
}
}
This is the Message class
package response;
public class Message {
private int status;
private String message;
private int code;
public Message() {
}
public Message(int status, String message, int code) {
super();
this.status = status;
this.message = message;
this.code = code;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
This is the Controller method
#RequestMapping(value = "/getOrder", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public List<PurchaseOrderHeaderDto> getOrders(){
String exceptionOccured="NULL_POINTER";
if(exceptionOccured.equalsIgnoreCase("NULL_POINTER")){
throw new NullPointerException("Null Pointer Exception");
}
return purchaseImpl.GetPurchaseOrder();
}
I am not able to handle the Exception thrown and I am using JAX-RS for handling it, but it is not working properly any suggestions are welcomed that would help me sort this out.
You're mixing JAX-RS with Spring MVC. Your controller code is Spring MVC and your attempt at exception handling with the ExceptionMapper is JAX-RS. These are two completely different and incompatible frameworks. For Spring MVC, you want to use a #ControllerAdvice class.
I try to get a Json object from Itis Webservice (https://www.itis.gov/ITISWebService/jsonservice/getHierarchyUpFromTSN?tsn=164282).
I use the following class to store the Json object:
public class Genus {
#JsonProperty("tsn")
private int tsn;
#JsonProperty("taxonName")
private String taxonName;
public Genus() {
super();
}
public int getTsn() {
return tsn;
}
public void setTsn(int tsn) {
this.tsn = tsn;
}
public String getCombinedName() {
return taxonName;
}
public void setCombinedName(String taxonName) {
this.taxonName = taxonName;
}
#Override
public String toString() {
return "Genus [tsn=" + tsn + ", taxonName=" + taxonName + "]";
}
}
My main method:
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
Genus quote = restTemplate.getForObject("https://www.itis.gov/ITISWebService/jsonservice/getHierarchyUpFromTSN?tsn=164282", Genus.class);
System.out.println(quote.toString());
}
As result I get the following exception:
Exception in thread "main"
org.springframework.web.client.RestClientException: Could not extract
response: no suitable HttpMessageConverter found for response type
[class de.aquaristikguru.taxonomy.itisObjects.Genus] and content type
[text/json;charset=ISO-8859-1
How can I fixed it?
I am trying to use mirah for JSON to POJO mapping in an codenameone application. It works finde when i want to map a Simple JSON like
{"id":"1","name":"foo","classification":"10"}
With this class:
public class Brand {
private String id;
private String name;
private String classification;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClassification() {
return classification;
}
public void setClassification(String classification) {
this.classification = classification;
}
}
Now I want to wrap it in a Message Object, where i have a list of brands:
import java.util.List;
public class Message {
public List<Brand> brands;
public List<Brand> getBrands() {
return brands;
}
public void setBrands(List<Brand> brands) {
this.brands = brands;
}
}
I use this Mirah Script for mapping:
data_mapper Message:MessageMapper
data_mapper Brand:BrandMapper
like shannah described here.
My code where I call my Webservice:
MessageMapper scheduleMapper = new MessageMapper();
DataMapper.createContext(Arrays.asList(
scheduleMapper,
new BrandMapper()
), new DataMapper.Decorator() {
public void decorate(DataMapper mapper) {
mapper.setReadKeyConversions(Arrays.asList(DataMapper.CONVERSION_NONE));
}
});
try {
Message message = scheduleMapper.readJSONFromURL("http://localhost/php-REST-DigitaleMusterplatte/api.php/brands", Message.class);
System.out.println(message);
} catch (IOException ex) {
Log.e(ex);
}
This is the json response:
{"brands":[{"id":"1","name":"foo","classification":"10"},{"id":"2","name":"bar","classification":"20"}]}
I get this exception:
java.lang.RuntimeException: Failed to get key brands for class interface java.util.List because it was not a registered object type
at ca.weblite.codename1.mapper.DataMapper.get(DataMapper.java:507)
at com.mycompany.app.dmp.models.MessageMapper.readMap(/Volumes/Windows VMS/Documents/Shared/NetBeansProjects/mirah_macro_utils/MirahMacroUtils/src/ca/weblite/mirah/utils/DataMapperBuilder.mirah)
at ca.weblite.codename1.mapper.DataMapper.readMap(DataMapper.java:719)
at ca.weblite.codename1.mapper.DataMapper.readJSON(DataMapper.java:780)
at ca.weblite.codename1.mapper.DataMapper.readJSON(DataMapper.java:792)
at ca.weblite.codename1.mapper.DataMapper.readJSONFromConnection(DataMapper.java:767)
at ca.weblite.codename1.mapper.DataMapper.readJSONFromURL(DataMapper.java:754)
at com.mycompany.myapp.MyApplication.start(MyApplication.java:96)
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.codename1.impl.javase.Executor$1$1.run(Executor.java:123)
at com.codename1.ui.Display.processSerialCalls(Display.java:1152)
at com.codename1.ui.Display.mainEDTLoop(Display.java:969)
at com.codename1.ui.RunnableWrapper.run(RunnableWrapper.java:120)
at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)
The demo application OSCONScheduler works fine.
This looks like a bug. But try changing brands to be private instead of public. It could be getting confused over whether to use your accessor/mutable or to use the public var.
Am writing a Restful Webservice Impl, where i consume and produce response in JSON format by annotating #Produces("application/json"). Am producing JSON response as well. Here am handling exception with a class where it has error code and error message. When am getting exception it is not produced in application/json format. I used ExceptionMapper to find a solution but it is `text/plain format.
snippet
public Class Confiuration{
#Path("getData")
#Consumes("application/json")
#Produces("application/json")
public JSONGetDataResponseVo getData(GetDataRequestVo datarequestVO)
throws FaultResponse {
JSONGetDataResponseVo response=new JSONGetDataResponseVo ();
DataServiceValidator.validateGetConfigurationAndDataRequest(datarequestVO);
....
....
}catch(ApplicationException applicationException){
throw new FaultResponse(applicationException,locale);
}
}
FaultResponseMapper
#Provider
public class FaultResponseMapper implements ExceptionMapper<FaultResponse> {
#Context
private HttpHeaders headers;
public Response toResponse(FaultResponse faultResponse) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(faultResponse).type(MediaType.APPLICATION_JSON).build();
}
}
Application Exception
public abstract class ApplicationException extends Exception{
private java.lang.String errorCode;
public ApplicationException(String errorCode, String message) {
super(message);
this.errorCode = errorCode;
}
public ApplicationException(String message) {
super(message);
}
public java.lang.String getErrorCode() {
return this.errorCode;
}
public abstract String getLocaleMessage(Locale locale);
}
FaultResponse
public class FaultResponse extends WebApplicationException {
private String errorCode;
private String errorMessage;
private String localErrorMessage;
public FaultResponse(String errorCode, String errorMessage,
String localErrorMessage) {
this.errorCode = errorCode;
this.errorMessage = errorMessage;
this.localErrorMessage = localErrorMessage;
}
public FaultResponse(ApplicationException applicationException,
Locale locale) {
this.errorCode = applicationException.getErrorCode();
this.errorMessage = applicationException.getMessage();
if (locale != null
&& applicationException.getLocaleMessage(locale) != null) {
this.localErrorMessage = applicationException
.getLocaleMessage(locale);
} else {
this.localErrorMessage = applicationException.getMessage();
}
}
}
So here how can i produce my faultResponse in JSON format.
This has to do with the fact that you are returning an exception as a response. I would
Make an exception mapper for ApplicationException.
Refactor FaultResponse to not extend and exception. Just create it in the mapper.
In order to see the response, you will need to send a status other than No Content. You can't have a body in it. Send somethng like Bad Request.
You can just declare the resource method as throws ApplicationException. You don't need to catch it and rethrow.
I've made these changes, and it works fine.
UPDATE: with complete test
Added getters (required for marshalling) to FaultResponse and remove the exception extension
public class FaultResponse {
...
public String getErrorCode() { return errorCode; }
public String getErrorMessage() { return errorMessage; }
public String getLocalErrorMessage() { return localErrorMessage; }
...
}
Created a Service for testing and ApplicationException implementation
public class ApplicationExceptionImpl extends ApplicationException {
public ApplicationExceptionImpl(){
this("400", "Bad Request");
}
public ApplicationExceptionImpl(String errorCode, String message) {
super(errorCode, message);
}
#Override
public String getLocaleMessage(Locale locale) {
return "Bad Request";
}
}
public class FaultService {
public void doSomething() throws ApplicationException {
throw new ApplicationExceptionImpl();
}
}
Resource class
#Path("fault")
public class FaultResource {
FaultService service = new FaultService();
#GET
public Response getException() throws ApplicationException {
service.doSomething();
return Response.ok("Cool").build();
}
}
ExceptionMapper
#Provider
public class ApplicationExceptionMapper implements ExceptionMapper<ApplicationException> {
#Override
public Response toResponse(ApplicationException exception) {
FaultResponse response = new FaultResponse(exception, Locale.ENGLISH);
return Response.status(Response.Status.BAD_REQUEST)
.entity(response).type(MediaType.APPLICATION_JSON).build();
}
}
ApplicationException class is left the same
curl -v http://localhost:8080/api/fault
{"errorCode":"400","errorMessage":"Bad Request","localErrorMessage":"Bad Request"}
If after this you are still not seeing JSON, it's possible you do not have a provider configured. If this is the case, please show your application configuration, along with your project dependencies.
I am using Jersey to parse the following JSON:
{"response":{"status":"OK","campaigns":[{"id":12345,"state":"active","code":null}]}}
But I get the following error message:
java.lang.IllegalArgumentException: No more parsing elements.
If I switch the position of the fields code and state so that the resulting JSON looks like
{"response":{"status":"OK","campaigns":[{"id":12345,"code":null,"state":"active"}]}}
everything works fine. Also if I change the code-field in the first JSON to a non-null value like "code":"test", Jersey can parse this without any problems. I tried other more complex examples always getting the above mentioned error message when leaving the last field of any element of an array null.
I think I am doing something wrong, because I could not find any others having the similar problem. I already tried to implement a CustomJAXBContextResolver using other JSON notations like natural but nothing worked for me.
Any ideas?
Here are my binding classes:
#XmlRootElement
public class LoadEntityResponse {
public LoadEntityResponse() {
}
private Response response;
public Response getResponse() {
return response;
}
public void setResponse(Response response) {
this.response = response;
}
}
and
public class Response {
public Response() {
}
private String status;
private String error;
private String error_id;
private Campaign[] campaigns;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public String getError_id() {
return error_id;
}
public void setError_id(String error_id) {
this.error_id = error_id;
}
public Campaign[] getCampaigns() {
return campaigns;
}
public void setCampaigns(Campaign[] campaigns) {
this.campaigns = campaigns;
}
}
and finally
public class Campaign{
public Campaign() {
}
protected int id;
protected String code;
protected String state;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
Solved: Using JacksonJsonProvider now:
...
DefaultClientConfig config = new DefaultClientConfig();
config.getClasses().add(JacksonJsonProvider.class);
...
that´s all!
You can also use Jackson POJO support that comes with jersey-json but there is a need to do some configuration, see POJO support in Jersey User Guide.
Try using Genson http://code.google.com/p/genson/.
To enable it on client side use the following code:
ClientConfig config = new DefaultClientConfig();
config.getClasses().add(GensonJsonConverter.class);
cli = Client.create(config);
EDIT: on server side there is no configuration needed, when the jar is in your classpath json support is automatically enabled.