How to consume third party WSDL services in Spring MVC - spring

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
}
}

Related

Spring HibernateDaoSupport not enabling hibernate filters

Why the HibernateDaoSupport is not enabling hibernate filters.I am trying to enable the filters in my code but not enabling.I have posted the spring and xml configuration files as below. I have provided all the files.
EmployeeHibernateDao.java :
public class EmployeeHibernateDao extends HibernateDaoSupport {
public void saveDetails(Student s){
getSession().merge(s);
}
public void getDetails(){
Criteria ct= getSession().createCriteria(Student.class);
getSession().enableFilter("addressFilter");
List<Student> list = ct.list();
for(Student s: list){
System.out.println(s.getSname());
}
}
}
student.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.spring.hibernatedao.Student" table="student24">
<composite-id class="com.spring.hibernatedao.Address" name="address">
<key-property name="addressNo" column="addressno" />
<key-property name="addressName" column="addressname" />
</composite-id>
<property name="sname" column="sname" />
<property name="date" column="inserteddate" />
<filter name="addressFilter" condition="sname = 'hello'" />
</class>
<filter-def name="addressFilter" />
</hibernate-mapping>
applicationContext.xml:
<beans>
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#localhost:1521:xe" />
<property name="username" value="system" />
<property name="password" value="system" />
</bean>
<bean id="myssessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="datasource" />
<property name="mappingResources">
<list>
<value>/com/spring/hibernatedao/student.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
</props>
</property>
</bean>
<bean id="empdao" class="com.spring.hibernatedao.EmployeeHibernateDao">
<property name="sessionFactory" ref="myssessionFactory" />
</bean>
Test.java:
public class Test {
public static void main(String[] args) {
ApplicationContext ct=new ClassPathXmlApplicationContext("com/spring/hibernatedao/applicationContext.xml");
EmployeeHibernateDao empdao= ct.getBean("empdao", EmployeeHibernateDao.class);
empdao.getDetails();
}
}
Add One below configuration into student.xml and try:
<filter name="addressFilter" condition="sname = :addressFilterParam" />
</class>
<filter-def name="addressFilter">
<filter-param name="addressFilterParam" type="java.lang.String"/>
</filter-def>

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.

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.

Spring xml in response via JAXB

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;
}
}

Spring HTTP.DELETE return code 415 unsupported mediatype

#ResponseBody
#RequestMapping(method = RequestMethod.DELETE)
public String deleteState(#RequestBody String message) {
System.out.println("controller");
int resp = stateService.delete(message);
return resp == 1 ? "State deleted successfully : HTTP 200"
: "delete operation failed : HTTP 400";
}
when I post a json { stateName: VA}, it returns 415 error, Can any one suggest something please?
#Override
#Transactional
public int delete(Object message) {
System.out.println("service");
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject((String) message);
Parameters p = new Parameters();
p.property = "state_name";
p.value = (String) jsonObj.getString("stateName");
System.out.println("service");
return stateDAO.delete(p);
} catch (Exception e) {
return 0;
}
}
This is what I am doing in the service...
Update : Here is my Spring Configuration:
<context:annotation-config />
<!-- Scans the classpath of this application for #Components to deploy as
beans -->
<context:component-scan base-package="com.tutorial.jquery" />
<!-- Configures the #Controller programming model -->
<mvc:annotation-driven />
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/spring/jdbc.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" p:driverClassName="org.postgresql.Driver"
p:url="jdbc:postgresql://localhost:5432/processdb" p:username="postgres"
p:password="postgres" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- >bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"
/> <property name="order" value="0" /> <property name="prefix"> <value>/WEB-INF/views/</value>
</property> <property name="suffix"> <value>.html</value> </property> </bean -->
<bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="2" />
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
</map>
</property>
<property name="defaultViews">
<list>
<!-- JSON View -->
<bean
class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
</bean>
</list>
</property>
</bean>
<!-- If no extension matched, use JSP view -->
<bean id="htmlView"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="order" value="1" />
<property name="prefix">
<value>/views/</value>
</property>
<property name="suffix">
<value>.html</value>
</property>
</bean>
I updated the method to get it working:
#ResponseBody
#RequestMapping(method = RequestMethod.DELETE)
public String deleteState(HttpServletRequest request,
HttpServletResponse response) {
Map<String, String[]> parameters = request.getParameterMap();
//System.out.print("RequestParam: " + state_Name);
int resp = stateService.delete(parameters.get("state_name")[0]);
return resp == 1 ? "State deleted successfully : HTTP 200"
: "delete operation failed : HTTP 400";
}
This fixed the issue
Thanks!
Try this,
change
#RequestBody String message
to
#RequestParam String stateName

Resources