cxf spring boot schemalocations configuration - java

I would like to add to webConfWebService configuration class for my spring boot app a schema(xsd).
With xml configuration is as follows:
<jaxws:endpoint address="/nameService" publishedEndpointUrl="">
<jaxws:implementor>
<bean class=name.pkg.ServiceWSImpl" />
</jaxws:implementor>
<jaxws:dataBinding>
<bean class="org.apache.cxf.xmlbeans.XmlBeansDataBinding" />
</jaxws:dataBinding>
<jaxws:serviceFactory>
<bean class="org.apache.cxf.jaxws.support.JaxWsServiceFactoryBean">
<property name="wrapped" value="false" />
</bean>
</jaxws:serviceFactory>
<jaxws:schemaLocations>
<jaxws:schemaLocation>classpath:META-INF/xsd/namexsd1.xsd</jaxws:schemaLocation>
<jaxws:schemaLocation>classpath:META-INF/xsd/namexsd12.xsd</jaxws:schemaLocation>
</jaxws:schemaLocations>
<jaxws:inInterceptors>
<ref bean="authInterceptor" />
</jaxws:inInterceptors>
<jaxws:properties>
<entry key="schema-validation-enabled" value="false" />
</jaxws:properties>
</jaxws:endpoint>
and with annotation i started to create my endPOint as follows and i am blocked to how to import the list of schemalocation, i don't know how to do it:
#Configuration
public class WebServiceConfig {
#Autowired
private Bus bus;
#Bean
public ServletRegistrationBean dispatcherSerlvet() {
return new ServletRegistrationBean(new CXFServlet(), "/services/*");
}
#Bean
public Endpoint namesServiceEndpoint() {
EndpointImpl endpoint = new EndpointImpl(bus, new NameServiceImpl());
endpoint.publish("/Hello");
endpoint.setSchemaLocations(schemaLocations);//HERE ......
return endpoint;
}

It is by adding them in a list as follows:
List<String> schemaLocations = new ArrayList<String>();
Resource resource = resourceLoader.getResource(""classpath:/xsd/nameSchema.xsd);
schemaLocations.add(resource.getFile().getPath());
endpoint.setSchemaLocations(schemaLocations);

Related

Java Spring Interceptor with no XML

I understand that it is possible to configure a Spring application without the use of XML config files, and have commited to this method. I am not sure, however, how to declare HTTP interceptors in this manner. I am using this tutorial, which declares the following 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-2.5.xsd">
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/welcome.htm">welcomeController</prop>
</props>
</property>
<property name="interceptors">
<list>
<ref bean="maintenanceInterceptor" />
<ref bean="executeTimeInterceptor" />
</list>
</property>
</bean>
<bean
class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
<property name="interceptors">
<list>
<ref bean="executeTimeInterceptor" />
</list>
</property>
</bean>
<bean id="welcomeController"
class="com.mkyong.common.controller.WelcomeController" />
<bean class="com.mkyong.common.controller.MaintenanceController" />
<bean id="executeTimeInterceptor"
class="com.mkyong.common.interceptor.ExecuteTimeInterceptor" />
<bean id="maintenanceInterceptor"
class="com.mkyong.common.interceptor.MaintenanceInterceptor">
<property name="maintenanceStartTime" value="23" />
<property name="maintenanceEndTime" value="24" />
<property name="maintenanceMapping" value="/SpringMVC/maintenance.htm" />
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
How to do this in Java? There is no #Interceptor annotation.
SpringApplication.java
#SuppressWarnings("WeakerAccess")
#SpringBootApplication
#PropertySources(value = {#PropertySource("classpath:/application.properties")})
public class SpringbackendApplication {
#Autowired
Environment env;
public static void main(String[] args) {
SpringApplication.run(SpringbackendApplication.class, args);
initializeFirebase();
}
#Bean
public ViewResolver getViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
#Bean
public UserController userController() {
UserController userController = new UserController(getUserDAO(), getYodleeDAO());
userController.setCobrandSession(cobrandSession());
userController.setUserSessionManager(userSessionManager());
userController.setAccountsService(accountsService());
userController.setTransactionsService(transactionsService());
return userController;
}
#Bean
public TestController testController() {
TestController testController = new TestController();
testController.setCobrandSession(cobrandSession());
testController.setUserSessionManager(userSessionManager());
testController.setAccountsService(accountsService());
testController.setTransactionsService(transactionsService());
return testController;
}
#Bean
public CobrandSession cobrandSession() {
CobrandSession cobrandSession = new CobrandSession();
cobrandSession.setApiBase(this.env.getProperty("API_BASE"));
cobrandSession.setLogin(this.env.getProperty("LOGIN"));
cobrandSession.setPassword(this.env.getProperty("PASSWORD"));
cobrandSession.setLocale(this.env.getProperty("LOCALE"));
cobrandSession.setRestTemplate(restTemplate());
cobrandSession.setGson(gson());
return cobrandSession;
}
#Bean
public AccountsService accountsService() {
AccountsService accountsService = new AccountsService();
accountsService.setApiBase(this.env.getProperty("API_BASE"));
accountsService.setRestTemplate(restTemplate());
accountsService.setGson(gson());
return accountsService;
}
#Bean
public RestTemplate restTemplate() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setOutputStreaming(false); // If we don't turn this off, we may get HttpRetryException on 401's.
return new RestTemplate(factory);
}
#Bean
public Gson gson() {
return new Gson();
}
}
To move your Spring beans defined in an XML file to a Configuration class (marked with #Configuration) you would need something like this:
#Configuration
public class MyConfig {
#Bean(name="executeTimeInterceptor")
public ExecuteTimeInterceptor getExecuteTimeInterceptor() {
return new com.mkyong.common.interceptor.ExecuteTimeInterceptor();
}
#Bean(name="maintenanceInterceptor")
public MaintenanceInterceptor getMaintenanceInterceptor(#Value("${properties.maintenanceStartTime}") int maintenanceStartTime,
#Value("${properties.maintenanceEndTime}") int maintenanceEndTime,
#Value("${properties.maintenanceMapping}") String maintenanceMapping) {
MaintenanceInterceptor myInt = new MaintenanceInterceptor();
myInt.setMaintenanceStartTime(maintenanceStartTime);
myInt.setmMaintenanceEndTime(maintenanceEndTime);
myInt.setMaintenanceMapping(maintenanceMapping);
return myInt;
}
}
...then in some propertiesFile.properties on the classpath add these...
properties.maintenanceStartTime=23
properties.maintenanceEndTime=24
properties.maintenanceMapping=/SpringMVC/maintenance.htm
EDIT
I see you are getting your props from the Environment, so instead of #Value injection, use the way you have it in your code right now.
You have to override WebMvcConfigurerAdapter.addInterceptors() method and add your interceptors:
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new CustomInterceptor());
}
Don't forget to mark your class with #Configuration

