posting a JSON using Spring RestTemplate - json

I've converted a Java Object to json String and I am trying to post it to a rest webservice using RestTemplate and I am always getting a 500 error. The following are the details:
User createJSONUser = createUser(); // provides me the java object
//converting the javaobject to json string successfully using jackson in the next two lines
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(createJSONUser);
//creating the headers
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
requestHeaders.setAccept(Collections.singletonList(new MediaType("application","json")));
//setting the message converter
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
//posting the json using resttemplate
ResponseEntity<String> response = restTemplate.exchange(sandBoxURL, HttpMethod.POST, new HttpEntity<String>(jsonString, requestHeaders), String.class);
I am obtaining the resttemplate as a bean which is defined in my context-xml as follows:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd">
<bean id="responseMessageConverter" class = "com.uhg.iam.esso.rest.client.converters.CustomResponseConverter">
<property name="supportedMediaTypes" value="application/xml"/>
</bean>
<bean id="customErrorHandlerForEssoRestServer" class="com.uhg.iam.esso.rest.client.EssoRestClientErrorHandler"/>
<bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter"/>
<bean id="jaxb2Marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="supportJaxbElementClass" value="true"/>
<property name="classesToBeBound">
<list>
<value>esso.schemas.core._1.Response</value>
</list>
</property>
</bean>
<bean id="marshallingHttpMessageConverter" class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
<property name="marshaller" ref="jaxb2Marshaller"/>
<property name="unmarshaller" ref="jaxb2Marshaller"/>
</bean>
<bean id="jsonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="prefixJson" value="false"/>
<property name="supportedMediaTypes" value="application/json"/>
</bean>
<bean id="restTemplateBean" class="org.springframework.web.client.RestTemplate">
<property name="errorHandler" ref="customErrorHandlerForEssoRestServer"/>
<property name="messageConverters">
<list>
<!-- <ref bean="marshallingHttpMessageConverter"/>
<ref bean="responseMessageConverter"/> -->
<ref bean="jsonHttpMessageConverter"/>
<ref bean="stringHttpMessageConverter"/>
</list>
</property>
</bean>
<bean id="essoRestClientDelegate" class="com.uhg.iam.esso.rest.client.EssoRestClientJSONDelegate">
<property name="restTemplate" ref="restTemplateBean"/>
</bean>
</beans>
Can someone please point out where I am making a mistake?

Related

Return a JSONObject through Spring MappingJackson2JsonView

I Have xml and json output view for my spring project. I'm using spring 4 version and This is the my ViewResolver xml file.
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1" />
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="xml" value="application/xml" />
</map>
</property>
<property name="defaultViews">
<list>
<!-- JSON View -->
<bean
class="org.springframework.web.servlet.view.json.MappingJackson2JsonView">
</bean>
<!-- JAXB XML View -->
<bean class="org.springframework.web.servlet.view.xml.MarshallingView">
<constructor-arg>
<bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>com.rest.dto.SportInfoDtoList</value>
</list>
</property>
</bean>
</constructor-arg>
</bean>
</list>
</property>
<property name="ignoreAcceptHeader" value="true" />
</bean>
I want to pass Jackson JSONObject through my controller using ModelAndView.
#RequestMapping(value="stat", method=RequestMethod.POST)
public ModelAndView getSeasonteamStat(#ModelAttribute(value="statDto") StatDto statDto){
ModelAndView model = new ModelAndView();
try{
String seasonteamstatStr = GuideStatClient.getSeasonTeamStats();
JSONObject seasonteamstat = new JSONObject(seasonteamstatStr);
model.addObject("seasonteamstat", seasonteamstat);
return model;
} catch (Exception e){
return model;
}
}
If I return seasonteamstatStr it will return successfully. But I need to pass this string as a json objet. This is a huge object so I dont want to map it into java objects using JAXB.
So is there have any way to pass this string as a json. I tried jackson and gson JSONObject. Thanks in advance
Annotate your method with #ResponseBody which indicates a method return value should be bound to the web response body and change the return type to String

bluemix server gives SQLGrammarException in MySQL

