How to add message converter to restTemplate in xml configuration - rest

I am using restTemplate for consuming json data from remote server, and then parsing the json in my java objects using jackson. I have added required message converters to my restTemplate by java code as:
List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
messageConverters.add(new FormHttpMessageConverter());
messageConverters.add(new StringHttpMessageConverter());
messageConverters.add(new MappingJacksonHttpMessageConverter());
restTemplate.setMessageConverters(messageConverters);
restTemplate.setRequestFactory(new CommonsClientHttpRequestFactory());
MyResponse myResponse = restTemplate.getForObject(caasUrl, MyResponse.class);
And my restTemplate is defined in my spring-config file as:
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<constructor-arg>
<bean class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory">
<property name="readTimeout" value="630000" />
<property name="connectTimeout" value="30000" />
</bean>
</constructor-arg>
</bean>
And its working fine, now my question is how can we pass the list of message converters to restTemplate in xml configuration as I do not want to do the same by java code. any Help please

Try this...sample code below shows only 2 converters.
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.FormHttpMessageConverter"/>
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
......more....
</list>
</property>

Related

Using spring cloud namespace and two DataSources

I have a Spring Integration WAR component that I'm updating to run in private PCF. I have two DataSources and a RabbitMQ connection factory defined in the application.
I see an article from Thomas Risberg on using the cloud namespace and handling multiple services of the same time - https://spring.io/blog/2011/11/09/using-cloud-foundry-services-with-spring-part-3-the-cloud-namespace. This is handled by using #Autowired and #Qualifier annotations.
I'm wondering how this can be achieved though when we're not #Autowired and #Qualifier annotations, e.g. wiring a DataSource into a JdbcTemplate. Here we do not have the ability to specify a #Qualifier annotation.
My application is Spring XML config based. I do have ability to use #Autowired and #Qualifier annotations on one of the DataSources, but the other is JPA entity manager. See code snippet.
Any help is much appreciated.
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="activity-monitor" />
<property name="jpaVendorAdapter" ref="jpaVendorAdapter"/>
<property name="jpaProperties">
<value>
hibernate.format_sql=true
</value>
</property>
</bean>
<beans profile="cloud">
<cloud:data-source id="dataSource" service-name="actmon-db-service" />
</beans>
Java Build Pack: java_buildpack_offline java-buildpack-offline-v2.4.zip
Spring Auto-reconfiguration version 1.4.0.
UPDATE: This is the full config for both data sources, including PropertySourcesPlaceholderConfigurer with properties loaded from data source using DAO.
<bean id="cic.application.ppc" class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="properties" ref="cic.application.properties"/>
<property name="locations" ref="cic.application.propertyLocations"/>
</bean>
<bean id="cic.application.properties" class="java.util.Properties">
<constructor-arg value="#{cicPropertiesService.properties}"></constructor-arg>
</bean>
<bean id="cic.properties.propertiesService" name="cicPropertiesService"
class="com.emc.it.eis.properties.service.DefaultPropertiesService">
<constructor-arg index="0"
ref="cic.properties.propertiesDao" />
</bean>
<bean id="cic.properties.propertiesDao" class="com.emc.it.eis.properties.dao.JdbcPropertiesDao">
<constructor-arg ref="cic.properties.dataSource" />
</bean>
<beans profile="default">
<jee:jndi-lookup id="cic.properties.dataSource"
jndi-name="jdbc/intdb" />
</beans>
<beans profile="cloud">
<cloud:data-source id="cic.properties.dataSource" service-name="oracle-cicadm-db-service" />
</beans>
<beans>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="actmonDataSource" />
<property name="persistenceUnitName" value="activity-monitor" />
<property name="jpaVendorAdapter" ref="jpaVendorAdapter"/>
<property name="jpaProperties">
<value>
hibernate.format_sql=true
</value>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
</beans>
<beans profile="default">
<jee:jndi-lookup id="dataSource"
jndi-name="jdbc/actmon" />
</beans>
<beans profile="cloud">
<cloud:data-source id="actmonDataSource" service-name="postgres-actmon-db-service" />
</beans>
<beans profile="default,cloud">
<bean id="jpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="POSTGRESQL" />
</bean>
</beans>
Output from CF when I deploy https://gist.github.com/anonymous/3986a1a7cea4f20c096e. Note it is skipping auto re-configuration of javax.sql.DataSources
First of all, the post from Thomas is pretty old, and references a deprecated support library. Instead of the org.cloudfoundry:cloudfoundry-runtime:0.8.1 dependency, you should use Spring Cloud Connectors dependencies instead.
You can then follow the instructions provided for using XML configuration with Spring Cloud Connectors. With multiple services of the same type, you will need to specify the name of the service for each bean. Following your example, and assuming you created two CF database services named inventory-db and customer-db, that might look something like this:
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="inventory-dataSource" />
<property name="persistenceUnitName" value="activity-monitor" />
<property name="jpaVendorAdapter" ref="jpaVendorAdapter"/>
<property name="jpaProperties">
<value>
hibernate.format_sql=true
</value>
</property>
</bean>
<beans profile="cloud">
<cloud:data-source id="inventory-dataSource" service-name="inventory-db">
<cloud:data-source id="customer-dataSource" service-name="customer-db">
</beans>
I've managed to resolve the issue by using the factory bean used by the spring cloud:data-source, CloudDataSourceFactory. Creating an instance of this and wiring up the config including the service-name of the CF service. This avoids the issue of our PropertySourcesPlaceholderConfigurer trying to use the data source before our the bean has even been defined.
<!--
configure cloud data source for using CloudDataSourceFactory; this is what spring cloud:data-source is using;
required to manually wire this data source bean as cloud:data-source bean gets defined in a phase after our
PropertySourcesPlaceholderConfigurer bean.
-->
<bean id="cic.properties.dataSource" class="org.springframework.cloud.service.relational.CloudDataSourceFactory">
<constructor-arg value="oracle-cicadm-db-service" />
<constructor-arg>
<!-- configuring minimal data source as it is used only to bootstrap properties on app start-up -->
<bean class="org.springframework.cloud.service.relational.DataSourceConfig">
<constructor-arg>
<bean class="org.springframework.cloud.service.PooledServiceConnectorConfig.PoolConfig">
<constructor-arg value="0" />
<constructor-arg value="2" />
<constructor-arg value="180" />
</bean>
</constructor-arg>
<!-- ConnectionConfig not required for cic.properties.dataSource so setting to null -->
<constructor-arg value="#{ null }" />
</bean>
</constructor-arg>
</bean>

