How to use WAS standard persistence provider with Spring - spring-mvc

I'm developing a portlet which runs in WebSphere Application Server ( - I accept the same problem to appear if it was a servlet instead of a portlet). At the moment it depends on Hibernate. As WAS provides a JPA implementation itself, which is a modified version of OpenJPA 2.0, I want to get rid of Hibernate.
This is my setup. persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
>
<persistence-unit name="default" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/myDb</jta-data-source>
<properties>
<property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.WebSphereExtendedJtaPlatform" />
<property name="hibernate.dialect" value="org.hibernate.dialect.DB2Dialect" />
</properties>
</persistence-unit>
</persistence>
myPortlet-portlet.xml
<!-- ... -->
<tx:jta-transaction-manager />
<jee:jndi-lookup jndi-name="jdbc/myDb" cache="true" id="dataSource" expected-type="javax.sql.DataSource" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="default" />
</bean>
In my DAO-classes I access the entityManager by using annotations:
#PersistenceContext(unitName = "default")
private EntityManager entityManager;
Everything works fine using Hibernate.
According to WebSphere Application Server docs, the default persistence provider is used if you don't specify it by using the <provider/>-tag in persistence.xml. But after commenting out the provider specification, Spring throws an exception due not being able to find the provider-class:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in PortletContext resource [/WEB-INF/myPortlet-portlet.xml]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: No PersistenceProvider specified in EntityManagerFactory configuration, and chosen PersistenceUnitInfo does not specify a provider class name either
How can I use the provided JPA implementation together with Spring (Portlet) MVC?

Short answer
You cannot use WebSphere's default provider by omitting the provider, if you want to use LocalContainerEntityManagerFactoryBean.
Long answer
Normally an entity manager is created by an entity manager factory provided by the container. You retrieve it by doing a context loopkup (EntityManager em = (EntityManager) ctx.lookup(...)) manually or use Springs jndi-lookup capability:
<beans>
<jee:jndi-lookup id="myEmf" jndi-name="persistence/myPersistenceUnit"/>
</beans>
In the question, a different approach is used, a LocalContainerEntityManagerFactoryBean, which creates an entity manager factory itself. This entity manager factory is a proxy that implements all the interfaces of the native entity manager factory. For creating such a proxy, Spring must know the class of the native entity manager factory. Spring uses three different ways to determine the class:
Detect it by the <provider/>-entry in persistence.xml
Asking a jpaVendorAdapter (specified in the equally named property of the factory bean)
Using the entityManagerFactoryInterface-property of the factory bean
And that's why you cannot completely omit the specification of your provider.