![out put from cf logs app-name --recent
]1I have developed a spring/hibernate-MySQL in backend based application. I have tested the application in the local machine successfully. But when I uploaded the app into IBM bluemix, there is exceptions everywhere when I am accessing service-->Dao methods. It says org.hibernate.exception.SQLGrammarException stating the message like " SELECT command denied to user 'username#75.126.83.16'. Interstingly, when I put a normal JSP without Hibernate/spring Dao but by using the same connection string, that works.
Here is the spring-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="pojos" />
<bean id="adminService" class="pojos.AdminService">
<property name="adminDao" ref="adminDao" />
</bean>
.. Other Service class bean's info....
<bean id="adminDao" class="pojos.AdminDao">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="fieldOfficerDao" class="pojos.FieldOfficerDao">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="questionMasterDao" class="pojos.QuestionMasterDao">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
.. Other Dao class bean's info....
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>pojos/Admin.hbm.xml </value>
... And other hbm files...
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
</props>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://192.155.247.251:3307/<DB-Name>" />
<property name="username" value="<DB-User-Name>" />
<property name="password" value="<DB-Password>" />
</bean>
<bean id="dbUtil"
class="pojos.DbUtil"
init-method="initialize">
<property name="dataSource" ref="dataSource" />
</bean>
I just removed catalog attribute from class tag of each .hbm.xml files. That attribute is optional and it contains schema name of mysQL.
Previously it was
<class name="pojos.Admin" table="admin" catalog="merca">
But Now It is
<class name="pojos.Admin" table="admin">

Sending and receiving data in json using spring

I am using POST MAN CLIENT of GOOGLE CHROME TO SEND articleName and articleId AS HEADER application/json.What things I needed to change in my controller and library as well as in my spring servlet.xml?My controller is as follows.
public class ArticleController {
#Autowired
private ArticleService articleService;
Article article = new Article();
Long articleId = article.getArticleId();
#RequestMapping(value = "/save", method = RequestMethod.POST)
public Article saveArticle(#ModelAttribute Article article,
BindingResult bindingresult) {
int a = articleService.addArticle(article);
if (a == 1) {
return new ModelAndView("success");
} else {
return new ModelAndView("error");
}
}
My Spring servlet is:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:property-placeholder location="classpath:jdbc.properties" />
<context:component-scan base-package="net.roseindia" />
<tx:annotation-driven transaction-manager="hibernateTransactionManager"/>
<mvc:annotation-driven />
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>net.roseindia.model.Article</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
</bean>
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
Plz help me out....Thanks in advance.
I assume what you want is to return JSON easily from Spring.
To do that you need Jackson dependency:
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.7.1</version>
</dependency>
When you have it,
you can annotate your method with #ResponseBody annotation just like this:
public #ResponseBody Article saveArticle(#ModelAttribute Article article,
BindingResult bindingresult) {
....
}
Such a method will return JSONified Article object in response.

Spring configuration - mvc:annotation-driven, AnnotationMethodHandlerAdapter, and JSON

Thanks in advance any help.
I'm trying to get one of my controller methods to return JSON. Starting off with a simple test:
#RequestMapping(value="/myReqPath", method=RequestMethod.GET)
#ResponseBody
public Map<String, String> myJsonMethod() {
Map<String, String> response = new TreeMap<String, String>();
response.put("test", "test");
return response;
}
It's my understanding that I need <mvc:annotation-driven/> added to my servlet context to accomplish this. The problem is when I add it, it breaks my custom AnnotationMethodHandlerAdapter.
[B]How do I extract and add the needed parts of <mvc:annotation-driven/> to return JSON from the controller?[/B]
Here are the pertinent parts of my servlet config:
<!--Skipping this for now...
<mvc:annotation-driven/>
-->
<!-- JSON Marshaling -->
<util:constant id="jsonBasicClassIntrospector"
static-field="org.codehaus.jackson.map.introspect.BasicClassIntrospector.instance" />
<bean id="jsonJaxbAnnotationIntrospector"
class="org.codehaus.jackson.xc.JaxbAnnotationIntrospector" />
<bean id="jsonVisibilityChecker"
class="org.codehaus.jackson.map.introspect.VisibilityChecker.Std"
factory-method="defaultInstance" />
<bean id="jsonDefaultTypeFactory"
class="org.codehaus.jackson.map.type.TypeFactory"
factory-method="defaultInstance" />
<bean id="jsonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper">
<property name="serializationConfig">
<bean class="org.codehaus.jackson.map.SerializationConfig">
<constructor-arg ref="jsonBasicClassIntrospector" />
<constructor-arg ref="jsonJaxbAnnotationIntrospector" />
<constructor-arg ref="jsonVisibilityChecker" />
<constructor-arg><null/></constructor-arg>
<constructor-arg><null/></constructor-arg>
<constructor-arg ref="jsonDefaultTypeFactory" />
<constructor-arg><null/></constructor-arg>
</bean>
</property>
<property name="deserializationConfig">
<bean class="org.codehaus.jackson.map.DeserializationConfig">
<constructor-arg ref="jsonBasicClassIntrospector" />
<constructor-arg ref="jsonJaxbAnnotationIntrospector" />
<constructor-arg ref="jsonVisibilityChecker" />
<constructor-arg><null/></constructor-arg>
<constructor-arg><null/></constructor-arg>
<constructor-arg ref="jsonDefaultTypeFactory" />
<constructor-arg><null/></constructor-arg>
</bean>
</property>
</bean>
...
<!-- My custom AnnotationMethodHandlerAdapter... -->
<bean id="sessionArgResolver" class="com.SessionParamArgumentResolver"/>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="customArgumentResolver" ref="sessionArgResolver"/>
</bean>
As it stands, my controller method is invoked however, the browser returns http status 406:
406 Not Acceptable - [url]http://localhost:8080/myApp/myReqPath[/url]
If you already have a custom AnnotationMethodHandlerAdapter declaration, you can just add a list of HttpMessageConverters to it:
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="customArgumentResolver" ref="sessionArgResolver"/>
<property name = "messageConverters">
<list>
<bean
class = "org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name = "objectMapper" ref = "jsonObjectMapper" />
</bean>
</list>
</property>
</bean>