Spring utilizing Mongo implementation over JPA

I am fairly new to the Spring Framework and have been having some trouble setting up the project I am currently working on. I need to be able to connect to two different databases one being MongoDB and the other being MSSQL. I am using JPA to connect to the MSSQL.
The problem that I am encountering is that it appears to be trying to make calls to the Mongo database when I want it to make calls to the MSSQL and I'm not really sure how to tell it what to read from. I have seen the posts advising to use the #Qualifier annotation to direct it to the correct implementation, but I don't think that that will work for my case.
#RestController
#RequestMapping("/software")
public class SoftwareEndpoint {
#Autowired
SoftwareRepository repo;
/**********************************************************************************
********************************MSSQL calls****************************************
***********************************************************************************/
#RequestMapping(value="/all",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON)
String getAllSoftware(){
System.out.println("Here1");
List<Software> allSoftware = (List<Software>) repo.findAll();
System.out.println("Here2");
//rest of method and class
Above shows a snippet of my controller class that has an instance of my SoftwareRepository. I also print to the out stream before and after the db call.
The out stream only shows "Here1", goes on to print out this line:
2016-10-04 07:35:39.810 INFO 4236 --- [nio-8080-exec-2] org.mongodb.driver.cluster : No server chosen by ReadPreferenceServerSelector{readPreference=primary} from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, all=[ServerDescription{address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused: connect}}]}. Waiting for 30000 ms before timing out
and then throws an exception on timeout.
I do not have a mongo instance running locally, however there will be on where the application is being deployed, but I don't believe that this is the problem because on hitting that endpoint, it shouldn't be making a call to the Mongo database, it should be trying to reach out to MSSQL.
TLDR: How do I specify which database implementation for Spring to use for a specific repository or database call?
You can connect to different databases in spring based on the configuration in context.
The below code is for connecting to MySql and Mongo DB. You can substitute MySql with MSSQL provided you have the JDBC for it. Check http://jdbforms.sourceforge.net/UsersGuide/html/ch20s02.html for what the properties for JDBC connection mean.
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg ref="mySqldataSource" /> <!-- Change the datasource to MSSQL-->
</bean>
<bean id="mySqldataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="removeAbandoned">
<value>true</value>
</property>
<property name="removeAbandonedTimeout">
<value>30</value>
</property>
<property name="driverClassName">
<value>MSSQL_DRIVER_CLASS_NAME</value>
</property>
<property name="url">
<value>MSSQL_DATABASE_URL</value>
</property>
<property name="username">
<value>MSSQL_DB_USER_NAME</value>
</property>
<property name="password">
<value>MSSQL_DB_PASSWORD</value>
</property>
<property name="maxIdle">
<value>10</value>
</property>
<property name="maxActive">
<value>10</value>
</property>
<property name="maxWait">
<value>100000</value>
</property>
<property name="testOnBorrow">
<value>false</value>
</property>
<property name="testWhileIdle">
<value>false</value>
</property>
<property name="timeBetweenEvictionRunsMillis">
<value>60000</value>
</property>
<property name="minEvictableIdleTimeMillis">
<value>60000</value>
</property>
<property name="numTestsPerEvictionRun">
<value>1</value>
</property>
<property name="defaultTransactionIsolation" value="1" />
<property name="poolPreparedStatements" value="true" />
<property name="maxOpenPreparedStatements" value="1" />
</bean>
<bean class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"></bean>
Below is for connecting to mongodb
<mongo:db-factory dbname="mongoDbName" host="mongoServer" port="mongoPort"/>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
</bean>
<mongo:repositories base-package="com.test.repoPackage"/> <!-- Package containing the mongo repository interfaces -->
Now you can use the repositories provided by spring.
EDIT 1: Suppose name of config is springConfig.properties. In the above example for the properties dbname, host and port in mongo:db-factory, you would want the values to be configured in springConfig.properties. So lets name them below:
mongoServer = xxx.xx.xxx.xxx
mongoPort = 27017
mongoDb = testDb
Now the context file needs to be modified to import the springConfig.properties. this is done as below in the context file:
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" >
<property name="locations" >
<list>
<value>classpath:/log4j.properties</value>
<value>classpath:/springConfig.properties</value>
</list>
</property>
</bean>
The bean mongo:db-factory would now look like:
<mongo:db-factory dbname="${mongoDb}" host="${mongoServer}" port="${mongoPort}"/>
Notice that the "keys" from config (dbname, host and port) are represented insde ${}. This will replace with values in config for the keys.
You need to have two separated config for JPA. Don't forget to disable JPA auto configuration.
#SpringBootApplication(
exclude={
DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class,
HibernateJpaAutoConfiguration.class
}
)
Below is example for two different sql database. Could be easily adapted for your needs (when second datasource is mongo).
First one:
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(
entityManagerFactoryRef = "sellitEntityManagerFactory",
transactionManagerRef = "sellitTransactionManager",
basePackages = { "co.sellit.core.api.repository.sellit" }
)
public class JpaSellitConfig {
#Bean
#ConfigurationProperties(prefix="spring.datasource.sellit")
public DataSourceProperties sellitDataSourceProperties() {
return new DataSourceProperties();
}
#Bean
#ConfigurationProperties(prefix="spring.hikaricp.sellit")
public HikariConfig sellitHikariConfig() {
HikariConfig hikariConfig = new HikariConfig();
return hikariConfig;
}
#Bean
public DataSource sellitDataSource(
#Qualifier("sellitHikariConfig") HikariConfig sellitHikariConfig,
#Qualifier("sellitDataSourceProperties") DataSourceProperties sellitDataSourceProperties) {
sellitHikariConfig.setDriverClassName(sellitDataSourceProperties.getDriverClassName());
sellitHikariConfig.setJdbcUrl(sellitDataSourceProperties.getUrl());
sellitHikariConfig.setUsername(sellitDataSourceProperties.getUsername());
sellitHikariConfig.setPassword(sellitDataSourceProperties.getPassword());
sellitHikariConfig.setConnectionTestQuery("SELECT 1");
HikariDataSource hikariDataSource = new HikariDataSource(sellitHikariConfig);
return hikariDataSource;
}
#Bean
#ConfigurationProperties(prefix="spring.jpa.sellit")
public JpaVendorAdapter sellitJpaVendorAdapter() {
HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
return jpaVendorAdapter;
}
#Bean
#Autowired
public EntityManagerFactory sellitEntityManagerFactory(
#Qualifier("sellitDataSource") DataSource sellitDataSource,
#Qualifier("sellitJpaVendorAdapter") JpaVendorAdapter sellitJpaVendorAdapter) {
LocalContainerEntityManagerFactoryBean lemf = new LocalContainerEntityManagerFactoryBean();
lemf.setDataSource(sellitDataSource);
lemf.setJpaVendorAdapter(sellitJpaVendorAdapter);
lemf.setPackagesToScan("co.sellit.core.api.entity.sellit");
lemf.setPersistenceUnitName("sellitPersistenceUnit");
lemf.afterPropertiesSet();
return lemf.getObject();
}
#Bean
#Autowired
public EntityManager sellitDataSourceEntityManager(
#Qualifier("sellitEntityManagerFactory") EntityManagerFactory sellitEntityManagerFactory) {
return sellitEntityManagerFactory.createEntityManager();
}
#Bean
#Autowired
#Qualifier("sellitTransactionManager")
public PlatformTransactionManager sellitTransactionManager(
#Qualifier("sellitEntityManagerFactory") EntityManagerFactory sellitEntityManagerFactory) {
return new JpaTransactionManager(sellitEntityManagerFactory);
}
}
Second one:
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(
entityManagerFactoryRef = "ofEntityManagerFactory",
transactionManagerRef = "ofTransactionManager",
basePackages = { "co.sellit.core.api.repository.openfire" }
)
public class JpaOpenfireConfig {
#Bean
#ConfigurationProperties(prefix="spring.datasource.openfire")
public DataSourceProperties ofDataSourceProperties() {
return new DataSourceProperties();
}
#Bean
#ConfigurationProperties(prefix="spring.hikaricp.openfire")
public HikariConfig ofHikariConfig() {
HikariConfig hikariConfig = new HikariConfig();
return hikariConfig;
}
#Bean
public DataSource ofDataSource(
#Qualifier("ofHikariConfig") HikariConfig ofHikariConfig,
#Qualifier("ofDataSourceProperties") DataSourceProperties ofDataSourceProperties) {
ofHikariConfig.setDriverClassName(ofDataSourceProperties.getDriverClassName());
ofHikariConfig.setJdbcUrl(ofDataSourceProperties.getUrl());
ofHikariConfig.setUsername(ofDataSourceProperties.getUsername());
ofHikariConfig.setPassword(ofDataSourceProperties.getPassword());
ofHikariConfig.setConnectionTestQuery("SELECT 1");
HikariDataSource hikariDataSource = new HikariDataSource(ofHikariConfig);
return hikariDataSource;
}
#Bean
#ConfigurationProperties(prefix="spring.jpa.openfire")
public JpaVendorAdapter ofJpaVendorAdapter() {
HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
return jpaVendorAdapter;
}
#Bean
#Autowired
public EntityManagerFactory ofEntityManagerFactory(
#Qualifier("ofDataSource") DataSource ofDataSource,
#Qualifier("ofJpaVendorAdapter") JpaVendorAdapter ofJpaVendorAdapter) {
LocalContainerEntityManagerFactoryBean lemf = new LocalContainerEntityManagerFactoryBean();
lemf.setDataSource(ofDataSource);
lemf.setJpaVendorAdapter(ofJpaVendorAdapter);
lemf.setPackagesToScan("co.sellit.core.api.entity.openfire");
lemf.setPersistenceUnitName("ofPersistenceUnit");
lemf.afterPropertiesSet();
return lemf.getObject();
}
#Bean
#Autowired
public EntityManager ofDataSourceEntityManager(
#Qualifier("ofEntityManagerFactory") EntityManagerFactory ofEntityManagerFactory) {
return ofEntityManagerFactory.createEntityManager();
}
#Bean
#Autowired
#Qualifier("ofTransactionManager")
public PlatformTransactionManager ofTransactionManager(
#Qualifier("ofEntityManagerFactory") EntityManagerFactory ofEntityManagerFactory) {
return new JpaTransactionManager(ofEntityManagerFactory);
}
}
So repositories from package co.sellit.core.api.repository.sellit will use sellit db
But repositories from package co.sellit.core.api.repository.openfire will use openfire database.
UPDATE (xml config version)
<bean id="openfireDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/openfire?characterEncoding=UTF-8" />
</bean>
<bean id="sellitDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/sellit?characterEncoding=UTF-8" />
</bean>
<bean id="openfireSessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="openfireDataSource" />
<property name="packagesToScan" value="co.sellit.core.api.repository.openfire" />
<property name="hibernateProperties">
<props>
...
</props>
</property>
</bean>
<bean id="sellitSessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="sellitDataSource" />
<property name="packagesToScan" value="co.sellit.core.api.repository.sellit" />
<property name="hibernateProperties">
<props>
...
</props>
</property>
</bean>
<bean id="openfireTxnManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="openfireSessionFactory" />
</bean>
<bean id="sellitTxnManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sellitSessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="openfireTxnManager" />
<tx:annotation-driven transaction-manager="sellitTxnManager" />

