RestTemplate POST with JSon - resttemplate

once again iam looking a for help/guide from experts,
My problem is, i need to create Dynamic web site which calls to restfull server to get data, all the requests are POST and returns json object. Iam thinking of use of Spring RestTemplate to make calls to server. My Server works ok, meaning currently some android and Apple apps connects to same APIs and they work ok. But when i try to use RestTemplate to connect to server, it gives some errors
org.springframework.web.client.HttpClientErrorException: 400 Bad Request
this is my server,
#Controller
public class ABCController
{
#RequestMapping(method = RequestMethod.POST, value = "/user/authenticate")
public #ResponseBody LoginResponse login(#RequestParam("email") String email,#RequestParam("password") String password,#RequestParam("facebookId") String facebookId) {
LoginRequest request = new LoginRequest(email, password, facebookId);
UserBusiness userBusiness = UserBusinessImpl.getInstance();
return userBusiness.login(request);
}
}
And this is my spring configs of server,
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<bean id="jsonViewResolver" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.BeanNameViewResolver" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jsonConverter" />
</list>
</property>
</bean>
<bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes" value="application/json" />
</bean>
<bean name="abcController" class="com.abc.def.controller.ABCController" />
<mvc:annotation-driven />
</beans>
This is how i try to call the server using RestTemplate,
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<!-- <constructor-arg ref="httpClientFactory"/> -->
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="objectMapper">
<ref bean="JacksonObjectMapper" />
</property>
</bean>
</list>
</property>
</bean>
<bean id="JacksonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper" />
and this is how i use it (for testing)
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("root-context.xml");
RestTemplate twitter = applicationContext.getBean("restTemplate", RestTemplate.class);
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("email", "x1#test.com");
map.add("password", "abc");
map.add("facebookId", null);
HttpEntity<LoginResponse> response= twitter.exchange("https://abc.com/Rest/api/user/authenticate", HttpMethod.POST, map, LoginResponse.class);
my login response class, and its sub classes,
LoginResponse
public class LoginResponse extends BaseResponse {
private LoginBase data;
with getters and setters
}
Login Base
public class LoginBase {
private String token;
private User user;
with getters and setters
}
User
public class User {
private Integer userId;
private String email;
private Integer status;
private String name;
with getters and setters
}
finally BaseResponse
public class BaseResponse {
protected String statusCode;
with getter and setter }
My questions are,
1. Why do i get this error when i call the server
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#63de8f2d: defining beans [restTemplate,JacksonObjectMapper]; root of factory hierarchy
WARN : org.springframework.web.client.RestTemplate - POST request for "https://abc.com/Rest/api/user/authenticate" resulted in 400 (Bad Request); invoking error handler
Exception in thread "main" org.springframework.web.client.HttpClientErrorException: 400 Bad Request
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:90)
at org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:494)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:451)
2. how do i map json response to java LoginResponse

You might have to add the content-type and accept headers to your request.
Mapping the response to LoginResponse can be done directly like this
LoginResponse lResponse = response.getBody();
or If you are using restTemplate.postForObject(), the reponse will be in the form of LoginResponse

Related

How to import DataSource created in #Configuration java class and use in config.xml as reference

I have my datasource in below class. Is there any way I can use that in config.xml?
I am getting an Error creating bean with name 'cmsTemplate' defined in file: cannot resolve reference bean 'contentDataSource' while setting constructor argument.
JdbcConfiguration.java
#Configuration
public class JdbcConfiguration{
#Value("$comContent.url")
private String dbUrl;
#Value("$comContent.dbUser")
private String dbUser;
#Value("$comContent.dbPass")
private String dbPass;
//rest of the properties
#Bean
#Primary
public DataSource contentDataSource() throws SQLException {
//code
}
}
config.xml
<bean id="cmsTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-args type="javax.sql.DataSource">
<ref bean="contentDataSource"/>
</constructor-args>
<property name="fetchSize" value="{systemProperties['jdbcFetchSize']}" />
</bean>
//Need to create datasource before spring context is getting created. Previously it was like below commented code.
<!-- <bean id="contentDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>java:comp/env/jdbc/comContent</value>
</property>
</bean> -->

Issue on implementing jdbc dao support in spring application

I was trying to access database using jdbcdao as per the following example:
http://www.mkyong.com/spring/spring-jdbctemplate-jdbcdaosupport-examples/
userdao, userdaoimpl,daocontext and datacontext.xml are as follows:
DAOIMPL
public class UserDAOImpl extends JdbcDaoSupport implements UserDAO {
/*Creates User */
public void insertUser(User user){
String sql = "INSERT INTO Users " +
"(id, username, password,role) VALUES (?, ?, ?,?)";
getJdbcTemplate().update(sql, new Object[] { user.getUserId(),
user.getUserName(),user.getPassWord()
});
}
}
DAO
import java.util.List;
import spring.web.models.User;
public interface UserDAO {
public void insertUser(User user);
}
DAOCONTEXT.XML
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<bean id="userDAO" class="spring.web.dao.impl.UserDAOImpl">
<property name="primaryDataSource" ref="oracleDataSource" />
</bean>
</beans>
DATA-CONTEXT.XML
<?xml version="1.0"?>
<beans
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans">
<bean id="oracleDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property value="oracle.jdbc.OracleDriver" name="driverClassName" />
<property value="jdbc:oracle:thin:#192.168.72.68:1521:d2he"
name="url" />
<property value="aaryal_1" name="username" />
<property value="oracle" name="password" />
</bean>
</beans>
The error I am facing is as follows:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDAO' defined in class path resource [dao-context.xml]:
Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException:
Invalid property 'primaryDataSource' of bean class [spring.web.dao.impl.UserDAOImpl]:
Bean property 'primaryDataSource' is not writable or has an invalid setter method.
Does the parameter type of the setter match the return type of the getter?
Please suggest me what did I miss.
You need a setPrimaryDataSource method in UserDAOImpl class. The error says it all. It's expecting a property called primaryDataSource in your class, but can't find it. Hence the error.
You'll need to do this:
private DataSource dataSource;
public void setPrimaryDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
EDIT:
If you go through the API of JdbcDaoSupport, the setDataSource method already exists. So to solve your error, you can either do the above, or simply rename your DataSource bean name to dataSource