how to configure spring mvc 3 to not return "null" object in json response?

a sample of json response looks like this:
{"publicId":"123","status":null,"partner":null,"description":null}
It would be nice to truncate out all null objects in the response. In this case, the response would become {"publicId":"123"}.
Any advice? Thanks!
P.S: I think I can do that in Jersey. Also I believe they both use Jackson as the JSON processer.
Added Later:
My configuration:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- Scans the classpath of this application for #Components to deploy as beans -->
<context:component-scan base-package="com.SomeCompany.web" />
<!-- Application Message Bundle -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages/messages" />
<property name="cacheSeconds" value="0" />
</bean>
<!-- Configures Spring MVC -->
<import resource="mvc-config.xml" />
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- Configures the #Controller programming model -->
<mvc:annotation-driven />
<!-- Forwards requests to the "/" resource to the "welcome" view -->
<!--<mvc:view-controller path="/" view-name="welcome"/>-->
<!-- Configures Handler Interceptors -->
<mvc:interceptors>
<!-- Changes the locale when a 'locale' request parameter is sent; e.g. /?locale=de -->
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
</mvc:interceptors>
<!-- Saves a locale change using a cookie -->
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" />
<!--<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="atom" value="application/atom+xml"/>
<entry key="html" value="text/html"/>
<entry key="json" value="application/json"/>
<entry key="xml" value="text/xml"/>
</map>
</property>
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
</list>
</property>
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
<bean class="org.springframework.web.servlet.view.xml.MarshallingView" >
<property name="marshaller">
<bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller" />
</property>
</bean>
</list>
</property>
</bean>
-->
<!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
My code:
#Controller
public class SomeController {
#RequestMapping(value = "/xyz", method = {RequestMethod.GET, RequestMethod.HEAD},
headers = {"x-requested-with=XMLHttpRequest","Accept=application/json"}, params = "!closed")
public #ResponseBody
List<AbcTO> getStuff(
.......
}
}
Yes, you can do this for individual classes by annotating them with #JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL) or you can do it across the board by configuring your ObjectMapper, setting the serialization inclusion to JsonSerialize.Inclusion.NON_NULL.
Here is some info from the Jackson FAQ: http://wiki.fasterxml.com/JacksonAnnotationSerializeNulls.
Annotating the classes is straightforward, but configuring the ObjectMapper serialization config slightly trickier. There is some specific info on doing the latter here.
Doesn't answer the question but this is the second google result.
If anybody comes here and wants do do it for Spring 4 (as it happened to me), you can use the annotation
#JsonInclude(Include.NON_NULL)
on the returning class.
As mentioned in the comments, and in case anyone is confused, the annotation should be used in the class that will be converted to JSON.
If using Spring Boot for REST, you can do it in application.properties:
spring.jackson.serialization-inclusion=NON_NULL
source
Java configuration for the above. Just place the below in your #Configuration class.
#Bean
public Jackson2ObjectMapperBuilder objectMapperBuilder() {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.serializationInclusion(JsonInclude.Include.NON_NULL);
return builder;
}