How to set bean using java config in spring

I have below details in spring xml file. Now I want to convert it into spring java config bean.
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="test" />
<property name="port" value="111" />
<property name="username" value="test#gmail.com" />
<property name="password" value="test123" />
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.starttls.enable">true</prop>
</props>
</property>
</bean>
<bean id="utilityObject" class="com.ezone.utility.TestUtility">
<property name="mailSender" ref="mailSender" />
</bean>
Converted mailSender this bean as below. But How to convert utilityObject in java config spring bean. I am new in this.
#Bean(name="mailSender",autowire=Autowire.BY_NAME)
public JavaMailSenderImpl mailConfiguration(){
JavaMailSenderImpl mail = new JavaMailSenderImpl();
mail.setHost("test");
mail.setPort(111);
mail.setUsername("test#gmail.com");
mail.setPassword("test123");
Properties javaMailProperties = new Properties();
javaMailProperties.put("mail.smtp.auth", "true");
javaMailProperties.put("mail.smtp.starttls.enable", "true");
javaMailProperties.setProperty("mail.smtp.auth", "true");
javaMailProperties.setProperty("mail.smtp.starttls.enable", "true");
mail.setJavaMailProperties(javaMailProperties);
return mail;
}
How can I define below bean :
<bean id="utilityObject" class="com.ezone.utility.TestUtility">
<property name="mailSender" ref="mailSender" />
</bean>
The above bean has the reference of mailSender.
You can either put a parameter on the #Bean method, which will get injected:
#Bean
public TestUtility utilityObject(JavaMailSender mailConfiguration) {
return new TestUtility(mailConfiguration);
}
or call from one #Bean method in an #Configuration to another; Spring will proxy them and make sure the singleton behavior gets applied:
#Bean
public TestUtility utilityObject() {
return new TestUtility(mailConfiguration());
}
I think the first one is a bit less magic, but either approach should work.
The methods annotated with #Bean can be called from other methods. Spring makes proxy for #Configuration class and singletons are created only once.
#Bean
public TestUtility utilityObject() {
TestUtility uo = new TestUtility();
uo.setMailSender(mailConfiguration());
return uo;
}
See details http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-java-further-information-java-config
Use #configuration for the JavaMailSenderImpl class
Refer : http://www.tutorialspoint.com/spring/spring_java_based_configuration.htm
EDIT
#Bean
public TestUtility getUtilityObject() {
return new TestUtility(mailConfiguration());
}