Spring mvc not able to read messages.properties file

I am trying to use custom validation error messages by using properties file. I have placed messages.properties file in web content/web-inf/ folder.
NonEmpty.batchDomain.batchName=Invalid message 2.
My applicationContext file is :
<context:component-scan base-package="com.coaching.controller" />
<!-- Enable annotation driven controllers, validation etc... -->
<mvc:annotation-driven />
<!-- Resolves view names to protected .jsp resources within the /WEB-INF/views
directory -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<mvc:default-servlet-handler />
<mvc:resources mapping="/resources/**" location="/resources/" />
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages" />
</bean>
And my controller is :
#RequestMapping(method = RequestMethod.POST)
public ModelAndView addBatch(
#Valid #ModelAttribute("batchDomain") BatchDomain batchDomain,
BindingResult result, HttpServletRequest request,
HttpServletResponse response) throws Exception {
try {
if (result.hasErrors()) {
ModelAndView modelAndView = new ModelAndView("newBatch");
return modelAndView;
}
}
BatchDomain is :
public class BatchDomain {
#NotNull
#NotEmpty
#Size(min = 1, max = 100)
private String batchName;
#Min(1)
#Max(1000)
private int strength;
}
As far as I have seen in google, I am following the correct approach. So, what can be the reason behind this issue?
You may try to put file "messages.properties" in /src/main/resource directory.

spring-mvc: error mapping url for form controller

i have a problem with spring mvc
my spring bean
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean
class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" />
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="welcome.htm">welcomeController</prop>
</props>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean name="welcomeController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="welcome" />
<bean name="/bscList.htm" class="cbs.web.BscController">
<property name="bscDao" ref="myBscDao" />
</bean>
<bean name="/bscForm.htm" class="cbs.web.BscFormController">
<property name="commandName" value="bsc"/>
<property name="commandClass" value="cbs.domain.Bsc"/>
<property name="formView" value="bscForm"/>
<property name="successView" value="bscList.htm"/>
<property name="bscDao" ref="myBscDao"/>
</bean>
</beans>
my form controller
public class BscFormController extends SimpleFormController {
private static Logger log = Logger.getLogger(BscController.class);
private BscDao bscDao;
public void setBscDao(BscDao bscDao) {
this.bscDao = bscDao;
}
protected Object formBackingObject(HttpServletRequest request)
throws Exception {
String id = request.getParameter("id");
if (!StringUtils.isBlank(id)) {
return bscDao.get(new Integer(id));
}
return new Bsc();
}
public ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws Exception {
log.debug("entering 'onSubmit' method...");
Bsc bsc = (Bsc) command;
String success = getSuccessView();
if (request.getParameter("delete") != null) {
bscDao.remove(bsc.getId());
} else {
bscDao.save(bsc);
}
return new ModelAndView(success);
}
}
my problem:
when I access /bscList.htm, it's display list of bsc (bscList.jsp template),
but when I access /bscForm.htm, it's still display bsc's list, not show my form (bscForm.jsp template)
I have test with some simple controller:
controller implement org.springframework.web.servlet.mvc.Controller, evething run fine
controller extends SimpleFormController, map error:
No mapping found for HTTP request with URI [/cbs/testform.htm] in DispatcherServlet with name 'dispatcher'
when i use HandlerMapping ControllerClassNameHandlerMapping, all request URL '/bsc*' will map to BscController (/bscForm.htm will not map to BscFormController)

Resolve PageNotFound with spring MultiActionController

I am trying to use a MultiActionController in spring mvc, but I keep getting a 404 with the following message in the log
(org.springframework.web.servlet.PageNotFound)
No mapping found for HTTP request with
URI [/www.mysite.no/a/b/c] in
DispatcherServlet with name 'myServlet'
It looks like I'm following the book example, but it still doesn't work? Ideas, anyone?
Code samples: web.xml
<servlet-mapping>
<servlet-name>subscriptionServlet</servlet-name>
<url-pattern>/a/b/*</url-pattern>
</servlet-mapping>
Spring config: my-servlet.xml
<beans ...>
<bean id="myController" class="foo.bar.MyController">
<property name="methodNameResolver" ref="productMethodNameResolver"/>
</bean>
<bean id="productMethodNameResolver" class="org.springframework.web.servlet.mvc.multiaction.PropertiesMethodNameResolver">
<property name="mappings">
<value>
/*=view
</value>
</property>
</bean>
</beans>
The controller:
public class MyController extends MultiActionController {
Log logger = ...
#Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception{
logger.fatal("Never displayed in log");
return super.handleRequest(request, response);
}
public ModelAndView view(HttpServletRequest request, HttpServletResponse response) throws Exception {
logger.fatal("Never displayed in log");
return null;
}
I had included url mapping to methods within the controller, but lacked url mapping to the actual controller. The following must be added to the spring config
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<value>
/*=myController
</value>
</property>
</bean>

Resources