Spring xml in response via JAXB - spring

I am using spring 3.1, and my application is already set up to send and receive data in json format. Now I need to provide one request API that should return the same data but in xml format.
Please help me with this stuff or tell what I am doing wrong. I tried JAXB, but instead of xml I receive "406 Not Acceptable".
My requests API:
/**
* Gets objects in json format
*/
#RequestMapping(value = "/objects/json", method = RequestMethod.GET)
#ResponseBody
public List<MyObjectTO> getAll() {
List<MyObjectTO> objectsList = new ArrayList<MyObjectTO>();
//forming objects
return objectsList;
}
/**
* Gets objects in xml format
*/
#RequestMapping(value = "/objects/xml", method = RequestMethod.GET,headers={"Accept=application/xml"})
#ResponseBody
public ResponseList getAll() {
ResponseList objectsList = new ResponseList ();
//the same formation
return objectsList;
}
Context
<?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:mvc="http://www.springframework.org/schema/mvc"
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.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.kenshoo.urlbuilder"/>
<mvc:annotation-driven/>
<mvc:view-controller path="/mainpage" view-name="mainpage"/>
<util:properties id="addProps" location="classpath:config/addProps.properties"/>
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="alwaysUseFullPath" value="true"/>
</bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="alwaysUseFullPath" value="true"/>
</bean>
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="html" value="text/html"/>
<entry key="json" value="application/json"/>
<entry key="pdf" value="application/pdf"/>
</map>
</property>
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="cache" value="true"/>
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</list>
</property>
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/>
</list>
</property>
</bean>
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
</beans>
My changes: Added message converters to AnnotationMethodHandlerAdapter and inserted JAXB marshaller. But after this got response "406 Not Acceptable":
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="alwaysUseFullPath" value="true"/>
<property name="messageConverters">
<list>
<ref bean="marshallingConverter" />
</list>
</property>
</bean>
<bean id="marshallingConverter" class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
<property name="marshaller" ref="jaxbMarshaller" />
<property name="unmarshaller" ref="jaxbMarshaller" />
<property name="supportedMediaTypes" value="application/xml"/>
</bean>
<bean id="jaxbMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>com.ResponseList</value>
</list>
</property>
</bean>
I would appreciate any help, thanks.
UPDATE
ResponseList structure:
public class ResponseList {
private List<FirstLevel> firstLevelObjects;
public List<FirstLevel> getFirstLevelObjects() {
return firstLevelObjects;
}
public void setFirstLevelObjects(List<FirstLevel> firstLevelObjects) {
this.firstLevelObjects= firstLevelObjects;
}
}
FirstLevel structure:
public class FirstLevel {
List<SecondLevel> secondLevelObjects;
boolean isConditional;
String beforeStart;
ConditionType type;//enum object
//...getters and setters
}

I lost hope with Castor, so tried once more with JAXB. Changed post
with details for JAXB. The same issues - I got Not Acceptable when
trying to request xml. Can you help me?
All you should need to do for JAXB is to add an #XmlRootElement annotation to your ResponseList class.
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class ResponseList {
private List<FirstLevel> firstLevelObjects;
public List<FirstLevel> getFirstLevelObjects() {
return firstLevelObjects;
}
public void setFirstLevelObjects(List<FirstLevel> firstLevelObjects) {
this.firstLevelObjects= firstLevelObjects;
}
}

Related

Hazelcast client spring configuration