This is most likely happening because the Spring JAR(s) that you include with your application contains a different implementation of the Persistence class, or other JPA classes, used to "bootstrap" JPA.
If you'd like to use WebSphere's default provider (or, more precisely, to use whichever JPA provide configured through WebSphere's administration screens), then you must ensure that the JPA "bootstrapping" code being called during runtime is WebSphere's, not yours.
You should look for a Spring distribution JAR that doesn't mess with JPA.

Related

how to inject userContext in JSP pages

how do I retrieve the values of a context in a jsp file? this tutorial is perfect for what I need but I need to retrieve the property values in the jsp file.
http://www.mkyong.com/spring/spring-listfactorybean-example/
is there a specific interceptor that I can use?
You're referring to spring context right?
In general, JSPs should be a template of a page only, so the only interaction with the back-end should be accessing the values of the scoped attributes. This means that whichever bean value you need you should instead store in the model.
This being said, there are a few ways you can expose spring beans to view. Depends on which View resolver you're using, the ones that extend UrlBasedViewResolver have the setExposeContextBeansAsAttributes property
Set whether to make all Spring beans in the application context
accessible as request attributes, through lazy checking once an
attribute gets accessed. This will make all such beans accessible in
plain ${...} expressions in a JSP 2.0 page, as well as in JSTL's c:out
value expressions.
Default is "false".
You would configure it like
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
<property name="exposeContextBeansAsAttributes" value="true" />
</bean>
Inject your bean (or source) of userContext into your controller, so you have access to it in a local variable.
So taking the example maybe this is:
#Autowired
private CustomerBean customerBean;
#RequestMapping(value="/foobar/index.jsp")
public String (HttpServletRequest request) {
Object userContext = customerBean.getLists();
request.setAttribute("userContext", userContext);
return "/foobar/index.jsp"; // expecting JstlView viewResolver to map to JSP file
}
In the CONTROLLER simply add data to the HttpServletRequest (which you just add as argument to the method to introduce it).
Then use request.setAttribute("userContext", userContext); then in JSP simply access it using Expression Language like ${userContext}. There are other ways using Spring model paradigm but they effectively do the above.
Ensure you have your JstlView setup to https://dzone.com/articles/exploring-spring-controller
More info about how to use EL in JSPs to retrieve data attached to request:
How to obtain request / session / servletcontext attribute in JSP using EL?

Spring AsyncServlet with ActiveMQ, Camel and Jetty

I'm trying to use Spring AsyncServlet with Camel and ActiveMQ. I'm using the following versions.
<spring.version>3.2.0.M1</spring.version>
<camel.version>2.10.0</camel.version>
<jetty.version>8.1.3.v20120416</jetty.version>
<activemq.version>5.6.0</activemq.version>
I want to push messages to clients that are connected to the server (Jetty).
My Camel routes looks like the following.
from("mina:udp://source_machine:9998").to("activemq:myqueue");
I've the following in my Spring/Camel configuration based on this.
<bean id="jmsConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="vm://localhost:61616" />
</bean>
<bean id="pooledConnectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory">
<property name="maxConnections" value="8" />
<property name="maximumActive" value="500" />
<property name="connectionFactory" ref="jmsConnectionFactory" />
</bean>
<bean id="jmsConfig" class="org.apache.camel.component.jms.JmsConfiguration">
<property name="connectionFactory" ref="pooledConnectionFactory" />
<property name="transacted" value="false" />
<property name="concurrentConsumers" value="10" />
</bean>
<bean id="activemq" class="org.apache.activemq.camel.component.ActiveMQComponent">
<property name="configuration" ref="jmsConfig" />
</bean>
Using the above configuration I'm able to input messages into my queue (at least I don't get any errors.) However, I've no idea how to read from this queue.
Is this the correct way of configuring ActiveMQ when using Spring, Camel and Jetty ?
How do I add/register a MessageListener javax.jms.MessageListener so that I can read from my queue.
How can I control the queue size and make the queue non-persistent?
It it possible to add multiple listeners
Thanks.
Your config looks good for activemq. No idea about jetty. There is no jetty config in the snippet you provided.
In a camel route you can simply use a from activemq endpoint to listen on the queue.
from("activemq:myqueue").to("log:test");
Btw. I typically use the jms ednpoint instead of the ActiveMQ one. This has the advantage that it is easier to switch to another jms provider if you have to at some point.
You can also use the connectionfactory and use you own DefaultMessageListenerContainer in a bean. See the spring configs for how to do this but this has nothing to do with camel then.
You can control the queue size in the activemq config. Using the http://activemq.apache.org/producer-flow-control.html.
You can not make a queue no persistent but you can define the messages you send to be non persistent. http://activemq.apache.org/how-do-i-disable-persistence.html
You can define many listeners and you can even define the number of threads for one listener using the option maxConcurrentConsumers on the from endpoint above.

How to access request scoped bean in controller?

I'm trying to understand the request scoped beans. Suppose I have a controller and I have a request scoped bean instantiated using spring config xml
<bean id="loginAction" class="com.foo.LoginAction" scope="request"/>
Do I need to add it as a dependency in controller to access it or I can access it directly from request object doing request.getAttribute("loginAction")
I just wanted to know how would I access this request scoped bean.
Thanks.
Use #Autowired annotation for this case.
#Autowired
private LoginAction loginAction;
and then add package for this bean as candidate for autowiring:
<context:annotation-config />
<context:component-scan base-package="com.foo"></context:component-scan>
and don't forget to mark this class as #Component or #Service.

understanding AMFChannel in flex and message broker