Error with Spring ldap pooling

i build async jersey web services, and now i need to make some operations with ldap.
I have configure Spring beam.xml in this mode:
<bean id="contextSourceTarget" class="org.springframework.ldap.core.support.LdapContextSource">
<property name="url" value="${ldap.url}" />
<property name="base" value="${ldap.base}" />
<property name="userDn" value="${ldap.userDn}" />
<property name="password" value="${ldap.password}" />
<property name="pooled" value="false" />
</bean>
<bean id="contextSource"
class="org.springframework.ldap.pool.factory.PoolingContextSource">
<property name="contextSource" ref="contextSourceTarget" />
</bean>
<bean id="ldapTemplate" class="org.springframework.ldap.core.LdapTemplate">
<constructor-arg ref="contextSource" />
</bean>
<bean id="ldapTreeBuilder" class="com.me.ldap.LdapTreeBuilder">
<constructor-arg ref="ldapTemplate" />
</bean>
<bean id="personDao" class="com.me.ldap.PersonDaoImpl">
<property name="ldapTemplate" ref="ldapTemplate" />
</bean>
But when i try to use ldap i have this error:
Error creating bean with name 'contextSource' defined in class path resource [config/Beans.xml]: Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: org/apache/commons/pool/KeyedPoolableObjectFactory
In my project i have commons-pool2-2.2.jar lib, but still i have this error..i try to add commons-pool2-2.2.jar in TOMCAT_PATH/lib but not works..
UPDATE:
If i put commons-pool-1.6.jar it works.. but if i want to use pool2 how i can do? only i must change class inn commons-pool2-2.2.jar?
Updated Answer:
Since at least Spring LDAP 2.3.2 you can now use commons-pool2. Spring LDAP now provides two classes:
For commons-pool 1.x:
org.springframework.ldap.pool.factory.PoolingContextSource
For commons-pool 2.x:
org.springframework.ldap.pool2.factory.PooledContextSource
Details can be found here:
https://github.com/spring-projects/spring-ldap/issues/351#issuecomment-586551591
Original Answer:
Unfortunately Spring-Ldap uses commons-pool and not commons-pool2. As you have found the class org.apache.commons.pool.KeyedPoolableObjectFactory does not exist in commons-pool2 (it has a different package structure), hence the error.
There is a Jira issue for the Spring-ldap project asking them to upgrade/support commons-pool2:
https://jira.spring.io/browse/LDAP-316
Until that has been completed you will have to use commons-pool 1.6.

Spring REST Form Data PUT method