I have createed a Hazelcast manager which uses spring, hibernate, jpa. I can start my hazelcast instance.
The problem I have is I dont know how to configure a hazelcast client using spring config. I want to use in some other server component a hazelcast-client
I really have no idea how to start
any help would be appreciated
Below is my spring config for hazelcast server
Johan
<?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:hz="http://www.hazelcast.com/schema/spring"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.hazelcast.com/schema/spring
http://www.hazelcast.com/schema/spring/hazelcast-spring.xsd">
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>file:${ecs.config.path}/ecs.properties</value>
<value>classpath*:config/ecs.properties</value>
</list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="ignoreResourceNotFound" value="true" />
</bean>
<context:component-scan base-package="nl.ict.psa.ecs.hazelcast.dao,nl.ict.psa.ecs.hazelcast.mapstores,nl.ict.psa.ecs.hazelcast.service" />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${datasource.driverClassName}" />
<property name="url" value="${datasource.url}" />
<property name="username" value="${datasource.username}"/>
<property name="password" value="${datasource.password}"/>
</bean>
<bean id="hazelcast" class="com.hazelcast.core.Hazelcast"/>
<bean id="entityManagerFactoryBean"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="PU" />
<property name="packagesToScan">
<list>
<value>nl.ict.psa.hazelcast.model.ecs</value>
<value>nl.ict.psa.hazelcast.model.ecs.ocr</value>
</list>
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.archive.autodetection">class</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
</bean>
<tx:annotation-driven />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactoryBean" />
</bean>
<bean id="transpInfo" class="nl.ict.psa.ecs.hazelcast.mapstores.TranspInfoMapStore"/>
<hz:hazelcast id="instance">
<hz:config>
<hz:network port="5701" port-auto-increment="true">
<hz:join>
<hz:multicast enabled="false"/>
</hz:join>
</hz:network>
<hz:map name="transp" read-backup-data="true">
<hz:map-store enabled="true" write-delay-seconds="60"
initial-mode="LAZY"
implementation="transpInfo"/>
</hz:map>
</hz:config>
</hz:hazelcast>
</beans>
Configured Multiple Ip's Using Pragmatically.
#Bean
public ClientConfig clientConfig() {
ClientConfig clientConfig = new ClientConfig();
ClientNetworkConfig networkConfig = clientConfig.getNetworkConfig();
networkConfig.addAddress("172.17.0.4:5701", "172.17.0.6:5701")
.setSmartRouting(true)
.addOutboundPortDefinition("34700-34710")
.setRedoOperation(true)
.setConnectionTimeout(5000)
.setConnectionAttemptLimit(5);
return clientConfig;
}
#Bean
public HazelcastInstance hazelcastInstance(ClientConfig clientConfig) {
return HazelcastClient.newHazelcastClient(clientConfig);
}
I would suggest to must read. http://docs.hazelcast.org/docs/latest/manual/html-single/index.html#configuring-client-connection-strategy
Something like this (from https://github.com/neilstevenson/spring-boot-autoconfigure-test/tree/master/hazelcast-imdg-client)
#Configuration
#ConditionalOnMissingBean(ClientConfig.class)
static class HazelcastClientConfigConfiguration {
#Bean
public ClientConfig clientConfig() throws Exception {
return new XmlClientConfigBuilder().build();
}
}
#Configuration
#ConditionalOnMissingBean(HazelcastInstance.class)
static class HazelcastClientConfiguration {
#Bean
public HazelcastInstance hazelcastInstance(ClientConfig clientConfig) {
return HazelcastClient.newHazelcastClient(clientConfig);
}
}
Try to avoid XML, Spring is moving away from it.

hibernatetemplate.getSessionFactory() throws NullPointerException

My DaoClass
#Repository("genObj")
public class GeneralQueries {
HibernateTemplate hibernatetemplate;
public HibernateTemplate getHibernatetemplate() {
return hibernatetemplate;
}
public void setHibernatetemplate(HibernateTemplate hibernatetemplate) {
this.hibernatetemplate = hibernatetemplate;
}
public String getStringfromQuery(String sql)
{
SessionFactory sessionFactory=hibernatetemplate.getSessionFactory();
Session session=sessionFactory.openSession();
String data=null;
try
{
System.out.println(sql);
data=session.createSQLQuery(sql).list().toString();
}
catch (Exception e)
{
e.printStackTrace();
}
return data;
}}
This method returns data as string
My Controller Class
#Controller
public class SchoolStudentsConfirmationContrl
{
#Autowired
SchoolStudentsConfirmationIntr schoolstdconfirmservice;
#Autowired
GeneralQueries genObj=new GeneralQueries();
#RequestMapping(value="/getData",method=RequestMethod.GET)
public ModelAndView getData(#ModelAttribute("schooldetailsform")SchoolDetailsForm formbean,HttpServletRequest request)
{
String PageHeading = "";
try
{
String district = request.getSession().getAttribute("dist_code").toString();
PageHeading = "BAS Students Confirmation for the Academic Year:"+ formbean.getAc_year() + " <br> District:"
+ genObj.getStringfromQuery("select dist_name from pmss_districts_mst where dist_code=" + district + "")+"";
mav.setViewName("showreportwithmenu");
}
catch(Exception e)
{
e.printStackTrace();
}
return mav;
}
}
Im trying to call the genObj.getStringfromQuery() method but it throws me null pointer exception at line
SessionFactory sessionFactory=hibernatetemplate.getSessionFactory();
my config file
<?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"
xmlns:tx="http://www.springframework.org/schema/tx" 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.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:annotation-config />
<context:component-scan base-package="cgg.gov.in.*" annotation-config="true"/>
<bean id="tiles" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass">
<value>
org.springframework.web.servlet.view.tiles3.TilesView
</value>
</property>
</bean>
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
<bean id="view" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://x.x.x.x/test" />
<property name="username" value="postgres" />
<property name="password" value="postgres" />
</bean>
<bean class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" name="sessionFactory">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.autocommit">false</prop>
</props>
</property>
<property name="annotatedClasses" >
<list>
<value>cgg.gov.in.model.login.LoginForm</value>
</list>
</property>
</bean>
<bean class="org.springframework.orm.hibernate4.HibernateTemplate" name="hibernatetemplate">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<mvc:default-servlet-handler />
<mvc:annotation-driven />
</beans>
You have a hibernatetemplate bean defined. But you haven't tell to point the variable, hibernatetemplate in GeneralQueries class, to the defined bean.
You can do this in two ways,
1) Create a bean for GeneralQueries in xml and define the property as below,
<bean name="generalQueries" class="package.GeneralQueries">
<property name="hibernatetemplate" ref="hibernatetemplate" />
</bean>
You have already defined the setter. Remember to remove #Repository from GeneralQueries, if you define it as a bean in xml.
2) Autowire the hibernatetemplate in GeneralQueries as below.
#Repository("genObj")
public class GeneralQueries {
#Autowired
HibernateTemplate hibernatetemplate;
//rest of code
}
GeneralQueries must be under component-scan.
Note: Also, #m-deinum suggested, remove new GeneralQueries() from SchoolStudentsConfirmationContrl.

