Posts Tagged ‘Spring’
Dynamic serviceUrl with Spring’s HttpInvokerProxyFactoryBean
Abstract
How to set dynamically the URL used by a HttpInvokerProxyFactoryBean
in a Spring-deployed WAR?
Detailed Case
I have to deploy a GWT/GXT application, calling two distant services:
a remote EJB
a service accessed through Spring Remoting
Here is the Spring configuration file I firstly used:
<util:properties id="jndiProperties" location="classpath:jndi.properties"/> <jee:remote-slsb id="myRemoteEJBService" jndi-name="ejb.remote.myRemoteService" business-interface="lalou.jonathan.myRemoteEJBService" environment-ref="jndiProperties" cache-home="false" lookup-home-on-startup="false" refresh-home-on-connect-failure="true" /> <bean id="mySpringRemoteService" class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean"> <property name="serviceInterface" value="lalou.jonathan.services.mySpringRemoteService" /> <property name="serviceUrl" value="${spring.remote.service.url}"/> </bean>
Unhappily, even though the remote EJB is retrieved (which proves that the jndi file is available in the classpath and rightly loaded), the Spring Remote service is not. I had to write the URL in hard in the configuration file… This is not very efficient when you work in a large team, with different production and testings environments!
This is the log when myRemoteEJBService
bean is loaded:
2010-08-17 16:05:42,937 DEBUG support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'myRemoteEJBService' 2010-08-17 16:05:42,937 DEBUG support.DefaultListableBeanFactory - Creating instance of bean 'myRemoteEJBService' 2010-08-17 16:05:42,937 DEBUG support.DefaultListableBeanFactory - Eagerly caching bean 'myRemoteEJBService' to allow for resolving potential circular references 2010-08-17 16:05:42,937 DEBUG support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'jndiProperties' 2010-08-17 16:05:42,937 DEBUG support.DefaultListableBeanFactory - Invoking afterPropertiesSet() on bean with name 'myRemoteEJBService' 2010-08-17 16:05:42,937 DEBUG framework.JdkDynamicAopProxy - Creating JDK dynamic proxy: target source is EmptyTargetSource: no target class, static 2010-08-17 16:05:42,953 DEBUG support.DefaultListableBeanFactory - Finished creating instance of bean 'myRemoteEJBService'
That is the log when mySpringRemoteService
is loaded:
2010-08-17 16:05:42,968 DEBUG support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'mySpringRemoteService' 2010-08-17 16:05:42,968 DEBUG support.DefaultListableBeanFactory - Creating instance of bean 'mySpringRemoteService' 2010-08-17 16:05:42,984 DEBUG support.DefaultListableBeanFactory - Eagerly caching bean 'mySpringRemoteService' to allow for resolving potential circular references 2010-08-17 16:05:43,234 DEBUG support.DefaultListableBeanFactory - Invoking afterPropertiesSet() on bean with name 'mySpringRemoteService' 2010-08-17 16:05:43,250 DEBUG framework.JdkDynamicAopProxy - Creating JDK dynamic proxy: target source is EmptyTargetSource: no target class, static 2010-08-17 16:05:43,250 DEBUG support.DefaultListableBeanFactory - Finished creating instance of bean 'mySpringRemoteService'
You can notice that no mention to jndiProperties
appears. Here is the key of the problem: jndiProperties
is considered as a bean among others, which cannot be accessed easyly from the HttpInvokerProxyFactoryBean
.
Fix
To fix the issue, you have to add an actual property holder in Spring XML configuration file, ie after:
<util:properties id="jndiProperties" location="classpath:jndi.properties"/>
add an instanciation of PropertyPlaceholderConfigurer
:
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jndi.properties"/> </bean>
Transaction Management with Spring in AOP
Case
You have a couple of Hibernate DAOs, in which a huge amount of code is duplicated: begin transactions, try/catch, close transactions, etc.
You would like to factorize your code.
Fix
- Define a
SessionFactory
, let’s sayhibernateSessionFactory
, with your own settings.<bean id="hibernateSessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">(...)</bean>
- Define a
TransactionManager
:<bean id="hibernateTransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory"> <ref local="hibernateSessionFactory" /> </property> </bean>
- Define transactions advices:
<tx:advice id="hibTxManager" transaction-manager="hibernateTransactionManager"> <tx:attributes> <tx:method name="*" propagation="NEVER" read-only="true" isolation="READ_COMMITTED" rollback-for="find*" no-rollback-for="dontFind*"/> </tx:attributes> </tx:advice>
name="*"
–> the aspect will apply to all methods. You may filter on patterns such as find*, get*, save*, etc.propagation="NEVER"
–> hints the propagation level. Available options areREQUIRED, SUPPORTS, MANDATORY,REQUIRES_NEW, NOT_SUPPORTED, NEVER, NESTED
.isolation="READ_COMMITTED"
–>rollback-for="find*"
–> rollback all transactions following the given patternno-rollback-for="dontFind*"
–> exceptions for rollbacks- Define the AOP configuration:
<aop:config> <aop:pointcut id="hibOperation" expression="execution(* com.lalou.jonathan.dao.hibernate.Hibernate*.*(..))" /> <aop:advisor pointcut-ref="hibOperation" advice-ref="hibTxManager" /> </aop:config>
Many thanks to Jean-Pierre ISOARD for his help on this subject.
Deploy a webservice under Mule ESB using CXF
This short tutorial is aimed at showing the main steps allowing to deploy a WebService, using CXF framework, under a Mule ESB instance.
Java code
Declare an interface:
@WebService public interface BasicExampleServices { @WebResult(name = "myReturnedInteger") Integer getInteger(@WebParam(name="myInteger") Integer myInteger); }
Implement this interface:
@WebService(endpointInterface = "com.lalou.jonathan.services.BasicExampleServices", serviceName = "basicExampleServices") public class WSBasicExampleServices implements BasicExampleServices { public Integer getInteger(Integer param) { return 12345; } }
XML files
Create a Spring config file ws-basicExample.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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <bean id="basicExampleService" scope="singleton"/> </beans>
Create a Mule configuration file ws-basicExample-config.xml
:
<?xml version="1.0" encoding="UTF-8" ?> <mule xmlns="http://www.mulesource.org/schema/mule/core/2.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:spring="http://www.springframework.org/schema/beans" xmlns:management="http://www.mulesource.org/schema/mule/management/2.2" xmlns:stdio="http://www.mulesource.org/schema/mule/stdio/2.2" xmlns:cxf="http://www.mulesource.org/schema/mule/cxf/2.2" xmlns:jetty="http://www.mulesource.org/schema/mule/jetty/2.2" xsi:schemaLocation="http://www.mulesource.org/schema/mule/management/2.2 http://www.mulesource.org/schema/mule/management/2.2/mule-management.xsd http://www.mulesource.org/schema/mule/core/2.2 http://www.mulesource.org/schema/mule/core/2.2/mule.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.mulesource.org/schema/mule/vm/2.2 http://www.mulesource.org/schema/mule/vm/2.2/mule-vm.xsd http://www.mulesource.org/schema/mule/cxf/2.2 http://www.mulesource.org/schema/mule/cxf/2.2/mule-cxf.xsd http://www.mulesource.org/schema/mule/stdio/2.2 http://www.mulesource.org/schema/mule/stdio/2.2/mule-stdio.xsd"> <spring:beans> <spring:import resource="ws-basicExample.xml"/> </spring:beans> <model name="wsBasicExampleModel"> <service name="wsBasicExampleService"> <inbound> <cxf:inbound-endpoint address="http://localhost:8282/services/basicExampleServices"/> </inbound> <component> <spring-object bean="basicExampleService"/> </component> </service> </model> </mule>
Checks
- Run the Mule, pointing your config file.
- In your favorite webbrowser, open the URL:
http://localhost:8282/services/basicExampleServices?wsdl
- You can also execute a runtime test:
public class WSBasicExampleServicesRuntimeTest { private BasicExampleServices basicExampleServices; @Before public void setup() { JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean(); factory.getInInterceptors().add(new LoggingInInterceptor()); factory.getOutInterceptors().add(new LoggingOutInterceptor()); factory.setServiceClass(BasicExampleServices.class); factory.setAddress("http://localhost:8282/services/basicExampleServices"); basicExampleServices = (BasicExampleServices) factory.create(); } @Test public void testGetInteger() { final Integer expectedAnswer = 12345; final Integer actualAnswer; final Integer param = 912354; actualAnswer = basicExampleServices.getInteger(param); assertNotNull(actualAnswer); assertEquals(expectedAnswer, actualAnswer); } }
The webservice contract is expected to be displayed.
GWT: call a remote EJB with Spring lookup
Abstract
Let’s assume you have followed the article “Basic RPC call with GWT“. Now you would like to call an actual EJB 2 as remote, via a Spring lookup.
Let’s say: you have an EJB MyEntrepriseComponentEJB
, which implements an interface MyEntrepriseComponent
. This EJB, generates a remote MyEntrepriseComponentRemote
.
Entry Point
In myApplication.gwt.xml
entry point file, after the line:
<inherits name='com.google.gwt.user.User'/>
add the block:
<inherits name='com.google.gwt.user.User' /> <inherits name="com.google.gwt.i18n.I18N" /> <inherits name="com.google.gwt.http.HTTP" />
Add the line:
<servlet path='/fooService.do'/>
Client
Under the *.gwt.client
folder:
Update the service interface. Only the annotation parameter is amended:
@RemoteServiceRelativePath("services/fooService") public interface FooService extends RemoteService { public String getHelloFoo(String fooName); }
You have nothing to modify in asynchronous call interface (FooServiceAsync
).
Server
Under the *.gwt.server folder
, update the implementation for service interface:
Change the super-class, replacing RemoteServiceServlet
with GWTSpringController
:
public class FooServiceImpl extends GWTSpringController implements FooService { public FooServiceImpl() { // init } }
Add new field and its getter/setter:
// retrieved via Spring private myEntrepriseComponent myEntrepriseComponent; public myEntrepriseComponent getMyEntrepriseComponent() { return myEntrepriseComponent; } public void setmyEntrepriseComponent(myEntrepriseComponent _myEntrepriseComponent) { myEntrepriseComponent = _myEntrepriseComponent; }
Write the actual call to EJB service:
public String getHelloFoo(String fooName) { return myEntrepriseComponent.getMyDataFromDB(); } }
web.xml
Fill the web.xml
file:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <!-- Spring --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>gwt-controller</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>gwt-controller</servlet-name> <url-pattern>/myApplication/services/*</url-pattern> </servlet-mapping> <!-- Default page to serve --> <welcome-file-list> <welcome-file>MyApplicationGwt.html</welcome-file> </welcome-file-list> </web-app>
JNDI
Add a jndi.properties
file in src/resources folder
:
java.naming.provider.url=t3://localhost:12345 java.naming.factory.initial=weblogic.jndi.WLInitialContextFactory java.naming.security.principal=yourLogin java.naming.security.credentials=yourPassword weblogic.jndi.enableDefaultUser=true
These properties will be used by Spring to lookup the remote EJB. The last option is very important, otherwise you may happen to face issues with EJB if they were deployed under WebLogic.
WEB-INF
In the WEB-INF
folder, add an applicationContext.xml
file:
<?xml version="1.0" encoding="UTF-8"?> <beans> <util:properties id="jndiProperties" location="classpath:jndi.properties" /> <jee:remote-slsb id="myEntrepriseComponentService" jndi-name="ejb.jonathan.my-entreprise-component" business-interface="lalou.jonathan.myApplication.services.myEntrepriseComponent" environment-ref="jndiProperties" cache-home="false" lookup-home-on-startup="false" refresh-home-on-connect-failure="true" /> </beans>
Add a gwt-controller-servlet.xml
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: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"> <bean> <property name="order" value="0" /> <property name="mappings"> <value> /fooService=fooServiceImpl </value> </property> </bean> <bean id="fooServiceImpl" class="lalou.jonathan.myApplication.web.gwt.server.FooServiceImpl"> <property name="myEntrepriseComponent" ref="myEntrepriseComponentService" /> </bean> </beans>
Of course, if your servlet mapping name in web.xml
is comoEstasAmigo, then rename gwt-controller-servlet.xml
as comoEstasAmigo-servlet.xml
😉
Build and deploy
Now you can compile, package your war and deploy under Tomcat or WebLogic. WebLogic server may raise an error:
java.rmi.AccessException: [EJB:010160]Security Violation: User: '<anonymous>' has insufficient permission to access EJB
This error is related to the rights required to call a method on the EJB. Indeed, two levels of rights are used by WebLogic: firstly to lookup / instanciate the EJB (cf. the property java.naming.security.principal
we set sooner), and another to call the method itself. In this second case, WebLogic requires an authentication (think of what you do when you login an web application deployed: your login and rights are kept for all the session) to grant the rights. I wish to handle this subject in a future post.
NB: thanks to David Chau and Didier Girard from SFEIR, Sachin from Mumbai team and PYC from NYC.
Mule: File transport reads many times the same file
Case
With Mule ESB 2.2.1, I use a classic <file:inbound-endpoint>
:
<file:inbound-endpoint path="${fromPath}" pollingFrequency="3000" fileAge="5000" moveToDirectory="${moveToDirectory}" synchronous="true" > <transformers> <transformer ref="mySimpleCSVParser"> </transformers> </file:inbound-endpoint>
When I launch the Mule with no component
(entreprise layer), everything is OK: the file is loaded, parsed and moved. But when I introduce a minimal component, which does nothing, then the file is read many times. Mule ESB seems to loop indefinitely, reading the file many times, without deleting it from the directory.
INFO 2010-03-04 15:47:18,291 [connector.file.0.receiver.6] org.mule.transport.file.FileMessageReceiver: Lock obtained on file: C:\temp\myFile.txt
Fix
Firstly I tried to increase the pollingFrequency
attribute, assuming that the file had not yet been completely parsed when another cycle of “load-parse-move”. But it did not fix the issue.
Indeed, the problem was not related to the component
layer, but to the parser itself. To fix the issue, you have to ensure the InputStream
is properly closed in your Transformer
layer:
try { inputStream.close(); return answer; } catch (IOException e) { throw new TransformerException((Message)null, e); }