FailoverTransport instantiated multiple times - spring

I'm using spring-jms version 3.0.5 and activeMQ version 4.5.2. When deployed to Tomcat, everything seems to work properly. When deployed to WebSphere, it appears that four separate failover transports are being insantiated, and my MessageListener implementation receives the same message four times for every message that gets published to my topic.
Here's my config:
<bean id="activeMQConnectionFactory"
class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="failover://(tcp://server.com:12345,tcp://server2.com:12345)?randomize=false/>
</bean>
<bean id="topic" class="org.apache.activemq.command.ActiveMQTopic">
<constructor-arg value="TOPIC.ONE" />
</bean>
<bean id="jmsTemplate" class="org.sprinframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="connectionFactory" />
<property name="defaultDestination" ref="topic" />
</bean>
<bean name="topicListener" class="com.foo.TopicListener" />
<jms:listener-container connection-factory="connectionFactory" cache="auto" destination-type="topic">
<jms:listener destination="topic" ref="topicListener" />
</jms:listener-container>
Here's my message listener:
import javax.jms.MessageListener;
import org.springframework.stereotype.Component;
#Component
public class TopicListener implements MessageListener {
public void onMessage(Message msg) {
log(msg);
}
}
And here's what I see in my logs (only on WebSphere)
11:59:59,764 () INFO (Thread-50) (DefaultLifecycleProcessor) Starting beans in phase 214783647
12:00:00,140 () INFO (ActiveMQ Task) (FailoverTransport) Successfully connected to tcp://server.com:12345
12:00:00,253 () INFO (ActiveMQ Task) (FailoverTransport) Successfully connected to tcp://server.com:12345
12:00:00,342 () INFO (ActiveMQ Task) (FailoverTransport) Successfully connected to tcp://server.com:12345
12:00:00,423 () INFO (ActiveMQ Task) (FailoverTransport) Successfully connected to tcp://server.com:12345
12:00:00,492 () INFO (Thread-50) (ContextLoader) Root WebApplicationContext: initialization completed in 100239 ms
And then once I publish to the topic, I see:
12:01:00,250 () INFO (org.springframework.jms.listener.DefaultMessageListenerContainer#0-1) (TopicListener) logging message
12:01:00,251 () INFO (org.springframework.jms.listener.DefaultMessageListenerContainer#3-1) (TopicListener) logging message
12:01:00,251 () INFO (org.springframework.jms.listener.DefaultMessageListenerContainer#2-1) (TopicListener) logging message
12:01:00,275 () INFO (org.springframework.jms.listener.DefaultMessageListenerContainer#1-1) (TopicListener) logging message
I've seen some indication that this sort of behavior might be expected if I'd set concurrentConsumers > 1, but as far as I can tell, I haven't. How can I make sure I'm only receiving these messages once?
UPDATE:
With debug logging on, I also see:
2012-10-28 12:00:00,000 () DEBUG (Thread-50) (DefaultLifecycleProcessor) Starting bean 'org.springframework.jms.listener.DefaultMessageListenerContainer#0' of type [class org.springframework.jms.listener.DefaultMessageListenerContainer]
2012-10-28 12:00:00,011 () DEBUG (Thread-50) (DefaultLifecycleProcessor) Starting bean 'org.springframework.jms.listener.DefaultMessageListenerContainer#1' of type [class org.springframework.jms.listener.DefaultMessageListenerContainer]
2012-10-28 12:00:00,021 () DEBUG (Thread-50) (DefaultLifecycleProcessor) Starting bean 'org.springframework.jms.listener.DefaultMessageListenerContainer#2' of type [class org.springframework.jms.listener.DefaultMessageListenerContainer]
2012-10-28 12:00:00,029 () DEBUG (Thread-50) (DefaultLifecycleProcessor) Starting bean 'org.springframework.jms.listener.DefaultMessageListenerContainer#3' of type [class org.springframework.jms.listener.DefaultMessageListenerContainer]
Why would Spring create four of these beans?

Related

Spring singleton scope isn't working in spring-integration application

I have a spring-integration application with the following configuration :
<beans:bean id="customMessageListenerContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer" scope = "singleton">
<beans:property name="errorHandler" ref="customErrorHandler"/>
<beans:property name="connectionFactory" ref="connectionFactory" />
<beans:property name="destination" ref="jmsInputQueueXssl" />
<beans:property name="sessionTransacted" value="true" />
<beans:property name="maxConcurrentConsumers" value="1" />
<beans:property name="concurrentConsumers" value="1" />
<beans:property name="receiveTimeout" value="5000" />
<beans:property name="recoveryInterval" value="60000" />
<beans:property name="autoStartup" value="true" />
<beans:property name="exposeListenerSession" value="false" />
<beans:property name="subscriptionDurable" value="true" />
<beans:property name="durableSubscriptionName" value="${ibm.jms.subscription.id1}" />
<beans:property name="backOff" ref="myBackoff" />
</beans:bean>
<beans:bean id="myBackoff" class="c.h.i.c.d.x.j.MyFixedBackOff">
<beans:constructor-arg index="0" value="5000"/>
<beans:constructor-arg index="1" value="5"/>
</beans:bean>
<!-- Custom error handler -->
<beans:bean id="customErrorHandler" class="c.h.i.c.d.x.j.XsslCustomErrorHandler" />
<beans:beans profile="env">
<jms:message-driven-channel-adapter
id="jmsInboundAdapterXssl" channel="channel2"
acknowledge="transacted" error-channel="errorChannel"
container="customMessageListenerContainer"/>
</beans:beans>
However, it seems that there are several instances of that class customMessageListenerContainer if I read the logs :
2019-05-10 17:54:39,783 INFO [main] o.s.i.e.SourcePollingChannelAdapter [AbstractEndpoint.java:97] started org.springframework.integration.config.SourcePollingChannelAdapterFactoryBean#0
2019-05-10 17:54:39,783 INFO [main] o.s.c.s.DefaultLifecycleProcessor [DefaultLifecycleProcessor.java:341] Starting beans in phase 2147483647
2019-05-10 17:54:39,924 INFO [customMessageListenerContainer-1] c.h.i.c.d.x.j.MyFixedBackOff [MyFixedBackOff.java:115] MyFixedBackOff currentAttempts = 0
2019-05-10 17:54:44,930 WARN [customMessageListenerContainer-1] o.s.j.l.DefaultMessageListenerContainer [DefaultMessageListenerContainer.java:871] Setup of JMS message listener invoker failed for destination 'queue:///CT_XSSL.CT_CPMX.MRZC_DGRM.0013' - trying to recover. Cause: JMSWMQ2008: Failed to open MQ queue 'CT_XSSL.CT_CPMX.MRZC_DGRM.0013'.; nested exception is com.ibm.mq.MQException: JMSCMQ0001: WebSphere MQ call failed with compcode '2' ('MQCC_FAILED') reason '2085' ('MQRC_UNKNOWN_OBJECT_NAME').
2019-05-10 17:54:44,930 INFO [customMessageListenerContainer-1] o.s.j.l.DefaultMessageListenerContainer [DefaultMessageListenerContainer.java:921] Successfully refreshed JMS Connection
2019-05-10 17:54:44,930 INFO [customMessageListenerContainer-2] c.h.i.c.d.x.j.MyFixedBackOff [MyFixedBackOff.java:115] MyFixedBackOff currentAttempts = 0
2019-05-10 17:54:49,938 WARN [customMessageListenerContainer-2] o.s.j.l.DefaultMessageListenerContainer [DefaultMessageListenerContainer.java:871] Setup of JMS message listener invoker failed for destination 'queue:///CT_XSSL.CT_CPMX.MRZC_DGRM.0013' - trying to recover. Cause: JMSWMQ2008: Failed to open MQ queue 'CT_XSSL.CT_CPMX.MRZC_DGRM.0013'.; nested exception is com.ibm.mq.MQException: JMSCMQ0001: WebSphere MQ call failed with compcode '2' ('MQCC_FAILED') reason '2085' ('MQRC_UNKNOWN_OBJECT_NAME').
2019-05-10 17:54:49,938 INFO [customMessageListenerContainer-2] o.s.j.l.DefaultMessageListenerContainer [DefaultMessageListenerContainer.java:921] Successfully refreshed JMS Connection
2019-05-10 17:54:49,953 INFO [customMessageListenerContainer-3] c.h.i.c.d.x.j.MyFixedBackOff [MyFixedBackOff.java:115] MyFixedBackOff currentAttempts = 0
2019-05-10 17:54:54,962 WARN [customMessageListenerContainer-3] o.s.j.l.DefaultMessageListenerContainer [DefaultMessageListenerContainer.java:871] Setup of JMS message listener invoker failed for destination 'queue:///CT_XSSL.CT_CPMX.MRZC_DGRM.0013' - trying to recover. Cause: JMSWMQ2008: Failed to open MQ queue 'CT_XSSL.CT_CPMX.MRZC_DGRM.0013'.; nested exception is com.ibm.mq.MQException: JMSCMQ0001: WebSphere MQ call failed with compcode '2' ('MQCC_FAILED') reason '2085' ('MQRC_UNKNOWN_OBJECT_NAME').
2019-05-10 17:54:54,962 INFO [customMessageListenerContainer-3] o.s.j.l.DefaultMessageListenerContainer [DefaultMessageListenerContainer.java:921] Successfully refreshed JMS Connection
How can I make customMessageListenerContainer effectively a singleton ?
What makes you think it's not a singleton?
If you mean the thread names are incrementing (customMessageListenerContainer-2 etc), it's because by default a SimpleAsyncTaskExecutor is used and a new thread is used after each failure (and the previous one terminates).
You can change the executor to a different implementation (e.g. thread pool) if you want.
Singleton is the default scope.

Camel Splitter Unit Test get wrong ExpectedMessageCount

I have to write unit test for a camel RouteBuilder that use splitter pattern.
Here my RouteConfiguration
protected void configureTest(){
from("direct:in").id("in")
.to("mock:a")
.split(body())
.to("mock:b")
.end();
}
And the test
public class AlertingRouteBuilderTest extends CamelSpringTestSupport {
#Test
public void testest() throws Exception {
String[] bodyArray = new String[]{"tenant1", "tenant2", "tenant3"};
getMockEndpoint("mock:a").setExpectedMessageCount(1);
getMockEndpoint("mock:b").setExpectedMessageCount(3);
template.sendBody("direct:in", bodyArray);
assertNotNull(context.hasEndpoint("direct:in"));
assertMockEndpointsSatisfied();
}
}
#Override
protected AbstractApplicationContext createApplicationContext() {
return new ClassPathXmlApplicationContext("classpath:cmCtx_alertingProcessTest.xml");
}
with this context.xml file
<bean id="A"
class="org.mockito.Mockito" factory-method="mock">
<constructor-arg value="foo.AProcessor"/>
</bean>
<bean id="B"
class="org.mockito.Mockito" factory-method="mock">
<constructor-arg value="foo.BProcessor"/>
</bean>
<bean id="routeBuilder"
class="foo.RouteBuilder" >
</bean>
<camel:camelContext id="context-objectAnalysis" trace="true" errorHandlerRef="errorHandler">
<camel:propertyPlaceholder id="properties" location="camel.properties"/>
<camel:routeBuilder ref="routeBuilder"/>
</camel:camelContext>
I tried different way to split my body
.split(body())
.split(body(String[].class))
....
But I get
java.lang.AssertionError: mock://b Received message count. Expected: <3> but was: <0>
I don't understand why my splitter does'nt go into my mock:b processor.
In the trace console I have
16:18:34.046 [main] DEBUG o.a.camel.processor.SendProcessor - >>>> Endpoint[mock://a] Exchange[Message: [Ljava.lang.String;#58ec5e8]
16:18:34.051 [main] DEBUG o.a.c.component.mock.MockEndpoint - mock://a >>>> 0 : Exchange[Message: [Ljava.lang.String;#58ec5e8] with body: [Ljava.lang.String;#58ec5e8 and headers:{breadcrumbId=ID-EFR02223-61984-1495635511863-0-1}
16:18:34.053 [main] INFO o.a.c.processor.interceptor.Tracer - ID-EFR02223-61984-1495635511863-0-2 >>> (direct:in) mock://a --> split[bodyAs[[Ljava.lang.String;]] <<< Pattern:InOnly, Headers:{breadcrumbId=ID-EFR02223-61984-1495635511863-0-1}, BodyType:String[], Body:[Ljava.lang.String;#58ec5e8
16:18:34.064 [main] DEBUG o.a.c.processor.MulticastProcessor - Done sequential processing 3 exchanges
Tell me if you need more info to help me.
EDIT:
camel version 2.12.1
Thanks.

Spring JPA transaction over multiple methods

I'm using Spring 3.2 with JPA and Hibernate 4 in a web application running in Tomcat 7. The application is divided into controller, service an DAO classes. The service classes have an annotated transaction configuration at class and method level. The DAOs are plain JPA with entity manager injected by #PersistenceContext annotation.
#Service("galleryService")
#Transactional(propagation=Propagation.SUPPORTS, readOnly=true)
public class GalleryServiceImpl implements GalleryService {
#Override
public Picture getPicture(Long pictureId) {
return pictureDao.find(pictureId);
}
#Override
public List<PictureComment> getComments(Picture picture) {
List<PictureComment> comments = commentDao.findVisibleByPicture(picture);
Collections.sort(comments, new Comment.ByCreatedOnComparator(Comment.ByCreatedOnComparator.SORT_DESCENDING));
return comments;
}
...
}
#Controller
#RequestMapping("/gallery/displayPicture.html")
public class DisplayPictureController extends AbstractGalleryController {
#RequestMapping(method = RequestMethod.GET)
public String doGet(ModelMap model, #RequestParam(REQUEST_PARAM_PICTURE_ID) Long pictureId) {
Picture picture = galleryService.getPicture(pictureId);
if (picture != null) {
model.addAttribute("picture", picture);
// Add comments
model.addAttribute("comments", galleryService.getComments(picture));
} else {
LOGGER.warn(MessageFormat.format("Picture {0} not found.", pictureId));
return ViewConstants.CONTENT_NOT_FOUND;
}
return ViewConstants.GALLERY_DISPLAY_PICTURE;
}
...
}
I switched on debug logging for org.springframework.transaction and noticed, that "Creating new transaction", "Opened new EntityManager", "Getting...", "Closing..." and "Committing transaction" is done for every call of a method in my service class. Even if those methods where called by one single method in my controller class. Here is an example of my log output:
2014-12-03 10:53:00,448 org.springframework.transaction.support.AbstractPlatformTransactionManager getTransaction
DEBUG: Creating new transaction with name [de.domain.webapp.gallery.service.GalleryServiceImpl.getPicture]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly
2014-12-03 10:53:00,448 org.springframework.orm.jpa.JpaTransactionManager doBegin
DEBUG: Opened new EntityManager [org.hibernate.jpa.internal.EntityManagerImpl#6133a72f] for JPA transaction
2014-12-03 10:53:00,468 org.springframework.orm.jpa.JpaTransactionManager doBegin
DEBUG: Exposing JPA transaction as JDBC transaction [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle#5182c1b7]
2014-12-03 10:53:00,468 org.springframework.transaction.interceptor.TransactionAspectSupport prepareTransactionInfo
TRACE: Getting transaction for [de.domain.webapp.gallery.service.GalleryServiceImpl.getPicture]
2014-12-03 10:53:00,489 org.springframework.transaction.interceptor.TransactionAspectSupport commitTransactionAfterReturning
TRACE: Completing transaction for [de.domain.webapp.gallery.service.GalleryServiceImpl.getPicture]
2014-12-03 10:53:00,489 org.springframework.transaction.support.AbstractPlatformTransactionManager processCommit
DEBUG: Initiating transaction commit
2014-12-03 10:53:00,489 org.springframework.orm.jpa.JpaTransactionManager doCommit
DEBUG: Committing JPA transaction on EntityManager [org.hibernate.jpa.internal.EntityManagerImpl#6133a72f]
2014-12-03 10:53:00,489 org.springframework.orm.jpa.JpaTransactionManager doCleanupAfterCompletion
DEBUG: Closing JPA EntityManager [org.hibernate.jpa.internal.EntityManagerImpl#6133a72f] after transaction
2014-12-03 10:53:00,489 org.springframework.orm.jpa.EntityManagerFactoryUtils closeEntityManager
DEBUG: Closing JPA EntityManager
I know that I can use an OpenSessionInView to hold the hibernate session for a complete request but some people said, OSIV is an antipattern. Instead I'm using SpringOpenEntityManagerInViewFilter. But with no success. How can I achieve, Spring uses a single transaction for multiple service layer method calls of my controller? Or did I missunderstand anything?
Here a part of my Spring configuration:
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="MYSQL" />
<property name="showSql" value="false" />
</bean>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/tikron" />
</bean>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="jpaTemplate" class="org.springframework.orm.jpa.JpaTemplate">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<context:component-scan base-package="de.domain.webapp">
<context:include-filter type="regex" expression=".*Service"/>
</context:component-scan>
My persistence unit:
<persistence-unit name="tikron-data" transaction-type="RESOURCE_LOCAL">
<!-- Entities located in external project tikron-data -->
<jar-file>/WEB-INF/lib/tikron-data-2.0.1-SNAPSHOT.jar</jar-file>
<!-- Enable JPA 2 second level cache -->
<shared-cache-mode>ALL</shared-cache-mode>
<properties>
<property name="hibernate.hbm2ddl.auto" value="validate" />
<property name="hibernate.cache.use_second_level_cache" value="true" />
<property name="hibernate.cache.use_query_cache" value="true" />
<property name="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory"/>
<property name="hibernate.generate_statistics" value="false" />
</properties>
</persistence-unit>
Some more log output from application startup:
2014-12-03 10:46:48,428 org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean createNativeEntityManagerFactory
INFO: Building JPA container EntityManagerFactory for persistence unit 'tikron-data'
2014-12-03 10:46:48,428 org.hibernate.ejb.HibernatePersistence logDeprecation
WARN: HHH015016: Encountered a deprecated javax.persistence.spi.PersistenceProvider [org.hibernate.ejb.HibernatePersistence]; use [org.hibernate.jpa.HibernatePersistenceProvider] instead.
2014-12-03 10:46:48,448 org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing PersistenceUnitInfo [
name: tikron-data
...]
...
2014-12-03 10:46:51,101 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#6cccf90d: defining beans [propertyConfigurer,messageSource,entityManagerFactory,dataSource]; root of factory hierarchy
2014-12-03 10:46:51,111 org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization completed in 3374 ms
Thanks in advance.
You need to play your PROPAGATION_LEVEL and structure your service bean calls properly. If you're using #Transactional on your Service classes, what you described is normal, since the transaction demarcation happens on public methods level. So depending on the propagation level when entering the public method of the service bean, the transaction will either start, join an existing transaction, throw an exception or execute non-transactionally.
To have service methods execute in one transaction, its enough to have the propagation level set to support as you do in your GalleryService (providing that you don't override it on a method level), and call these methods from a single method of another service which is annotated #Transactional(propagation=Propagation.REQUIRED). Its important to have you're calls pass through a bean e.g. (galleryService.getPicture instead of local call getPicture), 'cause aspects that inject the transaction semantics work against a proxy that wraps the bean
#Service("exampleService")
#Transactional(propagation=Propagation.REQUIRED)
public class ExampleServiceImpl implements ExampleService {
#Autowired
private GalleryService galleryService;
#Override
public void singleTransaction() {
galleryService.getPicture
galleryService.getComments
}
...
}
a brief PROPAGATION_LEVEL glossary
MANDATORY
Support a current transaction, throw an exception if none exists.
NESTED
Execute within a nested transaction if a current transaction exists, behave like PROPAGATION_REQUIRED else.
NEVER
Execute non-transactionally, throw an exception if a transaction exists.
NOT_SUPPORTED
Execute non-transactionally, suspend the current transaction if one exists.
REQUIRED
Support a current transaction, create a new one if none exists.
REQUIRES_NEW
Create a new transaction, suspend the current transaction if one exists.
SUPPORTS
Support a current transaction, execute non-transactionally if none exists.
UPDATE with respect to the comment
But is combining service method calls into one service method the only way to handle those calls in one single transaction?
No, but in my opinion its your best option. Consider the article http://www.ibm.com/developerworks/java/library/j-ts2/index.html. What I'm describing is whats referred to in the article as API layer strategy. Its defined as
The API Layer transaction strategy is used when you have
coarse-grained methods that act as primary entry points to back-end
functionality. (Call them services if you would like.) In this
scenario, clients (be they Web-based, Web services based,
message-based, or even desktop) make a single call to the back end to
perform a particular request.
Now in the standard three-layer architecture you have the presentation, a business and a persistence layer. In simple words you can annotate your controllers, services or DAOs. Services are the ones holding the logical unit of work. If you annotate your controllers, they are part of your presentation layer, if your transactional semantics is there, and you decide to switch or add a non-http client (e.g. Swing client), you're bound to either migrate or duplicate your transaction logic. DAO layers should also not be the owners of transaction, 'the granularity of the DAO methods is much less than what is a business logical unit. I'm restraining from points like best-practice etc. but, if you're uncertain, choose your business (service) as your API transaction layer :)
You have numerous posts discussing this topic in all directions
why use #transactional with #service insted of with #controller
Where should "#Transactional" be place Service Layer or DAO
very good and fun reading, many opinions and very context-dependant

junit test with jparepository not creating object in database

I am starting a project using Spring 3.2.1.RELEASE, Hibernate 4.1.9.FINAL as jpa provider, spring data 1.2.0.RELEASE for repository and bitronix 2.1.3 as transaction manager. I am new to all of these technologies so I'm sorry if I'm missing some huge point.
I am running a simple unit test to create a User object in a database:
#ContextConfiguration(locations={"classpath:tests-context.xml"})
#Transactional
#TransactionConfiguration(transactionManager="transactionManager", defaultRollback=false)
#RunWith(SpringJUnit4ClassRunner.class)
public class UserTest extends AbstractTransactionalJUnit4SpringContextTests
{
#Autowired
protected UserMgmtService userService;
#Test
public void createUserTest()
{
User user = new User();
user.setFirstName("jonny");
user.setLastName("doe");
user.setUsername("user5");
user.setPasswordHash("1238");
user.setEmail("user5#domain.com");
System.out.println("Created user" + user);
User testUser = userService.saveUser(user);
System.out.println("Saved user" + testUser);
Assert.assertEquals("The user should be equal to saved user", user, testUser);
}
}
My test-context.xml used is as follows:
<context:annotation-config/>
<!-- Bitronix Transaction Manager embedded configuration -->
<bean id="btmConfig" factory-method="getConfiguration"
class="bitronix.tm.TransactionManagerServices">
</bean>
<!-- DataSource definition -->
<bean id="dataSource" class="bitronix.tm.resource.jdbc.PoolingDataSource"
init-method="init" destroy-method="close">
<property name="className" value="bitronix.tm.resource.jdbc.lrc.LrcXADataSource" />
<property name="uniqueName" value="jdbc/MySQL_Test_Repository" />
<property name="minPoolSize" value="0" />
<property name="maxPoolSize" value="5" />
<property name="allowLocalTransactions" value="true" />
<property name="driverProperties">
<props>
<prop key="driverClassName">com.mysql.jdbc.Driver</prop>
<prop key="url">jdbc:mysql://localhost:3306 MySQL_Test_Repository</prop>
<prop key="user">root</prop>
<prop key="password">123654</prop>
</props>
</property>
</bean>
<!-- create BTM transaction manager -->
<bean id="BitronixTransactionManager" factory-method="getTransactionManager"
class="bitronix.tm.TransactionManagerServices" depends-on="btmConfig,dataSource"
destroy-method="shutdown" />
<!-- Transaction manager -->
<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager"
depends-on="BitronixTransactionManager">
<property name="transactionManager" ref="BitronixTransactionManager" />
<property name="userTransaction" ref="BitronixTransactionManager" />
<property name="allowCustomIsolationLevels" value="true" />
</bean>
<!-- AOP configuration for transactions -->
<aop:config>
<aop:pointcut id="userServiceMethods"
expression="execution(* users.service.UserMgmtService.*(..))" />
<aop:advisor advice-ref="transactionAdvice"
pointcut-ref="userServiceMethods" />
</aop:config>
<!-- Transaction configuration -->
<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" rollback-for="Exception" />
</tx:attributes>
</tx:advice>
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- bean declaring the property map for the entity manager factory bean -->
<bean id="jpaPropertyMap" class="org.springframework.beans.factory.config.MapFactoryBean">
<property name="sourceMap">
<map>
<entry key="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
<!-- show the sql code executed -->
<entry key="hibernate.show_sql" value="true"/>
<!-- format the shown sql code -->
<entry key="hibernate.format_sql" value="true"/>
<!-- enables hibernate to create db schemas from classes;
Possible values: validate | update | create | create-drop
with create-drop the schema will be created/dropped for each hibernate sesssion open/close-->
<entry key="hibernate.hbm2ddl.auto" value="update"/>
<!-- sets the hibernate classname for the TransactionManagerLookup;
hibernate wraps and hides the underlying transaction system and needs a reference
to the transaction manager used -->
<entry key="hibernate.transaction.factory_class" value="org.hibernate.transaction.JTATransactionFactory"/>
<entry key="hibernate.transaction.manager_lookup_class"
value="org.hibernate.transaction.BTMTransactionManagerLookup"/>
</map>
</property>
</bean>
<!-- bean declaring the entity manager factory -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="ruleEditor.persistence"/>
<property name="dataSource" ref="dataSource" />
<property name="jpaPropertyMap" ref="jpaPropertyMap"/>
</bean>
<!-- The location where Spring scans for interfaces implementing the JPARepository
and creates their implementation -->
<jpa:repositories base-package="users.repository" />
<!-- Persistence annotations for post processing -->
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<!-- User service implementation bean -->
<bean id="userMgmtService" class="users.service.impl.UserMgmtServiceImpl"/>
</beans>
The Repository implementation is a standard JPARepository:
public interface UserRepository extends JpaRepository<User, Long>
{
User findByUsername(String username);
}
And the service implementation only makes calls to the repository:
#Service("userMgmtService")
public class UserMgmtServiceImpl implements UserMgmtService
{
#Autowired
private UserRepository userRepository;
#Override
public User saveUser(User user)
{
User savedUser = userRepository.save(user);
return savedUser;
}
The problem is that when I execute the test, it passes, but no user is created in the database. I thought it might be because of the Rollback behavior so I set the defaultRollback=false in the User test. Here is some information provided by the transaction framework when set to DEBUG that might be relevant:
Running UserTest
2013-02-12 13:01:12 INFO XmlBeanDefinitionReader:315 - Loading XML bean definitionsfrom class path resource [tests-context.xml]
2013-02-12 13:01:12 INFO GenericApplicationContext:510 - Refreshing org.springframework.context.support.GenericApplicationContext#7d95609: startup date [Tue Feb 12 13:01:12 CET 2013]; root of context hierarchy
2013-02-12 13:01:12 INFO GenericApplicationContext:1374 - Bean 'dataSource' of type [class bitronix.tm.resource.jdbc.PoolingDataSource] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2013-02-12 13:01:12 INFO GenericApplicationContext:1374 - Bean 'jpaPropertyMap' of type [class org.springframework.beans.factory.config.MapFactoryBean] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2013-02-12 13:01:12 INFO GenericApplicationContext:1374 - Bean 'jpaPropertyMap' of type [class java.util.LinkedHashMap] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2013-02-12 13:01:12 INFO LocalContainerEntityManagerFactoryBean:264 - Building JPA container EntityManagerFactory for persistence unit 'ruleEditor.persistence'
2013-02-12 13:01:13 INFO SchemaUpdate:182 - HHH000228: Running hbm2ddl schema update
2013-02-12 13:01:13 INFO SchemaUpdate:193 - HHH000102: Fetching database metadata
2013-02-12 13:01:13 INFO SchemaUpdate:205 - HHH000396: Updating schema
2013-02-12 13:01:13 INFO TableMetadata:65 - HHH000261: Table found: MySQL_Test_Repository.user
2013-02-12 13:01:13 INFO TableMetadata:66 - HHH000037: Columns: [id, enabled, first_name, username, email, password_hash, last_name]
2013-02-12 13:01:13 INFO TableMetadata:68 - HHH000108: Foreign keys: []
2013-02-12 13:01:13 INFO TableMetadata:69 - HHH000126: Indexes: [id, username, primary]
2013-02-12 13:01:13 INFO SchemaUpdate:240 - HHH000232: Schema update complete
2013-02-12 13:01:13 INFO BitronixTransactionManager:390 - Bitronix Transaction Manager version 2.1.3
2013-02-12 13:01:13 WARN Configuration:649 - cannot get this JVM unique ID. Make sure it is configured and you only use ASCII characters. Will use IP address instead (unsafe for production usage!).
2013-02-12 13:01:13 INFO Recoverer:152 - recovery committed 0 dangling transaction(s) and rolled back 0 aborted transaction(s) on 1 resource(s) [jdbc/MySQL_Test_Repository]
2013-02-12 13:01:14 INFO GenericApplicationContext:1374 - Bean 'entityManagerFactory' of type [class org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2013-02-12 13:01:14 INFO GenericApplicationContext:1374 - Bean 'org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#0' of type [class org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2013-02-12 13:01:14 INFO GenericApplicationContext:1374 - Bean 'org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0' of type [class org.springframework.transaction.annotation.AnnotationTransactionAttributeSource] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2013-02-12 13:01:14 INFO GenericApplicationContext:1374 - Bean 'org.springframework.transaction.config.internalTransactionAdvisor' of type [class org.springframework.transaction.interceptor.BeanFactoryTransactionAttributeSourceAdvisor] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2013-02-12 13:01:14 INFO JtaTransactionManager:470 - Using JTA UserTransaction: a BitronixTransactionManager with 0 in-flight transaction(s)
2013-02-12 13:01:14 INFO JtaTransactionManager:481 - Using JTA TransactionManager: a BitronixTransactionManager with 0 in-flight transaction(s)
2013-02-12 13:01:14 DEBUG NameMatchTransactionAttributeSource:94 - Adding transactional method [*] with attribute [PROPAGATION_REQUIRED,ISOLATION_DEFAULT,-Exception]
2013-02-12 13:01:14 DEBUG AnnotationTransactionAttributeSource:106 - Adding transactional method 'createUserTest' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
2013-02-12 13:01:14 DEBUG AnnotationTransactionAttributeSource:106 - Adding transactional method 'createUserTest' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
2013-02-12 13:01:14 DEBUG JtaTransactionManager:365 - Creating new transaction with name [createUserTest]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
2013-02-12 13:01:14 INFO TransactionalTestExecutionListener:279 - Began transaction (1): transaction manager [org.springframework.transaction.jta.JtaTransactionManager#2a3998f8]; rollback [false]
Created userusers.model.User#63aa9dc1[userId=0,first name=jonny,last name=doe,email=user5#domain.com,username=user5,password=1238,enabled=false]
2013-02-12 13:01:14 DEBUG JtaTransactionManager:470 - Participating in existing transaction
2013-02-12 13:01:14 DEBUG JtaTransactionManager:470 - Participating in existing transaction
Saved userusers.model.User#6b38579e[userId=0,first name=jonny,last name=doe,email=user5#domain.com,username=user5,password=1238,enabled=false]
2013-02-12 13:01:14 DEBUG JtaTransactionManager:752 - Initiating transaction commit
2013-02-12 13:01:14 WARN Preparer:69 - executing transaction with 0 enlisted resource
2013-02-12 13:01:14 INFO TransactionalTestExecutionListener:299 - Committed transaction after test execution for test context [TestContext#5a93c236 testClass = UserTest, testInstance = UserTest#1ab395af, testMethod = createUserTest#UserTest, testException = [null], mergedContextConfiguration = [MergedContextConfiguration#42821db testClass = UserTest, locations = '{classpath:tests-context.xml}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader']]
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 3.029 sec
2013-02-12 13:01:14 INFO GenericApplicationContext:1042 - Closing org.springframework.context.support.GenericApplicationContext#7d95609: startup date [Tue Feb 12 13:01:12 CET 2013]; root of context hierarchy
2013-02-12 13:01:14 INFO BitronixTransactionManager:320 - shutting down Bitronix Transaction Manager
2013-02-12 13:01:14 INFO LocalContainerEntityManagerFactoryBean:441 - Closing JPA EntityManagerFactory for persistence unit 'ruleEditor.persistence'
The logs show a testException=[null] but I have no idea why that would be.. I even tried to use the saveAndFlush() method provided by the JPARepository but doing so I get the error javax.persistence.TransactionRequiredException: no transaction is in progress
So if anyone has some idea of what I am doing wrong and can point me in the right direction I would very much appreciate the help.
After some careful reading of the logs, I found this warning:
WARN Ejb3Configuration:1309 - HHH000193: Overriding hibernate.transaction.factory_class is dangerous, this might break the EJB3 specification implementation
This was related to a property that I had set in the jpaPropertyMap bean in my tests-context.xml file:
<entry key="hibernate.transaction.factory_class" value="org.hibernate.transaction.JTATransactionFactory" />
It turns out that once I removed this line in the configuration file I could see hibernate performing an "insert" action and the user was actually created in the database. Since I am new to spring and all the technologies I used, I must have copied the configuration from somewhere without really analysing it. So, I am now able to run junit4 tests in a project using spring data, hibernate and bitronix as transaction manager.

PreAuthorize doesn't work

I'm writing a socket server (no web-application !) application and want to use method-based security to handle my ACL needs. i followed a small tutorial i found spring security by example
so far i configured:
<security:global-method-security pre-post-annotations="enabled">
<security:expression-handler ref="expressionHandler" />
</security:global-method-security>
<bean id="expressionHandler" class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler">
<property name="permissionEvaluator">
<bean id="permissionEvaluator" class="myPermissionEvaluator" />
</property>
</bean>
<security:authentication-manager id="authenticationmanager">
<security:authentication-provider ref="authenticationprovider" />
</security:authentication-manager>
<bean id="authenticationprovider" class="myAuthenticationProvider" />
With a service bean:
#Named
public class ChannelService {
#PreAuthorize("isAuthenticated() and hasPermission(#channel, 'CHANNEL_WRITE')")
public void writeMessage(Channel channel, String message) { ... }
}
Everything compiles and the application starts and works fine, but without access control. My debug log shows that my Evaluator is never called.
When i tried something similar with a #Secured annotation the annotation was evaluated and access was denied. but simple role based security isn't enough for my requirements.
EDIT
did some more tests: when i configure only secured-annotations="enabled" the role based security works. when configure pre-post-annotations="enabled" in ADDITION neither secured nor preauthorize works. when i configure only pre-post-annotations it still doesn't work.
EDIT2
some more tests:
with only secured_annotations="enabled" the call to my channelservice goes through the Cglib2AopProxy
as soon as i activate pre-post-annotations the call lands directly in the channelservice. no interceptor, no proxy, nothing.
I'm getting kind of desperate...
EDIT3
I debug-logged my testruns here is the part for spring-security
with only secured-annotations="enabled"
2012-04-12 13:36:46,171 INFO [main] o.s.s.c.SpringSecurityCoreVersion - You are running with Spring Security Core 3.1.0.RELEASE
2012-04-12 13:36:46,174 INFO [main] o.s.s.c.SecurityNamespaceHandler - Spring Security 'config' module version is 3.1.0.RELEASE
2012-04-12 13:36:49,042 DEBUG [main] o.s.s.a.m.DelegatingMethodSecurityMetadataSource - Caching method [CacheKey[mystuff.UserService; public void mystuff.UserService.serverBan(java.lang.String,mystuff.models.User,org.joda.time.DateTime)]] with attributes [user]
2012-04-12 13:36:49,138 DEBUG [main] o.s.s.a.i.a.MethodSecurityInterceptor - Validated configuration attributes
2012-04-12 13:36:49,221 DEBUG [main] o.s.s.a.m.DelegatingMethodSecurityMetadataSource - Caching method [CacheKey[mystuff.ChannelService; public void mystuff.ChannelService.writeMessage(mystuff.models.Channel,java.lang.String)]] with attributes [blubb]
2012-04-12 13:36:51,159 DEBUG [main] o.s.s.a.ProviderManager - Authentication attempt using mystuff.GlobalchatAuthenticationProvider
2012-04-12 13:36:56,166 DEBUG [Timer-1] o.s.s.a.ProviderManager - Authentication attempt using mystuff.GlobalchatAuthenticationProvider
2012-04-12 13:36:56,183 DEBUG [Timer-1] o.s.s.a.i.a.MethodSecurityInterceptor - Secure object: ReflectiveMethodInvocation: public void mystuff.ChannelService.writeMessage(mystuff.models.Channel,java.lang.String); target is of class [mystuff.ChannelService]; Attributes: [blubb]
2012-04-12 13:36:56,184 DEBUG [Timer-1] o.s.s.a.i.a.MethodSecurityInterceptor - Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#312e8aef: Principal: mystuff.UserId#ced1752b; Credentials: [PROTECTED]; Authenticated: true; Details: null; Not granted any authorities
Exception in thread "Timer-1" org.springframework.security.access.AccessDeniedException: Access is denied
at org.springframework.security.access.vote.AbstractAccessDecisionManager.checkAllowIfAllAbstainDecisions(AbstractAccessDecisionManager.java:70)
at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:88)
at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:205)
at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:59)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:622)
at mystuff.ChannelService$$EnhancerByCGLIB$$3ad5e57f.writeMessage(<generated>)
at mystuff.run(DataGenerator.java:109)
at java.util.TimerThread.mainLoop(Timer.java:512)
at java.util.TimerThread.run(Timer.java:462)
2012-04-12 13:36:56,185 DEBUG [Timer-1] o.s.s.access.vote.AffirmativeBased - Voter: org.springframework.security.access.vote.RoleVoter#1cfe174, returned: 0
2012-04-12 13:36:56,185 DEBUG [Timer-1] o.s.s.access.vote.AffirmativeBased - Voter: org.springframework.security.access.vote.AuthenticatedVoter#da89a7, returned: 0
with pre-post-annotations="enabled"
2012-04-12 13:39:54,926 INFO [main] o.s.s.c.SpringSecurityCoreVersion - You are running with Spring Security Core 3.1.0.RELEASE
2012-04-12 13:39:54,929 INFO [main] o.s.s.c.SecurityNamespaceHandler - Spring Security 'config' module version is 3.1.0.RELEASE
2012-04-12 13:39:54,989 INFO [main] o.s.s.c.m.GlobalMethodSecurityBeanDefinitionParser - Using bean 'expressionHandler' as method ExpressionHandler implementation
2012-04-12 13:39:59,812 DEBUG [main] o.s.s.a.ProviderManager - Authentication attempt mystuff.GlobalchatAuthenticationProvider
2012-04-12 13:39:59,850 DEBUG [main] o.s.s.a.i.a.MethodSecurityInterceptor - Validated configuration attributes
As far as i understand this log output spring doesn't realize my beans need to be proxied, so they aren't and so i don't get security.
EDIT4
I debug-logged the complete sprint startup... (thats one big log) and there i find:
2012-04-12 14:40:41,385 INFO [main] o.s.c.s.ClassPathXmlApplicationContext - Bean 'channelService' of type [class mystuff.ChannelService] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
is there a way to figure out why? because as far as i understand it. because of #preauthorize the bean should be eligible. with only secured-annotations="enabled" i get a post processing log.
This configuration worked just as expected for me:
<bean id="securityExpressionHandler"
class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler" />
<bean id="preInvocationAdvice"
class="org.springframework.security.access.expression.method.ExpressionBasedPreInvocationAdvice"
p:expressionHandler-ref="securityExpressionHandler" />
<util:list id="decisionVoters">
<bean class="org.springframework.security.access.vote.AuthenticatedVoter" />
<bean class="org.springframework.security.access.vote.RoleVoter" />
<bean class="org.springframework.security.access.prepost.PreInvocationAuthorizationAdviceVoter"
c:pre-ref="preInvocationAdvice" />
</util:list>
<bean id="accessDecisionManager"
class="org.springframework.security.access.vote.UnanimousBased"
c:decisionVoters-ref="decisionVoters" />
<sec:global-method-security
authentication-manager-ref="authenticationManager"
access-decision-manager-ref="accessDecisionManager"
pre-post-annotations="enabled" />
I got the log message:
WARN org.springframework.security.access.expression.DenyAllPermissionEvaluator -
Denying user jack permission 'CHANNEL_WRITE' on object Channel[ name=null ]
And an exception:
org.springframework.security.access.AccessDeniedException: Access is denied
From a simple test:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration("classpath:META-INF/spring/application-context.xml")
public class SpringSecurityPrePostTest {
#Autowired
ChannelService channelService;
#Test
public void shouldSecureService() throws Exception {
Authentication authentication = new UsernamePasswordAuthenticationToken("jack", "sparrow");
SecurityContext securityContext = SecurityContextHolder.getContext();
securityContext.setAuthentication(authentication);
channelService.writeMessage(new Channel(), "test");
}
}
One thing I did diffrent was to use interface on a service and JDK proxies instead of cglib:
public interface ChannelService {
void writeMessage(Channel channel, String message);
}
and:
#Component
public class ChannelServiceImpl implements ChannelService {
private static final Logger LOG = LoggerFactory.getLogger(ChannelServiceImpl.class);
#Override
#PreAuthorize("isAuthenticated() and hasPermission(#channel, 'CHANNEL_WRITE')")
public void writeMessage(Channel channel, String message) {
LOG.info("Writing message {} to: {}" , message, channel);
}
}
UPDATE1:
With this simplified config I get the same result:
<bean id="securityExpressionHandler"
class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler" />
<sec:global-method-security
authentication-manager-ref="authenticationManager"
pre-post-annotations="enabled">
<sec:expression-handler ref="securityExpressionHandler" />
</sec:global-method-security>
UPDATE2:
The debug message from Edit4 indicates that channelService may not have bean proxied at all as it got classified as not eligible for auto-proxying. This qiestion answers similar problem - try not to use #Autowired or any other mechanism based on BeanPostProcessors to set up the beans involved in security checks (i.e. myPermissionEvaluator).
UPDATE3:
You cannot use secured resources (i.e. services) within beans responsible for security checks! This creates a dependency loop and is a error in Your configuration. You must use lover level access (i.e. DAO) to check permissions, anything that is not secured! Implementing security checks using secured resources is not what You want to do.
If despite using not secured resources with #Autowired things don't work as expected, try using old-school XML confiuration style for all beans involved in security checks. Also remember that <context:component-scan /> is in fact a BeanDefinitionRegistryPostProcessor and introduces the scanned beans into the BeanFactory after all the ones declared in XML are already there.
it works,
make sure that you have <sec:global-method-security pre-post-annotations="enabled"/> in your spring servlet (ie where you may have your <mvc:annotation-driven/>)
"sec" is from xmlns:sec="http://www.springframework.org/schema/security"

Resources