`mvc:message-converters` ignored in Spring 5 - spring

We used to have the following configuration to customize our message converters in Spring 4:
<mvc:annotation-driven conversion-service="conversionService" content-negotiation-manager="contentNegotiationManager">
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper" ref="myObjectMapper"/>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
But after migrating to Spring 5, the above configuration has lost any effect (the default message converters take place).
If I define the bean explicitly, it works:
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="objectMapper" ref="myObjectMapper" />
</bean>
</property>
</bean>
<bean class="org.springframework.http.converter.ByteArrayHttannotation-drivenpMessageConverter"/>
<bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter"/>
<bean class="org.springframework.http.converter.FormHttpMessageConverter"/>
<bean class="org.springframework.http.converter.StringHttpMessageConverter" />
</list>
</property>
</bean>
Any idea why the mvc:message-converters tag stopped working?
ps. While debugging the issue I also noticed several instances of RequestMappingHandlerAdapter being instantiated in all cases, even though I would expect them to be a singleton. The latter significantly obscures debugging, since I'm not sure which is the right one to attribute message converters to to investigate.
pps. Another report of this issue:
https://stackoverflow.com/a/49156186/657723

In this case mvc:message-converters was overridden by another, empty mvc:annotation-driven which happened to be unnoticeably included down the chain of child xml inclusions.
In any case, the major problem was the silent override, which should have better be an error.

Related

Hibernate Envers not Finding JPA Transaction:

I've been trying to wrap my head around this issue all day.
Currently our project has setup JPATransactionManager through a Spring Application Context to take care of our various session transactions with the use of #Transactional on all services that take care of persistence and deletions (DAO usage).
Changing over from Hibernate 3 to 5, we wanted to remove our use of a custom audit interceptor and move onto using Hibernate Envers. I have annotated all my classes properly and have the tables being created, but once it actually gets to a point of insertion, the listener throws an error in which it can't find the current transaction given by JPA:
org.hibernate.envers.exception.AuditException: Unable to create revision because of non-active transaction
at org.hibernate.envers.event.spi.BaseEnversEventListener.checkIfTransactionInProgress(BaseEnversEventListener.java:132)
at org.hibernate.envers.event.spi.EnversPostInsertEventListenerImpl.onPostInsert(EnversPostInsertEventListenerImpl.java:34)
at org.hibernate.action.internal.EntityIdentityInsertAction.postInsert(EntityIdentityInsertAction.java:156)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:102)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:597)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:232)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:213)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:256)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:318)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:275)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:182)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:113)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:97)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSaveOrUpdate(SessionImpl.java:651)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:643)
at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:638)
Looking inside the code, it seems that it's basing the transaction status off it's default value of INACTIVE meaning that it's not hooking into the transaction properly. I know that Hibernate Envers also automatically pushes the listeners into hibernate with recent versions so I don't know if this may also be a source of the issue.
I know that its been documented to work with HibernateTransactionManager but we wish to step away from using that in favor of hooking up our transactions and sessions solely via Spring making things easier so it may also be the need of finding an alternative to envers. Does anyone have any advice or solutions to this problem? Or also hit this issue?
ApplicationContext.xml
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="dataSource" ref=“dataSource" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="net.sourceforge.jtds.jdbcx.JtdsDataSource" />
<property name="url" value="jdbc:jtds:sqlserver://.." />
<property name="username" value=“..." />
<property name="password" value=“..." />
</bean>
<bean id="hibernateProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location">
<value>classpath:hibernate.properties</value>
</property>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="hibernateProperties">
<ref bean="hibernateProperties" />
</property>
</bean>
<bean id="txProxyTemplate" abstract="true" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager">
<ref bean="transactionManager" />
</property>
<property name="transactionAttributes">
<props>
<prop key="find*">PROPAGATION_SUPPORTS,readOnly
</prop>
<prop key="load*">PROPAGATION_SUPPORTS,readOnly
</prop>
<prop key="make*">PROPAGATION_REQUIRED</prop>
<prop key="add*">PROPAGATION_REQUIRED</prop>
<prop key="refresh">PROPAGATION_SUPPORTS</prop>
<prop key="delete*">PROPAGATION_REQUIRED</prop>
<prop key="*">PROPAGATION_SUPPORTS,readOnly
</prop>
</props>
</property>
</bean>
<bean id="PROPAGATION_REQUIRED" class="org.apache.camel.spring.spi.SpringTransactionPolicy">
<property name="transactionManager" ref="transactionManager" />
</bean>
hibernate.properties
#hibernate.hbm2ddl.auto=update
hibernate.show_sql=true
hibernate.connection.datasource=java\:comp/env/datasource
#hibernate.connection.provider_class=org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl
hibernate.connection.provider_class=org.hibernate.connection.DatasourceConnectionProvider
hibernate.cache.use_second_level_cache=true
hibernate.cache.use_query_cache=true
#hibernate.generate_statistics=true
hibernate.cache.use_structured_entries=true
hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory
hibernate.id.new_generator_mappings=false
hibernate.dialect=org.hibernate.dialect.SQLServer2008Dialect
hibernate.listeners.envers.autoRegister=false
org.hibernate.envers.track_entities_changed_in_revision=false
org.hibernate.envers.audit_table_prefix=AUD_
org.hibernate.envers.audit_table_suffix=
My DAOs are hooked up using the txProxyTemplate like so
<bean id="objectDAO" parent="txProxyTemplate">
<property name="target">
<bean
class="path.to.objectDAOImpl">
<property name="sessionFactory">
<ref local="sessionFactory" />
</property>
</bean>
</property>
</bean>
All my services that use the various DAOs are simply hooked up using the #Transactional annotation where we want to have transactions. I've been able to see through trace that my transactions are succeeding in completing and rolling back as well when there are errors. Once I added envers into the mix, the auditing can't find the transaction to join. There must be something I'm missing but I'm not sure what it is.
I don't believe you need to define a txProxyTemplate bean nor a SpringTransactionPolicy from my experience. This functionality has since been superseded with the <tx:/> tags and the use of the #Transactional annotation.
You just need to make sure a JpaTransactionManager has been created and associated as the transactionManager associated with the <tx:annotation-driven/> tag.