I have given below my spring controller and .xml file congif info .
class TestingController
{
#RequestMapping(value="/addinfo",method=RequestMethod.PUT)
public void addInfo(#RequestBody Userinfo user){
}
context
<mvc:annotation-driven/>
<bean id="contentNegotiationManager" class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="ignoreAcceptHeader" value="true"/>
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="xml" value="application/xml" />
</map>
</property>
This is working fine as i am expecting for the JSON and XML Request using REST Client.
for example : {"user":"test","cval":"12","mval":"12} JSON working fine .
when i try to pass the data like user=test&cval=12&mval=12 using in request body using REST client with header "Content-Type:application/x-www-form-urlencoded"
I am getting 415 error message.
My Requirement is
SPring RESTfull Webservice need to handle the below Content-Type
1.application/json
2.application/xml
3.application/x-www-form-urlencoded
Regards
Vasanth D

How to perform JAXB2 marshalling of input request in REST with Spring MVC3?

I am new to Spring MVC (Spring 3) and REST, and I am trying out a little toy app to try out GET and POST web services. I have read the Spring's official reference, and found these questions in Stackoverflow, RequestBody of a REST application , Pass a request parameter in Spring MVC 3 but I am still stucked in making it works. Can anyone give me hints on what I missed?
My Controller is like this:
#Controller
#RequestMapping(value = "/echo")
public class EchoControllerImpl implements EchoController {
#RequestMapping(method = RequestMethod.POST, value = "/echoByPost")
public ModelAndView echoByPost(#ModelAttribute EchoDto input) {
// ...
}
}
I have putted corresponding converter in the app ctx:
<mvc:annotation-driven />
<bean id="jaxb2Marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller" >
<property name="classesToBeBound">
<list>
<value>foo.EchoDto</value>
</list>
</property>
</bean>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="marshallingHttpMessageConverter" />
<ref bean="stringHttpMessageConverter" />
</list>
</property>
</bean>
<bean id="stringHttpMessageConverter"
class="org.springframework.http.converter.StringHttpMessageConverter" />
<bean id="marshallingHttpMessageConverter"
class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
<property name="marshaller" ref="jaxb2Marshaller" />
<property name="unmarshaller" ref="jaxb2Marshaller" />
</bean>
<!-- other beans like ViewResolvers -->
I even tried to add these to web.xml as I saw somewhere mentioning about it (though I don't really know what does it means)
<filter>
<filter-name>httpPutFormFilter</filter-name>
<filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>httpPutFormFilter</filter-name>
<servlet-name>spring-rest</servlet-name>
</filter-mapping>
Then I tried to invoke my web service by Curl:
curl -d "echoDto=<EchoDto><message>adrian</message></EchoDto>" http://localhost:8001/foo/rest/echo/echoByPost.xml
I found that my incoming object is not created through unmarshalling of JAXB2. Instead, seems that the ctor EchoDto(String) is called which the contains whole request xml message.
(I also tried annotating the parameter with #RequestBody instead but it is even worse, that I cannot even invoke the controller method)
Can someone tell me what I have missed?
The Jaxb2Marshaller is setup correctly with the DTO class, coz I am able to use it as returned model object in case of another GET REST webserivce call.
You need to set the content type of the request and you don't need the echoDto=:
curl -H "Content-Type: application/xml" -d "<EchoDto><message>adrian</message></EchoDto>" http://localhost:8001/foo/rest/echo/echoByPost.xml

How do i change the property of jaxrs endpoint to support "mtom"

I created a RESTful web service, and I want to send binary files to this service without SOAP.
There are some information on CXF website:
XOP
But I can't find a way to get the CXF JAX-RS endpoints, and set an mtom-enabled property.
My Spring config is:
<jaxrs:server id="fis" address="http://172.20.41.40:8080/fis">
<jaxrs:serviceBeans>
<ref bean="FaultInfoResource" />
<ref bean="ExplorationResultResource" />
</jaxrs:serviceBeans>
</jaxrs:server>
<bean id="FaultInfoService" parent="baseService" class="com.dfe.demo.FaultInfoService">
</bean>
<bean id="FaultInfoResource" class="com.dfe.demo.FaultInfoResource">
<property name="faultInfoService" ref="FaultInfoService"/>
</bean>
<bean id="ExplorationResultService" parent="baseService" class="com.dfe.demo.ExplorationResultService">
</bean>
<bean id="ExplorationResultResource" class="com.dfe.demo.ExplorationResultResource">
<property name="explorationResultService" ref="ExplorationResultService"/>
</bean>
And my server class is:
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{"com/dfe/iss/config/applicationContext.xml","com/dfe/demo/yearlyplan/cxf-servlet.xml"});
JAXRSServerFactoryBean fib = (JAXRSServerFactoryBean) ctx.getBean("fis");
fib.create();
Try this:
<beans>
<jaxrs:server id="bookstore1">
<jaxrs:properties>
<entry key="mtom-enabled" value="true"/>
</jaxrs:properties>
</jaxrs:server>
</beans>