How Write Java Configuration for this XML configuration.?

I am in the middle of converting my appconfig.xml tp JavaConfigurations(AnnotationConfigs). I did converting most of the beans into JavaConfig. But I am got stuck with couple of beans which are listed below. Could some one help me on this..??
1.The Bean has a list element which takes values from a properties file..
The XML Configuration is :
<bean id="propertyCommons"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:dbUser.properties</value>
</list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="true" />
</bean>
How do we convert this to java Config..(especially taking values from dbUser.properties?
2.How do we convert the following factory configuration to JavaConfigs?
.
.
.
<bean id="oozieJobFactoryBean" class="com.mycompany.product.dfe.main.OozieJobFactoryBean" />
<bean id="cmdArgs" class="com.mycompany.product.dfe.main.CmdArgs"
scope="prototype" />
<bean id="oozieJob" factory-bean="oozieJobFactoryBean"
factory-method="createJob" scope="prototype">
<constructor-arg ref="cmdArgs" />
</bean>
.
.
.
3. Also the following Configuration ..
.
.
.
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="productPU" />
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaPropertyMap">
<map>
<entry key="hibernate.cache.use_second_level_cache" value="true" />
<entry key="hibernate.cache.use_query_cache" value="true" />
<entry key="hibernate.cache.provider_class" value="net.sf.ehcache.hibernate.SingletonEhCacheProvider" />
<entry key="hibernate.show_sql" value="false" />
<entry key="hibernate.format_sql" value="false" />
<entry key="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
<entry key="javax.persistence.validation.mode" value="NONE" />
<entry key="hibernate.connection.characterEncoding" value="utf8" />
</map>
</property>
</bean>
.
.
.
Please help me on this am new to spring.. :)
Thanks in Advance...
Noushad Ali.
1.PropertyPlaceholderConfigurer
#Configuration
#PropertySource(value = "spring/test5.properties")
class Config {
#Bean
PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
PropertySourcesPlaceholderConfigurer c = new PropertySourcesPlaceholderConfigurer();
c.setIgnoreUnresolvablePlaceholders(true);
return c;
}
...
OOzieJobFactory
class Config {
#Bean
#Scope("prototype")
CmdArgs cmdArgs() {
return new CmdArgs();
}
#Bean
#Scope("prototype")
OozieJobFactory oozieJobFactory() {
return new OozieJobFactory();
}
#Bean
OozieJob oozieJob(OozieJobFactory factory, CmdArgs cmdArgs) {
return factory.createJob(cmdArgs);
}
}
EntityManager
class Config {
#Bean
LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean() {
LocalContainerEntityManagerFactoryBean b = new LocalContainerEntityManagerFactoryBean();
b.setPersistenceUnitName("productPU");
...
return b;
}
#Bean
JpaTransactionManager jpaTransactionManager(LocalContainerEntityManagerFactoryBean emf) {
JpaTransactionManager tm = new JpaTransactionManager();
tm.setEntityManagerFactory(emf);
return tm;
}

How to set timeout in Spring WebServiceTemplate

I am using org.springframework.ws.client.core.WebServiceTemplate for making Web Service calls. How can i configure timeout for the call.
If you are using Spring Webservices 2.1.0 version, You can set timeout using HttpComponentsMessageSender.
CommonsHttpMessageSender are deprecated and not recommended by Spring anymore.
The way I have it implemented, I define my WebServiceTemplate to use HttpComponentsMessageSender.
Values are in Milliseconds
<bean id="webServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
<property name="defaultUri" value="${endpoint.url}" />
<property name="marshaller" ref="marshaller" />
<property name="unmarshaller" ref="unmarshaller" />
<property name="messageSender">
<bean class="org.springframework.ws.transport.http.HttpComponentsMessageSender">
<property name="connectionTimeout" value="1200000" />
<property name="readTimeout" value="1200000" />
</bean>
</property>
</bean>
Just Make sure you have in your pom file, you added the following
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.2.1</version>
<scope>compile</scope>
</dependency>
Same as Sathish answer, but programmatically (Spring 4+):
#Component
public class MyWebServiceGatewaySupport extends WebServiceGatewaySupport
{
#Value("${my.ws.readtimeout}")
private String readTimeout;
#Value("${my.ws.connectiontimeout}")
private String connectionTimeout;
Object marshalSendAndReceive(String endpoint, Object requestPayload)
{
WebServiceTemplate wsTemplate = this.getWebServiceTemplate();
WebServiceMessageSender[] senders = wsTemplate.getMessageSenders();
for (WebServiceMessageSender sender: senders)
{
try
{
int readTimeoutMsec = Integer.parseInt(readTimeout);
int connTimeoutMsec = Integer.parseInt(connectionTimeout);
HttpComponentsMessageSender httpSender = (HttpComponentsMessageSender) sender;
httpSender.setReadTimeout(readTimeoutMsec);
httpSender.setConnectionTimeout(connTimeoutMsec);
}
catch (ClassCastException|NumberFormatException cex)
{
logger.warn("Cannot set WS timeout: " + cex.getMessage());
}
}
return wsTemplate.marshalSendAndReceive(endpoint, requestPayload);
}
}
Since Spring Webservices 2.2, you can also use Spring's ClientHttpRequestMessageSender:
#Service
public class CustomWebServiceImpl extends WebServiceGatewaySupport implements CustomWebService {
private static final int CONNECTION_TIMEOUT = (10 * 1000);
private static final int READ_TIMEOUT = (10 * 1000);
public CustomWebServiceImpl() {
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setConnectTimeout(CONNECTION_TIMEOUT);
requestFactory.setReadTimeout(READ_TIMEOUT);
setMessageSender(new ClientHttpRequestMessageSender(requestFactory));
}
(...)
}
(no dependency to Apache HTTP Components required)
The below code worked for me.
#Bean
public YourClassImpl yourClassImpl(Jaxb2Marshaller marshaller, HttpComponentsMessageSender httpComponentsMessageSender) {
YourClassImpl client = new YourClassImpl();
client.setDefaultUri(PiiProperties.SOAP_ACTION.getValue());
client.setMarshaller(marshaller);
client.setUnmarshaller(marshaller);
client.setMessageSender(httpComponentsMessageSender);
return client;
}
#Bean
public HttpComponentsMessageSender httpComponentsMessageSender() {
HttpComponentsMessageSender sender = new HttpComponentsMessageSender();
sender.setReadTimeout(1000);
sender.setConnectionTimeout(1000);
return sender;
}
If you want that kind of control, you can
either switch to CommonsHttpMessageSender, which uses the Jakarta Commons
HttpClient
or subclass HttpUrlConnectionMessageSender and in the
prepareConnection(HttpURLConnection) method call
UrlConnection.setReadTimeOut(int)
That's how I did:
#Configuration
public class MunisServiceConfig {
#Value("${service.uri}")
private String soapUri;
#Bean
Jaxb2Marshaller jaxb2Marshaller() {
Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();
jaxb2Marshaller.setContextPath(CheckStatePayment.class.getPackage().getName());
return jaxb2Marshaller;
}
#Bean
public WebServiceTemplate munisService() {
WebServiceTemplate template = new WebServiceTemplate();
template.setMarshaller(jaxb2Marshaller());
template.setUnmarshaller(jaxb2Marshaller());
template.setDefaultUri(soapUri);
HttpComponentsMessageSender httpComponentsMessageSender = new HttpComponentsMessageSender();
httpComponentsMessageSender.setReadTimeout(3000);
httpComponentsMessageSender.setConnectionTimeout(5000);
template.setMessageSender(httpComponentsMessageSender);
return template;
}
}
This article will probably sort you out:
http://onebyteatatime.wordpress.com/2009/03/19/how-to-set-socket-timeout-using-spring-webservicetemplate/
The way I have it implemented, I define my WebServiceTemplate to use CommonsHttpMessageSender:
<bean id="webServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
<constructor-arg ref="messageFactory" />
<property name="messageSender">
<bean
class="org.springframework.ws.transport.http.CommonsHttpMessageSender">
</bean>
</property>
</bean>
Then, in code, I get the messageSender and set the timeout on it. You could equally do this in your xml.
CommonsHttpMessageSender messageSender = (CommonsHttpMessageSender)webServiceTemplate.getMessageSenders()[0];
messageSender.getHttpClient().getParams().setSoTimeout(timeoutMillis);
This code works with Spring Boot (verified on 2.1.5.RELEASE):
#Configuration
public class ExampleServiceClientConfiguration {
#Value("${example-service.uri}")
private String exampleServiceUri;
#Value("${example-service.timeout:120}")
private int exampleServiceTimeout;
#Bean
public ExampleServiceClient exampleServiceClient() {
ExampleServiceClient client = new ExampleServiceClient();
client.setMessageSender(httpUrlConnectionMessageSender());
client.setDefaultUri(exampleServiceUri);
client.setMarshaller(marshaller());
client.setUnmarshaller(marshaller());
return client;
}
#Bean
HttpUrlConnectionMessageSender httpUrlConnectionMessageSender() {
HttpUrlConnectionMessageSender sender = new HttpUrlConnectionMessageSender();
Duration timeout = Duration.ofSeconds(exampleServiceTimeout);
sender.setReadTimeout(timeout);
sender.setConnectionTimeout(timeout);
return sender;
}
#Bean
public Jaxb2Marshaller marshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setContextPath(ObjectFactory.class.getPackageName());
return marshaller;
}
}
For the CommonsHttpMessageSender, we can set the timeout in the following way:
<bean id="httpParams" class="org.apache.commons.httpclient.params.HttpClientParams">
<!-- Timeout in milliseconds: in this case 1 minute -->
<property name="soTimeout" value="60000" />
</bean>
<bean id="httpClient" class="org.apache.commons.httpclient.HttpClient">
<property name="params" ref="httpParams" />
</bean>
<!-- Define the message sender used by all web service templates -->
<bean id="webServiceMessageSender" class="org.springframework.ws.transport.http.CommonsHttpMessageSender">
<constructor-arg>
<ref bean="httpClient"/>
</constructor-arg>
</bean>
and ref the webServiceMessageSender as below:
<bean id="genericWebServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
<property name="messageSender" ref="webServiceMessageSender"/>
</bean>

Categories

Resources