spring-batch : load and use a property file

I am new on Spring batch so am here to ask some basic advice.
What is the best approach to load a config file in memory (or bean) and use its content while the spring Job/step are running ?
I am not sure but based on some google search I found the below scenario even if I dont quite understand why I should define a writer even if i dont need it :
step1 : load config file (the content is two field delimited by =)
step2 : perform some java code and use the previous config file
so for the step 1 :
<bean id="inputFile" class="org.springframework.core.io.FileSystemResource" scope="step">
<constructor-arg value="path_config_file"/>
</bean>
<bean id="readerConfigFile" class="org.springframework.batch.item.file.FlatFileItemReader" scope="step">
<property name="resource" ref="inputFile"/>
<property name="lineMapper">
<bean class="org.springframework.batch.item.file.mapping.DefaultLineMapper">
<property name="lineTokenizer">
<bean class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer">
<property name="names" value="field,value"/>
<property name="delimiter" value="="/>
</bean>
</property>
<property name="fieldSetMapper">
<bean class="org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper">
<property name="prototypeBeanName" value="configProperties"/>
</bean>
</property>
</bean>
</property>
</bean>
<bean id="outputConfig" class="outputConfig"></bean>
<bean id="configProperties" class="configProperties" scope="prototype"/>
so my question are :
How can I use the information gathered in the file ? Should I put them in the Java bean ?
How can I pas this info between different step or make them persistent in the whole application life-cycle ?
Would you recommend to use a itemProcessor to achieve the above ?
Any advice are most than welcome
I'm a bit confused about your questions because I think you only need to load a properties file in spring context using a PropertiesFactoryBean:
<bean id="config" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location">
<value>file:path_config_file</value>
</property>
</bean>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="propertiesArray">
<list>
<ref bean="config"/>
</list>
</property>
</bean>
and you can refer to property values using ${} placeholder; but this solution is unrelated to spring-batch; I don't need it!
About your questions:
Using a POJO is a good way because spring-batch offers in-box mapping strategies (BeanWrapperFieldSetMapper in your case)
Objects used in a job are accessible only in job context, not in application context (this is why I think you need a PropertiesFactoryBean).To pass object between steps read How can we share data between the different steps of a Job in Spring Batch?
ItemProcessor is requested if you need to convert an object T read from a ItemReader<T> to an object of type S written by an ItemWriter<S>. So no, you don't need an ItemProcessor.
I hope I was clear, English is not my native language