Spring #ExceptionHandler not working

I am trying to handle an exception using #ExceptionHandler but it is not working and I don't know why. The thing is right now I am getting this response from my web service: {"message":"The date provided 2013-02-30 is invalid","code":500,"ids":null}. And I want that to be a 400 exception instead of 500.
Here is my code:
#Controller
public class WsController {
#RequestMapping(value={"/getDeletedUsers"}, method=RequestMethod.GET)
public List<Integer> getDeletedUsers(#RequestParam(value = "date", required = true) String dateStr) throws WebServiceException {
if (dateStr == null) {
throw new WebServiceException("The date provided is null");
} else if (StringUtils.isEmpty(dateStr)) {
throw new WebServiceException("The date provided is empty");
} else {
SimpleDateFormat sdf = new SimpleDateFormat();
sdf.applyPattern("yyyy-MM-dd");
sdf.setLenient(false);
try {
sdf.parse(dateStr);
} catch (ParseException e) {
throw new WebServiceException("The date provided " + dateStr + " is invalid");
}
return service.getDeletedUsers(dateStr);
}
}
#ExceptionHandler(WebServiceException.class)
public void handleWebServiceException() {
System.out.println("PLEASE DO SOMETHING!");
}
}
public class WebServiceException extends Exception {
//Constructors and serialVersionUID
}
disparcher-servlet.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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
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.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/util http://www.springframework.org/schema/util/spring-util.xsd">
<bean class="org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE"/>
<property name="searchContextAttributes" value="true"/>
<property name="contextOverride" value="true"/>
<property name="ignoreResourceNotFound" value="true"/>
<property name="locations">
<list>
<value>classpath:application.properties</value>
<value>file:c://rt//properties//webservices-application.properties</value>
</list>
</property>
</bean>
<import resource="classpath:keepalive.xml" />
<import resource="classpath:controller.xml" />
<bean id="exceptionResolver" class="com.company.project.webservices.spring.ExceptionResolver"/>
<bean id="error" class="com.company.project.webservices.spring.ErrorView"/>
<bean id="readOnlyModeError" class="com.company.project.webservices.spring.ReadOnlyModeErrorView"/>
<bean id="methodUnavailableError" class="com.company.project.webservices.spring.MethodUnavailableErrorView"/>
<bean id="badRequestError" class="com.company.project.webservices.spring.BadRequestErrorView"/>
<!-- View Resolver -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1" />
<property name="mediaTypes">
<map>
<entry key="json" value="application/json"/>
</map>
</property>
<!-- Ticket-3245 Spring 60 -->
<property name="defaultContentType" value="application/json" />
<property name="useNotAcceptableStatusCode" value="true"/>
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
<property name="order" value="2" />
</bean>
</list>
</property>
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
</list>
</property>
</bean>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages"/>
</bean>
<!-- Dispatches requests mapped to POJO #Controllers implementations -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<util:list id="beanList">
<ref bean="jsonHttpMessageConverter"/>
</util:list>
</property>
</bean>
<bean id="jsonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
</bean>
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="useDefaultSuffixPattern" value="false"/>
</bean>
<!-- Dispatches requests mapped to non-annotated controllers -->
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />
<context:annotation-config/>
<context:component-scan base-package="com.company.project" />
When I try to debug the handleWebServiceException method it doesn't even stop there.
Any tips will be appreciated.
As jny suggested, I took a look at the dispatcher-servlet.xml and realized that there was a exceptionResolver bean that I haven't seen that looks like this:
public class ExceptionResolver extends AbstractHandlerExceptionResolver {
private static Log logger = LogFactory.getLog(ExceptionResolver.class);
#Override
protected ModelAndView doResolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
ModelAndView mv = null;
if (ex instanceof ReadOnlyModeException) {
mv = new ModelAndView("readOnlyModeError");
} else if (ex instanceof MethodUnavailableException) {
mv = new ModelAndView("methodUnavailableError");
} else if (ex instanceof BadRequestException) {
mv = new ModelAndView("badRequestError");
} else {
logger.error("caught an exception: ", ex);
mv = new ModelAndView("error");
}
ResultBean resultBean = new ResultBean();
resultBean.setCode(500);
resultBean.setMessage(ex.getMessage());
mv.addObject("result", resultBean);
return mv;
}
}
And there I was able to make the suitable changes.
Thanks again to jny for the hint.