I need to use AMFChannel in order to connect to RemoteObject in flex tried searching a lot but couldn;t get source to understand the two parameters being passed to the constructor ... I am using spring framework as a backend for my GUI created using flex .... canm some one explain me this integration of flex with spring or guide me to a proper resource to understand it... through which I can understand the overall scenerio... or atleast understand how this call is being made using message broker . PLEASE SOME ONE HELP ME BY TELLING ME WHAT IS THE MEANING OF URL WE ARE PASSING TO THE AMF CHANNEL CONSTRUCTOR
This link might help some one.
The MessageBroker transparently handles the process of serialization and deserialization between the Flex AMF data format and Java.
This link explains everything with help of example which was exactly what I was looking for
some important setup information is as follows
Server side has following files
* testdrive/src/main/webapp/WEB-INF/spring/app-config.xml
* testdrive/src/main/webapp/WEB-INF/flex-servlet.xml
* testdrive/src/main/java/flex/spring/samples/product/ProductDAO.java
Client side has one file which looks like this
Step1) Initialize a messagebroker in flex-servlet.xml
<flex:message-broker>
<flex:message-service
default-channels="my-streaming-amf,my-longpolling-amf,my-polling-amf" />
<flex:secured />
</flex:message-broker>
Step2) In the same flex-servlet.xml specify one tag
<flex:remoting-destination ref="productService" />
Step 3) In app-config.xml
<bean id="contactService" class="org.springframework.flex.samples.product.ProductDAO">
<constructor-arg ref="dataSource" />
</bean>
Step 4) ProductDAO.java is the class which will exposed for the remoting
Client side can call the remote object as follows
Step 5)
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<!-- "productService" is defined in Spring's configuration file WEB-INF/config/web-application-config.xml
and provides remote access to the org.springframework.flex.samples.product.ProductDAO class -->
<mx:RemoteObject id="ro" destination="productService"/>
<mx:DataGrid dataProvider="{ro.findAll.lastResult}" width="100%" height="100%"/>
<!-- the findAll() method is defined in org.springframework.flex.samples.product.ProductDAO -->
<mx:Button label="Get Data" click="ro.findAll()"/>
</mx:Application>

How to enable Spring 3.0 MappingJacksonHttpMessageConverter with #ResponseBody AND pre-Spring-3.0 Controller SimpleUrlHandlerMapping together?

As the title suggests, I'm trying and failing to get the following combination working in Spring 3.0:
pre-Spring-3.0 controllers mapped with SimpleUrlHandlerMapping, and,
a Spring-3.0 #Controller using MappingJacksonHttpMessageConverter and #ResponseBody to return JSON.
All the pieces work - except when put together!
In more detail, I have an existing Spring web-app which includes many pre-Spring-3.0 controllers. These implement Controller and are mapped explicitly with a SimpleUrlHandlerMapping bean. (So one solution is to change them all to #Controller style). The same web-app (DispatcherServlet) also supports several newer controllers annotated with #Controller.
My bean config includes the following, and all is good:
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/path/name.ext">mySpring25Controller</prop>
</props>
</property>
</bean>
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
</bean>
Now I'm adding, to a new controller annotated with #Controller and #RequestMapping, use of MappingJacksonHttpMessageConverter so that with #ResponseBody some of my methods can return JSON via Jackson - to Ajax calls. Again all is good:
<!-- to generate JSON responses using Jackson (without using <mvc:annotation-driven/>) -->
<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jacksonMessageConverter"/>
</list>
</property>
</bean>
The problem is that now my explicit mappings defined in the SimpleUrlHandlerMapping bean are no longer working:
[http-8081-Processor25] ERROR org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/mayapp].[springapp] - Servlet.service() for servlet springapp threw exception
javax.servlet.ServletException: No adapter for handler [com.mycom.controller.mySpring25Controller ...]: Does your handler implement a supported interface like Controller?
at org.springframework.web.servlet.DispatcherServlet.getHandlerAdapter(DispatcherServlet.java:985)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:773)
These mappings still appear in my log at start-up (SimpleUrlHandlerMapping - Mapped URL path ... etc) - but evidently are now broken somehow.
INFO org.springframework.web.servlet.handler.SimpleUrlHandlerMapping - Mapped URL path [/path/name.ext] onto handler [com.mycom.controller.mySpring25Controller ....]
I started with <mvc:annotation-driven/> which had the same problem. I've tried re-ordering without success, including order properties. And I've also not found an explanation in the Spring docs. It seems there is some interaction in the Spring auto-magic which I haven't got to the bottom of.
Interesting problem anyone? Insight gratefully received!
Post and ye shall find (delayed by 8 hours for lack of reputation)!
As per post No adapter for handler exception the answer appears to be that the explicit AnnotationMethodHandlerAdapter definition blows away the implicit SimpleControllerHandlerAdapter which was previously satisfying the SimpleUrlHandlerMapping mappings.
So add it explicitly:
<bean
class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter">
</bean>
And we're good, though at the same time you might also need to introduce also an explicit replacement for the implicit HttpRequestHandlerAdapter also blown away:
<bean
class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter">
</bean>

Resources