Spring, Websphere, JMS and Eclipselink Issue

I have an application that runs inside of Websphere, and I am having an issue with persisting JPA entities.
Previously, the application was setup with RESOURCE_LOCAL persistence units, with the Spring JpaTransactionManager, and transactions that were committed explicitly in code.
TransactionStatus transactionStatus = transactionManager.getTransaction( new DefaultTransactionDefinition() );
try {
entityManager.persist( someJpaEntity );
}
catch( Exception exception ) {
transactionManager.rollback( transactionStatus );
throw exception;
}
try {
transactionManager.commit( transactionStatus );
}
catch( TransactionException exception ) {
exception
}
I am working on an enhancement to the application that will allow calls through a Message Driven Pojo linked to a Websphere Queue. I was able to setup a configuration through spring that will allow my application to receive messages through a JMS queue. The spring config looks like:
<jee:jndi-lookup id="jmsConnectionFactory" jndi-name="QueueConnectionFactory"/>
<jee:jndi-lookup id="jmsQueue" jndi-name="DIQueue" />
<!-- A dynamic resolver -->
<bean id="jmsDestResolver" class="org.springframework.jms.support.destination.DynamicDestinationResolver"/>
<bean id="jmsQueueTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory">
<ref bean="jmsConnectionFactory"/>
</property>
<property name="destinationResolver">
<ref bean="jmsDestResolver"/>
</property>
</bean>
<bean id="messageListener" class="my.app.FileMessageListener" />
<bean id="exListener" class="my.app.JmsExceptionListener" />
<bean id="msgListenerContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="jmsConnectionFactory" />
<property name="destination" ref="jmsQueue" />
<property name="messageListener" ref="messageListener" />
<property name="transactionManager" ref="transactionManager" />
<property name="taskExecutor" ref="myTaskExecutor" />
<property name="exceptionListener" ref="exListener" />
</bean>
<bean id="myTaskExecutor" class="org.springframework.scheduling.commonj.WorkManagerTaskExecutor">
<property name="workManagerName" value="wm/default" />
</bean>
Not sure if there is an issue with my spring setup, but I do receive messages through my Active MQ broker, so that part I seem to be good with.
Now, the issue is, that when I get a message in through JMS, I would call the above code to insert the JPA entity. When the code would run, I would get the message "unable to commit a one phase resource in a two phase transaction", or something similar. What I came to understand is that the Spring JpaTransactionManager does not work with XA or JTA transactions.
So, I worked on moving to the Spring JtaTransactionManager.
I changed everything I Could think of over to use JTA, here is where I declare my transaction manager:
<bean id="transactionManager" class="org.springframework.transaction.jta.WebSphereUowTransactionManager"/>
Updated my persistence XML:
<persistence-unit name="AppUnit" transaction-type="JTA">
<provider>oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider</provider>
<jta-data-source>java:APPDS</jta-data-source>
And still, nothing works. My code runs without exception, but nothing gets persisted to the database. The message gets pulled off of the JMS Queue, but no data.
Any suggestions?
I finally got this working, and figured I would post the answer.
There are actually 2 pieces to the puzzle.
First, in Websphere, you need to go to your app server -> TransactionService, and check / enable the "Accept Heuristic Hazard" checkbox. That definitely helped. I am running WAS 7.
The second thing, is you MUST set the property eclipselink.target-server on your persistence unit or your EntityManagerFactory.
That second item definitely did the trick. I tested with the property and without it. Without it, nothing persists. With it, everything works fine.
Here is my EntityManagerFactory, I am using a property placeholder to set the value of the eclipselink.target-server property:
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="MyUnit" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">
<property name="databasePlatform">
<value>${app.databasePlatform}</value>
</property>
<property name="showSql">
<value>${app.showSql}</value>
</property>
</bean>
</property>
<!-- THIS DID THE TRICK -->
<property name="jpaPropertyMap">
<map>
<entry key="eclipselink.target-server" value="${app.targetServer}"/>
</map>
</property>
</bean>

Spring Vs Struts + Freemarker