How to consume third party WSDL services in Spring MVC

I wrote some services (used by an Android app) which takes a request and sends th response in json. Now I have a scenario where I have to consume a third party web service, through a provided WSDL file. I don't know how to do this, can anyone help?
This is my dispatcher-servlet.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans ">
<context:property-placeholder location="classpath:jdbc.properties" />
<context:component-scan base-package="com.srihari" />
<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>com.srihari.model.User</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
//This is used to convert my requests and responses into json automatically
<bean id="jacksonMessageChanger" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes" value="application/json"/>
</bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<util:list id="beanList">
<ref bean="jacksonMessageChanger"/>
</util:list>
</property>
</bean>
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="json" value="application/json"/>
<entry key="html" value="text/html"></entry>
<entry key="xml" value="application/xml"></entry>
</map>
</property>
</bean>
</beans>
This is my simple controller: These services are working fine
#Controller
#RequestMapping("/home")
public class UserController {
#RequestMapping(value="/getallusers",method = RequestMethod.GET)
public #ResponseBody List<User> getallusers()
{
List<User> allUsersDetails =userServices.getAllUsers();
return allUsersDetails;
}
}
This is the WSDL file provided by the third party
POST /someservices/otherService.asmx HTTP/1.1
Host: sriharicorp.com
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://tempuri.org/CreateCard"
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Header>
<UserCredentials xmlns="http://tempuri.org/">
<Password>string</Password>
<Username>string</Username>
</UserCredentials>
</soap:Header>
<soap:Body>
Example String Request
<CreateCard xmlns="http://tempuri.org/">
<request>
<DePpAcctCreationDate>string</DePpAcctCreationDate>
<DePpAcctCreationTime>string</DePpAcctCreationTime>
//Some other fields also
</request>
</CreateCard>
</soap:Body>
</soap:Envelope>
Example String Response
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<CreateCardResponse xmlns="http://tempuri.org/">
<CreateCardResult>
<RequestType>string</RequestType>
<ProductType>string</ProductType>
<ResponseCode>string</ResponseCode>
<ReasonDescription>string</ReasonDescription>
</CreateCardResult>
</CreateCardResponse>
</soap:Body>
</soap:Envelope>
Finally I'm able to access Third services.
This is my method to access service
public void createSoapActionCallBack(ValidateCardRequest validateCardRequest) {
//This is used to send header message
SoapActionCallback actionCallBack=new SoapActionCallback(soapAction);
try{
actionCallBack = new SoapActionCallback(ResponseConstants.SOAPACTION_DEFAULT_URL) {
public void doWithMessage(WebServiceMessage msg) {
SoapMessage smsg = (SoapMessage)msg;
SoapHeader soapHeader = smsg.getSoapHeader();
try{
//To send header message
StringSource headerSource = new StringSource("<UserCredentials xmlns='URL'>\n" +
"<userid>"+"ABCD"+"</userid>\n" +
"<password>"+"ABCD"+"</password>\n" +
"</UserCredentials>");
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.transform(headerSource, soapHeader.getResult());
smsg.setSoapAction(soapAction);
}catch(Exception e)
{
e.printStackTrace();
}
}
};
validateCardResponse = (FVValidateCardResponse) webServiceTemplate.marshalSendAndReceive(URL, validateCardRequest, actionCallBack);
} catch (Exception e) {
e.printStackTrace();
}
}
This is my configuration xml file:
<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory">
<property name="soapVersion">
<util:constant static-field="org.springframework.ws.soap.SoapVersion.SOAP_12"/>
</property>
</bean>
<bean id="marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<!-- If we want to use contextPath then we mush create ObjectFactory class in the described Package-->
<!-- <property name="contextPath" value="com.waleteros.firstviewmodel" /> -->
<property name="classesToBeBound">
<list>
<value>com.waleteros.firstviewmodel.FVValidateCardRequest</value>
<value>com.waleteros.firstviewmodel.FVValidateCardResponse</value>
</list>
</property>
</bean>
<bean id="webServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
<constructor-arg ref="messageFactory" />
<property name="marshaller" ref="marshaller"></property>
<property name="unmarshaller" ref="marshaller"></property>
<property name="messageSender">
<bean class="org.springframework.ws.transport.http.HttpComponentsMessageSender"/>
</property>
<!-- <property name="defaultUri" value="https://www.firstviewcorp.com/dbbapplications/ServicesSS/Selfservice.asmx?wsdl"/> -->
</bean>
Create pojo's according to your xmls
Here is example
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement(name = "CardUpdateResponse",namespace="http://www.corecard.com/Prepaid")
public class FVCardUpdateResponse {
#XmlElement(name="CARDUPDATE_RET", namespace="http://www.corecard.com/Prepaid")
private CARDUPDATE_RET response;
//Getters and Setters
public static class CARDUPDATE_RET{
#XmlElement(name = "ACCOUNTNUMBER", namespace="http://www.corecard.com/Prepaid")
private String AccountNumber;
#XmlElement(name = "ResCode", namespace="http://www.corecard.com/Prepaid")
private String ResCode;
#XmlElement(name = "ResErrorCode", namespace="http://www.corecard.com/Prepaid")
private String ResErrorCode;
#XmlElement(name = "ResErrorMsg", namespace="http://www.corecard.com/Prepaid")
private String ResErrorMsg;
//Getters and Setters
}
}

