JAX-RS client returns entity of null - resteasy

I have a JAX-RS service defined like this:
#Produces(MediaType.APPLICATION_JSON)
#GET
#Path("/namestartswith")
public List<ProductBrand> nameStartsWith(#QueryParam("name") String name) {
List<ProductBrand> productBrandList = productBrandService.findByNameStartsWith(name);
System.out.println("productBrandList: " + productBrandList);
return productBrandList;
}
Issuing the following URL:
http://localhost:19191/productbrand/namestartswith?name=f
produces:
{"productBrand":[{"brandImage":"ffbrand.png","description":"the brand called ff","id":"1","name":"ffbrand"},{"brandImage":"flfl.png","description":"flfl","id":"6","name":"flfl"},{"brandImage":"ffbran.png","description":"ffbr","id":"16","name":"ffbran"}]}
which means the service is working as intended.
Now I use RestEasy for client access.
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-client</artifactId>
<version>${resteasy.version}</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson-provider</artifactId>
<version>${resteasy.version}</version>
</dependency>
The following code accesses the service:
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:19191/productbrand/namestartswith?name=" + name);
Response restEasyResponse = target.request(MediaType.APPLICATION_JSON).get();
log("entity: " + restEasyResponse.readEntity(new GenericType<List<ProductBrand>>() {
}););
The output is:
entity: null
Even calling restEasyResponse.getEntity() returns null. What might be wrong?

I had a similar issue and I work around it using:
restEasyResponse.readEntity(List.class)
It will return a List<Map<String, Object>> where each item represents an element of the json array.

Related

Read a csv file in Flink 1.15 using Table API

I'm doing a simple tutorial with flink + java using Table API. What I want to do is really simple - I want to read a csv file from a local filesystem, using a schema and print it out.
The way I'm doing this is this(the code below is compiled from samples from Flink's website tutorial section):
package p1;
import org.apache.flink.table.api.*;
import org.apache.flink.api.java.utils.ParameterTool;
public class CabAggregation {
public static void main(String[] args) throws Exception {
ParameterTool params = ParameterTool.fromArgs(args);
EnvironmentSettings settings = EnvironmentSettings
.newInstance()
.inBatchMode()
.build();
TableEnvironment tableEnv = TableEnvironment.create(settings);
final Schema schema = Schema.newBuilder()
.column("cab_id", DataTypes.INT())
.column("cab_plate", DataTypes.STRING())
.column("cab_make", DataTypes.STRING())
.column("cab_driver", DataTypes.STRING())
.column("active_trip", DataTypes.STRING())
.column("pickup_location", DataTypes.STRING())
.column("target_location", DataTypes.STRING())
.column("num_pass", DataTypes.INT())
.build();
tableEnv.createTemporaryTable("cabs",
TableDescriptor
.forConnector("filesystem")
.schema(schema)
.option("path", "file:///Users/virtual/Downloads/cabs.csv")
.format(FormatDescriptor.forFormat("csv").build())
.build());
Table result = tableEnv.from("cabs").select("*");
result.execute().print();
}
}
Running this gives me this:
Caused by: org.apache.flink.table.api.ValidationException: Could not find any factory for identifier 'filesystem' that implements 'org.apache.flink.table.factories.DynamicTableFactory' in the classpath.
Available factory identifiers are:
blackhole
datagen
print
Now, it seems evident that somehow CSV is not available as a factory identifier. I can't figure out why.
I'm building the project with maven.
You'll be needing these dependencies. Have you added them?
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-connector-files</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-csv</artifactId>
<version>${flink.version}</version>
</dependency>

java.lang.NoClassDefFoundError: feign/Request$Body in feign while adding support for multipart/form-data