For a Web application If I've choices between Spring and Struts to use with Freemarker, which one go well, Or I would rather ask, which MVC framework integrates smoothly with Freemarker?
The Spring framework provides everything you need to use FreeMarker for your view layer.
Both have pretty good freemarker support. Its easy to turn on.
Struts2 is a little more pojo based. Spring is a little closer to the servlet api. Spring's default macros in spring.ftl need a little work and you will likely need to roll your own. Some of the macros blow up if an object is not present rather than gracefully testing for it and moving on if it is not there.
I like Spring's application of validation via annotations better than Struts 2 default validation. However, persisting validation errors over redirects is easier in Struts2. For Spring you'll end up needing to roll your own solution where I feel the framework should hide more of that. Needing to use the error prone spring.bind macro with freemarker templates is more cumbersome than it needs to be.
Spring 3.1 is supposed to provide better support for this validation errors living over redirects.
Also note, with Spring I typically use more than one view resolver. e.g. I still leaving support for .jsp on.
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="html" value="text/html"/>
<entry key="ftl" value="text/html"/>
<entry key="xml" value="application/xml"/>
<entry key="json" value="application/json"/>
</map>
</property>
<property name="favorPathExtension" value="true"/>
<property name="defaultViews">
<list>
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/>
</list>
</property>
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="cache" value="true"/>
<property name="order" value="1"/>
<property name="prefix" value="/"/>
<property name="suffix" value=".ftl"/>
<property name="contentType" value="text/html;charset=UTF-8"/>
<property name="exposeSpringMacroHelpers" value="true"/>
<property name="requestContextAttribute" value="rc"/>
<property name="exposeSessionAttributes" value="true"/>
<property name="exposeRequestAttributes" value="true"/>
</bean>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
</list>
</property>
</bean>

Spring MVC from 2.5 to 3.0

We are migrating our web application from Spring 2.5 to Spring 3.0.5. Looks like all the Controller classes (the classes in org.springframework.web.servlet.mvc package: BaseCommandController, AbstractCommandController, SimpleFormController, etc) have been deprecated. We used those classes heavily in our application. These classes have been replaced by #Controller annotation instead.
I have a few questions regarding Spring 3.0.x Controller configuration...
We used the following XML to create a Controller bean in Spring 2.5. If <context:component-scan> is used instead to create the Controller beans, then how do I wire-in the dependencies? If possible I would like to avoid Auto-Wiring.
<bean id="photosetViewController" class="com.xyz.web.PhotosetViewController"
p:photosetManager-ref="photosetManager"
p:photoManager-ref="photoManager" />
We have created 3 Interceptors. We use SimpleUrlHandlerMapping to map these Interceptors to different request URLs and also to map URLs to Controllers. How do we achieve the same in Spring 3.0.x?
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="alwaysUseFullPath" value="true" />
<property name="interceptors">
<list>
<ref bean="httpRedirectInterceptor"/>
<ref bean="loginInterceptor"/>
</list>
</property>
<property name="mappings">
<value>
/abc.html=abcLookupController
/photoupload.html=photoUploadController
</value>
</property>
</bean>
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="alwaysUseFullPath" value="true" />
<property name="interceptors">
<list>
<ref bean="httpRedirectInterceptor"/>
<ref bean="loginInterceptor"/>
<ref bean="userMenuInterceptor" />
</list>
</property>
<property name="mappings">
<value>
/index.html=homepageController
/success.html=simpleController
</value>
</property>
</bean>
In case of SimpleFormControllers we used different methods like initBinder, referenceData, formBackingObject. We also used command objects and validation classes. How do we achieve the same in Spring 3.0.x?
<bean id="photosetAddController" class="com.xyz.web.PhotosetAddController"
p:photosetManager-ref="photosetManager"
p:photosetTypeManager-ref="photosetTypeManager"
p:stateManager-ref="stateManager" >
<property name="validator">
<bean class="com.xyz.form.PhotosetAddValidator" />
</property>
<property name="formView" value="photosetadd" />
<property name="successView" value="redirect:/photoset" />
</bean>
Any pointers are greatly appreciated.
As skaffman noted - your code will work fine without any modifications. I'll answer your questions in short:
You can use #Resource(name="beanName") for name-based injection. But autowiring is also a good option. Either #Autowired, or #javax.inject.Inject. Note that you can use #Qualifier("name") to differentiate between beans with the same interface/base class. You can even use the javax.inject qualifiers (read about all these in the docs)
interceptor mappings can stay the same
There is #InitBinder, which denotes the initBinder method. I can't tell about the other.

Resources