Stored Procedure Call with Spring Framework

Can anyone provide complete example of Stored Procedure call with Spring framework.
Thanks,
Raj
Using the Spring stored procedure framework:
jdbc-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:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/orcl/DB"/>
</bean>
<bean id="storedProc" class="com.DatabaseStoredProc">
<property name="dataSource" ref="dataSource" />
<property name="sql" value="aStoredProc" />
<property name="parameters">
<list>
<bean class="org.springframework.jdbc.core.SqlParameter">
<constructor-arg index="0" value="p_id1" />
<constructor-arg index="1">
<util:constant static-field="java.sql.Types.VARCHAR" />
</constructor-arg>
</bean>
<bean class="org.springframework.jdbc.core.SqlParameter">
<constructor-arg index="0" value="p_id2" />
<constructor-arg index="1">
<util:constant static-field="java.sql.Types.VARCHAR" />
</constructor-arg>
</bean>
</list>
</property>
</bean>
</beans>
DatabaseStoredProcedure class
import java.util.Map;
import org.springframework.jdbc.object.StoredProcedure;
public class DatabaseStoredProc extends StoredProcedure {
public Map<String, Object> execute(Map inputs){
Map out=super.execute(inputs);
return null;
}
// Method to map data to inputs Map:
public boolean businessRules(Object obj, Map inputs){
SomeObject otd = (SomeObject) obj;
inputs.put("p_id1", otd.getId1());
inputs.put("p_id2", otd.getId2() );
return true;
}
}
Create a Controller with reference to which you inject your datasource (applicationContext.xml):
<bean id="storedProcedureDao" class="com..myapp.SpringStoredProcedureDao">
<property name="dataSource">
<ref bean="jtdsDataSource"/>
</property>
</bean>
Data source:
<bean id="jtdsDataSource" class="net.sourceforge.jtds.jdbcx.JtdsDataSource">
<property name="serverName">
<value>servername</value>
</property>
<property name="databaseName">
<value>database</value>
</property>
<property name="user">
<value>username</value>
</property>
<property name="password">
<value>password</value>
</property>
</bean>
In your Controller, put the following:
public class SpringStoredProcedureDao extends StoredProcedure {
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public CallStoredProcedure(String procedureName){
super(this.dataSource, procedureName);
compile();
}
}
This should more or less be it :)
The above solution won't work, as you cannot call a super class constructor in a sub class method. It has to be called within the sub class constructor

Resources