I am trying to proxy multipart request via feign.
#PostMapping(value = "{pathUri1}/{pathUri2}",consumes = MediaType.MULTIPART_FORM_DATA_VALUE,produces = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<BaseResponse<?>> uploadFileCall(#PathVariable(value = "pathUri1") String pathUri1, #PathVariable(value = "pathUri2") String pathUri2, #RequestPart(name = "file") MultipartFile file, #RequestParam Map<Object,Object> requestParam, #RequestHeader HttpHeaders httpHeaders);
this is service call.
#Configuration
class MultipartSupportConfig {
#Autowired
ObjectFactory<HttpMessageConverters> messageConverters;
#Bean
#Primary
#Scope("prototype")
public Encoder feignFormEncoder() {
return new SpringFormEncoder(new SpringEncoder(messageConverters));
}
}
added encoder config for multipart/form-data .
I have followed this
https://github.com/OpenFeign/feign-form
But I am getting hystrixRunTimeException which is caused because of
java.lang.NoClassDefFoundError: feign/Request$Body error.
Use feign-form-spring 3.4.1 version.
Gradle
compile(group: 'io.github.openfeign.form', name: 'feign-form-spring', version: '3.4.1')
Maven
<dependency>
<groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form</artifactId>
<version>3.4.1</version>
</dependency>
Check requirements https://github.com/OpenFeign/feign-form#requirements
According to the open-feign's github document, Please Note the feign-form's versions:
all feign-form releases before 3.5.0 works with OpenFeign 9.* versions;
starting from feign-form's version 3.5.0, the module works with OpenFeign 10.1.0 versions and greater.
The following config works for me:
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-jackson</artifactId>
<version>${feign.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
<version>${feign.version}</version>
</dependency>
Where:
<feign.version>11.0</feign.version>
<spring-cloud.version>Hoxton.SR3</spring-cloud.version>

GcsServiceFactory.createGcsService leads to 500 server error

I am working on an app which uses GAE and GCS serverside. Among other things I can upload pictures and store their publicUrl in a google mysql database. Today I tried to use .secureUrl(true) when getting those publicUrls and since then I get a 500 server error when sending post requests.
I can break it down to the following code snippet:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException,
ServletException {
// create Writer for response
PrintWriter out = response.getWriter();
response.setContentType("application/json");
// create Database Connection url with name database, username and password
String mysqlUrl = System.getProperty("cloudsql");
// get 'operation' parameter to determine further action
String operation = request.getParameter("operation");
if (operation == null){ operation = "getFav"; }
GcsService gcsService = GcsServiceFactory.createGcsService();
When I dont comment out the last line where gcsService is set, every post request sent from my phone is answered with a 500 server error. If I make the line a comment, everything (except for the parts where gcs is used) works perfectly. Checking out the Google console, I get the following message:
java.lang.NoClassDefFoundError: com/google/appengine/api/utils/SystemProperty
at com.google.appengine.tools.cloudstorage.GcsServiceFactory.createRawGcsService (GcsServiceFactory.java:57)
at com.google.appengine.tools.cloudstorage.GcsServiceFactory.createGcsService (GcsServiceFactory.java:44)
at com.google.appengine.tools.cloudstorage.GcsServiceFactory.createGcsService (GcsServiceFactory.java:40)
at net.xyz.yzxI.HelloAppEngine.<init> (HelloAppEngine.java:69)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0 (Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance (NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance (DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance (Constructor.java:423)
at java.lang.Class.newInstance (Class.java:443)
at org.eclipse.jetty.server.handler.ContextHandler$Context.createInstance (ContextHandler.java:2481)
at org.eclipse.jetty.servlet.ServletContextHandler$Context.createServlet (ServletContextHandler.java:1327)
at org.eclipse.jetty.servlet.ServletHolder.newInstance (ServletHolder.java:1285)
at org.eclipse.jetty.servlet.ServletHolder.initServlet (ServletHolder.java:615)
at org.eclipse.jetty.servlet.ServletHolder.getServlet (ServletHolder.java:499)
at org.eclipse.jetty.servlet.ServletHolder.ensureInstance (ServletHolder.java:791)
at org.eclipse.jetty.servlet.ServletHolder.prepare (ServletHolder.java:776)
at org.eclipse.jetty.servlet.ServletHandler.doHandle (ServletHandler.java:579)
at org.eclipse.jetty.server.handler.ScopedHandler.handle (ScopedHandler.java:143)
at org.eclipse.jetty.security.SecurityHandler.handle (SecurityHandler.java:524)
at org.eclipse.jetty.server.session.SessionHandler.doHandle (SessionHandler.java:226)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle (ContextHandler.java:1180)
at org.eclipse.jetty.servlet.ServletHandler.doScope (ServletHandler.java:512)
at org.eclipse.jetty.server.session.SessionHandler.doScope (SessionHandler.java:185)
at org.eclipse.jetty.server.handler.ContextHandler.doScope (ContextHandler.java:1112)
at org.eclipse.jetty.server.handler.ScopedHandler.handle (ScopedHandler.java:141)
at com.google.apphosting.runtime.jetty9.AppVersionHandlerMap.handle (AppVersionHandlerMap.java:297)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle (HandlerWrapper.java:134)
at org.eclipse.jetty.server.Server.handle (Server.java:534)
at org.eclipse.jetty.server.HttpChannel.handle (HttpChannel.java:320)
at com.google.apphosting.runtime.jetty9.RpcConnection.handle (RpcConnection.java:202)
at com.google.apphosting.runtime.jetty9.RpcConnector.serviceRequest (RpcConnector.java:81)
at com.google.apphosting.runtime.jetty9.JettyServletEngineAdapter.serviceRequest (JettyServletEngineAdapter.java:108)
at com.google.apphosting.runtime.JavaRuntime$RequestRunnable.dispatchServletRequest (JavaRuntime.java:680)
at com.google.apphosting.runtime.JavaRuntime$RequestRunnable.dispatchRequest (JavaRuntime.java:642)
at com.google.apphosting.runtime.JavaRuntime$RequestRunnable.run (JavaRuntime.java:612)
at com.google.apphosting.runtime.JavaRuntime$NullSandboxRequestRunnable.run (JavaRuntime.java:806)
at com.google.apphosting.runtime.ThreadGroupPool$PoolEntry.run (ThreadGroupPool.java:274)
at java.lang.Thread.run (Thread.java:745)
It drives me crazy: Even if I dont use the gcs at all, just trying to set it up breaks the app. I have like no clue where to look at, so hopefully someone else has had similar experiences or knows what to check.
Thanks in advance
If you are using Maven to handle dependencies this error may be due to a "provided" in the com.google.appengine dependency. Remove that line in pom.xml so Maven will include app engine sdk in the compiled project.
Before:
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-api-1.0-sdk</artifactId>
<version>1.9.63</version>
<scope>provided</scope>
</dependency>
After:
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-api-1.0-sdk</artifactId>
<version>1.9.63</version>
</dependency>

Spring + AngularJS - the server responded with a status of 406 (Not Acceptable) [duplicate]

this is my javascript:
function getWeather() {
$.getJSON('getTemperature/' + $('.data option:selected').val(), null, function(data) {
alert('Success');
});
}
this is my controller:
#RequestMapping(value="/getTemperature/{id}", headers="Accept=*/*", method = RequestMethod.GET)
#ResponseBody
public Weather getTemparature(#PathVariable("id") Integer id){
Weather weather = weatherService.getCurrentWeather(id);
return weather;
}
spring-servlet.xml
<context:annotation-config />
<tx:annotation-driven />
Getting this error:
GET http://localhost:8080/web/getTemperature/2 406 (Not Acceptable)
Headers:
Response Headers
Server Apache-Coyote/1.1
Content-Type text/html;charset=utf-8
Content-Length 1070
Date Sun, 18 Sep 2011 17:00:35 GMT
Request Headers
Host localhost:8080
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0.2) Gecko/20100101 Firefox/6.0.2
Accept application/json, text/javascript, */*; q=0.01
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip, deflate
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Connection keep-alive
X-Requested-With XMLHttpRequest
Referer http://localhost:8080/web/weather
Cookie JSESSIONID=7D27FAC18050ED84B58DAFB0A51CB7E4
Interesting note:
I get 406 error, but the hibernate query works meanwhile.
This is what tomcat log says, everytime when I change selection in dropbox:
select weather0_.ID as ID0_0_, weather0_.CITY_ID as CITY2_0_0_, weather0_.DATE as DATE0_0_, weather0_.TEMP as TEMP0_0_ from WEATHER weather0_ where weather0_.ID=?
What could the problem be? There were two similar questions in SO before, I tried all the accepted hints there, but they did not work I guess...
Any suggestions? Feel free to ask questions...
406 Not Acceptable
The resource identified by the request is only capable of generating response entities which have content characteristics not acceptable according to the accept headers sent in the request.
So, your request accept header is application/json and your controller is not able to return that. This happens when the correct HTTPMessageConverter can not be found to satisfy the #ResponseBody annotated return value. HTTPMessageConverter are automatically registered when you use the <mvc:annotation-driven>, given certain 3-d party libraries in the classpath.
Either you don't have the correct Jackson library in your classpath, or you haven't used the
<mvc:annotation-driven> directive.
I successfully replicated your scenario and it worked fine using these two libraries and no headers="Accept=*/*" directive.
jackson-core-asl-1.7.4.jar
jackson-mapper-asl-1.7.4.jar
I had same issue, with Latest Spring 4.1.1 onwards you need to add following jars to pom.xml.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.4.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.1.1</version>
</dependency>
also make sure you have following jar:
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
406 Spring MVC Json, not acceptable according to the request "accept" headers
There is another case where this status will be returned: if the Jackson mapper cannot figure out how to serialize your bean. For example, if you have two accessor methods for the same boolean property, isFoo() and getFoo().
What's happening is that Spring's MappingJackson2HttpMessageConverter calls Jackson's StdSerializerProvider to see if it can convert your object. At the bottom of the call chain, StdSerializerProvider._createAndCacheUntypedSerializer throws a JsonMappingException with an informative message. However, this exception is swallowed by StdSerializerProvider._createAndCacheUntypedSerializer, which tells Spring that it can't convert the object. Having run out of converters, Spring reports that it's not being given an Accept header that it can use, which of course is bogus when you're giving it */*.
There is a bug for this behavior, but it was closed as "cannot reproduce": the method that's being called doesn't declare that it can throw, so swallowing exceptions is apparently an appropriate solution (yes, that was sarcasm). Unfortunately, Jackson doesn't have any logging ... and there are a lot of comments in the codebase wishing it did, so I suspect this isn't the only hidden gotcha.
I had the same problem, my controller method executes but response is Error 406.
I debug AbstractMessageConverterMethodProcessor#writeWithMessageConverters and found that method ContentNegotiationManager#resolveMediaTypes always returns text/html which is not supported by MappingJacksonHttpMessageConverter. The problem is that the org.springframework.web.accept.ServletPathExtensionContentNegotiationStrategy works earlier than org.springframework.web.accept.HeaderContentNegotiationStrategy, and extension of my request /get-clients.html is the cause of my problem with Error 406. I just changed request url to /get-clients.
Make sure that the sent object (Weather in this case) contains getter/setter
Make sure that following 2 jar's are present in class path.
If any one or both are missing then this error will come.
jackson-core-asl-1.9.X.jar jackson-mapper-asl-1.9.X.jar
Finally found answer from here:
Mapping restful ajax requests to spring
I quote:
#RequestBody/#ResponseBody annotations don't use normal view resolvers, they use their own HttpMessageConverters. In order to use these annotations, you should configure these converters in AnnotationMethodHandlerAdapter, as described in the reference (you probably need MappingJacksonHttpMessageConverter).
Check <mvc:annotation-driven /> in dispatcherservlet.xml , if not add it.
And add
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
these dependencies in your pom.xml
Probably no one is scrolling down this far, but none of the above solutions fixed it for me, but making all my getter methods public did.
I'd left my getter visibility at package-private; Jackson decided it couldn't find them and blew up. (Using #JsonAutoDetect(getterVisibility=NON_PRIVATE) only partially fixed it.
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-base</artifactId>
<version>2.6.3</version>
</dependency>
I was having the same problem because I was missing the #EnableWebMvc annotation. (All of my spring configurations are annotation-based, the XML equivalent would be mvc:annotation-driven)
In the controller, shouldn't the response body annotation be on the return type and not the method, like so :
#RequestMapping(value="/getTemperature/{id}", headers="Accept=*/*", method = RequestMethod.GET)
public #ResponseBody Weather getTemparature(#PathVariable("id") Integer id){
Weather weather = weatherService.getCurrentWeather(id);
return weather;
}
I'd also use the raw jquery.ajax function, and make sure contentType and dataType are being set correctly.
On a different note, I find the spring handling of json rather problematic. It was easier when I did it all myself using strings, and GSON.
As #atott mentioned.
If you have added the latest version of Jackson in your pom.xml, and with Spring 4.0 or newer, using #ResponseBody on your action method and #RequestMapping configured with produces="application/json;charset=utf-8", however, you still got 406(Not Acceptable), I guess you need to try this in your MVC DispatcherServlet context configuration:
<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager" />
<bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="favorPathExtension" value="false" />
</bean>
That's the way how I resolved my issue finally.
check this thread.
spring mvc restcontroller return json string
p/s: you should add jack son mapping config to your WebMvcConfig class
#Override
protected void configureMessageConverters(
List<HttpMessageConverter<?>> converters) {
// put the jackson converter to the front of the list so that application/json content-type strings will be treated as JSON
converters.add(new MappingJackson2HttpMessageConverter());
// and probably needs a string converter too for text/plain content-type strings to be properly handled
converters.add(new StringHttpMessageConverter());
}
Spring 4.3.10: I used the below settings to resolve the issue.
Step 1: Add the below dependencies
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.6.7</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.7</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
Step 2: Add the below in your MVC DispatcherServlet context configuration:
<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager"/>
<bean id="contentNegotiationManager"
class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="favorPathExtension" value="false"/>
<property name="favorParameter" value="true"/>
<property name="ignoreAcceptHeader" value="false" />
</bean>
Since spring 3.2, as per the default configuration favorPathExtension is set as true, because of this if the request uri have any proper extensions like .htm spring will give priority for the extension. In step 2 I had added the contentNegotiationManager bean to override this.
make sure your have correct jackson version in your classpath
Check as #joyfun did for the correct version of jackson but also check our headers ... Accept / may not be transmitted by the client ... use firebug or equivalent to check what your get request is actually sending. I think the headers attribute of the annotation /may/ be checking literals although I'm not 100% sure.
Other then the obvious problems I had another one that I couldn't fix regardless of including all possible JARs, dependancies and annotations in Spring servlet. Eventually I found that I have wrong file extension by that I mean I had two separate servlet running in same container and I needed to map to different file extensions where one was ".do" and the other as used for subscriptions was randomly named ".sub". All good but SUB is valid file extension normally used for films subtitle files and thus Tomcat was overriding the header and returning something like "text/x-dvd.sub..." so all was fine but the application was expecting JSON but getting Subtitles thus all I had to do is change the mapping in my web.xml file I've added:
<mime-mapping>
<extension>sub</extension>
<mime-type>application/json</mime-type>
</mime-mapping>
I had the same problem unfortunately non of the solution here solved my problem as my problem was something in a different class.
I first checked that all dependencies are in place as suggested by #bekur
then I checked the request/response that travels from clients to the server all headers was in place an properly set by Jquery.
I then checked the RequestMappingHandlerAdapter MessageConverters and all 7 of them were in place, I really started to hate Spring ! I then updated to from Spring 4.0.6.RELEASE to 4.2.0.RELEASE I have got another response rather than the above. It was Request processing failed; nested exception is java.lang.IllegalArgumentException: No converter found for return value of type
Here is my controller method
#RequestMapping(value = "/upload", method = RequestMethod.POST,produces = "application/json")
public ResponseEntity<UploadPictureResult> pictureUpload(FirewalledRequest initialRequest) {
DefaultMultipartHttpServletRequest request = (DefaultMultipartHttpServletRequest) initialRequest.getRequest();
try {
Iterator<String> iterator = request.getFileNames();
while (iterator.hasNext()) {
MultipartFile file = request.getFile(iterator.next());
session.save(toImage(file));
}
} catch (Exception e) {
return new ResponseEntity<UploadPictureResult>(new UploadPictureResult(),HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity<UploadPictureResult>(new UploadPictureResult(), HttpStatus.OK);
}
public class UploadPictureResult extends WebResponse{
private List<Image> images;
public void setImages(List<Image> images) {
this.images = images;
}
}
public class WebResponse implements Serializable {
protected String message;
public WebResponse() {
}
public WebResponse(String message) {
this.message = message;
}
public void setMessage(String message) {
this.message = message;
}
}
The solution was to make UploadPictureResult not to extend WebResponse
For some reason spring was not able to determine the how to convert UploadPictureReslt when it extended WebResponse
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.0</version>
</dependency>
i don't use ssl authentication and this jackson-databind contain jackson-core.jar and jackson-databind.jar, and then change the RequestMapping content like this:
#RequestMapping(value = "/id/{number}", produces = "application/json; charset=UTF-8", method = RequestMethod.GET)
public #ResponseBody Customer findCustomer(#PathVariable int number){
Customer result = customerService.findById(number);
return result;
}
attention:
if your produces is not "application/json" type and i had not noticed this and got an 406 error, help this can help you out.
This is update answer for springVersion=5.0.3.RELEASE.
Those above answers will be only worked older springVersion < 4.1 version. for latest spring you have to add following dependencies in gradle file:
compile group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: fasterxmljackson
compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: fasterxmljackson
fasterxmljackson=2.9.4
I hope this will be helpful for who using latest spring version.
Simple answer just add Getter method in your domain/model class.
But Why this works ??
Under the hood Spring used HttpMessageConverters to convert your input JSON to Java Object. The Accept header that is passed in the request is used to select appropriate MessageConvertor at runtime. These message convertors use getter of your domain/model class for conversion, so if there are no getter method, Marshall and unmarshall Java Objects to and from JSON will not happen, even if you add Jackson in your classpath, because even Jackson lib uses Getter methods for marshalling stuffs !!.
Can you remove the headers element in #RequestMapping and try..
Like
#RequestMapping(value="/getTemperature/{id}", method = RequestMethod.GET)
I guess spring does an 'contains check' rather than exact match for accept headers. But still, worth a try to remove the headers element and check.

415 (Unsupported Media Type)

while using POST using angularJS to the rest based controller in Spring MVC, I am getting 415 Media Type unsupported type. Can anybody please help in fixing the same.Below is the code for angularJS and Rest based controller.
AngularJS-
$http.post(urlBase + 'users/insert',$scope.user)
.success(function(data) {
$scope.users = data;
$scope.user="";
$scope.toggle='!toggle';
});
Controller rest based -
#RequestMapping(value="/users/insert",method = RequestMethod.POST,headers="Accept=application/json")
public List<User> addUser(#RequestBody User user) throws ParseException {
//setter methods for setting objects and sending to backend
}
I found the issue, have set some default value to due to which this issue was coming. $http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
Corrected it to-
$http.defaults.headers.post["Content-Type"] = "application/json";
For spring-mvc JSON-Java conversion, you need to have jackson libraries in your classpath
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.4.2</version>
</dependency>
For more detailed example look at this link

Resources