Posts Tagged ‘J2EE’

Multicast pitfalls

Multicast might seem like a great idea for 2 problems: iptv and discovery. In my case it seemed like a very good idea for cluster node auto-discovery: no need to configure each node with all the other nodes, no need to know the number of nodes beforehand, use a single node configuration. However it seems that more and more nodes are discovered you can fall into some very dark pitfalls which could eat days and nights of your time until either you find a solution, either you revert to tcp or udp unicast. And the conclusion is that multicast at network level is not something you can assume working as is the case for tcp or udp unicast. Here are some pitfalls I found in various deployments and the solution or lack of, I could or could not find. (more…)

Replicated EhCache, the uneasy road

At first replicating EhCache seems a very easy task, just need to configure ehcache.xml with RMI and you are ready. Is it so?

(more…)

JBoss migration – Quartz

This is a continuation of the previous article regarding some migration points (1, 2) from JBoss 4.2.2-GA to JBoss 7.1.1 and, presumably, Tomcat 7.

3. Quartz

Quartz migration has been the simplest of all, by far.
(more…)

JBoss migration – the HAR archive

This is a continuation of the previous article regarding some migration points from JBoss 4.2.2-GA to JBoss 7.1.1 and, presumably, Tomcat 7.

2. The HAR archive

The HAR archive was a nice mechanism which allowed hibernate integration. A ${name}.har file was created, containing all the mappings (*.hbm.xml) and data classes (*.class), allong with a hibernate-service.xml (later renamed to service-hibernate.xml in JBoss 5). This took care of creating the SessionFactory and making it accessible through JNDI. Creating a session in code become:

InitialContext ctx = new InitialContext();
SessionFactory factory = (SessionFactory) ctx.lookup("XName");
return factory.openSession();

(more…)

JBoss migration – the data source

I have spent a lot of time lately trying to create a migration plan for an application currently running on JBoss 4.2.2. Since this application development started a few migration attempts to newer versions of JBoss have been done (see for 5.1) but as it seems each version has different style configuration files and this application is expected to have a long lifetime the work seems a bit futile so in parallel of
migrating to JBoss-7.1.1 I’ve tried to migrate to Tomcat since our use of EJB’s is limited and other MBeans can be refactored in simpler ways. Unlike JBoss, Tomcat configuration seems to be eternal and by all means simpler.
(more…)

RIA’s. Where to go from now?

I was a big fan of Flex. The code was clean, object-oriented, re-usable. We even had the bonus of E4X. We’ve wrote the interface of a huge project using it and I know there was no way we could have had such a rich client other than using native code. We developed multiplatform and the client ran multiplatform without a bit of change. The deployment was easy and the administration on the client side minimal. Everyone had flash.

(more…)

To migrate or not to migrate

This is not a guide, nor intended to help, it’s a steam valve for my efforts to migrate an application to jboss 7 as each exception can take minutes or hours to solve without altering the original code.

Caused by: org.jboss.jca.common.metadata.ParserException: IJ010061: Unexpected element: local-tx-datasource
        at org.jboss.jca.common.metadata.ds.DsParser.parseDataSources(DsParser.java:183)
        at org.jboss.jca.common.metadata.ds.DsParser.parse(DsParser.java:119)
        at org.jboss.jca.common.metadata.ds.DsParser.parse(DsParser.java:82)
        at org.jboss.as.connector.deployers.processors.DsXmlDeploymentParsingProcessor.deploy(DsXmlDeploymentParsingProcessor.java:80)

        at org.jboss.as.ee.metadata.MethodAnnotationAggregator.runtimeAnnotation
Information(MethodAnnotationAggregator.java:58)
        at org.jboss.as.ee.component.deployers.InterceptorAnnotationProcessor.ha
ndleAnnotations(InterceptorAnnotationProcessor.java:85)
        at org.jboss.as.ee.component.deployers.InterceptorAnnotationProcessor.pr
ocessComponentConfig(InterceptorAnnotationProcessor.java:70)
        at org.jboss.as.ee.component.deployers.InterceptorAnnotationProcessor.de
ploy(InterceptorAnnotationProcessor.java:55)
        at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:113) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
        ... 5 more
Caused by: java.lang.NoClassDefFoundError: org/hibernate/HibernateException
        at java.lang.Class.getDeclaredFields0(Native Method) [rt.jar:1.6.0_23]
        at java.lang.Class.privateGetDeclaredFields(Class.java:2291) [rt.jar:1.6.0_23]
        at java.lang.Class.getDeclaredFields(Class.java:1743) [rt.jar:1.6.0_23]
        at org.jboss.as.server.deployment.reflect.ClassReflectionIndex.(ClassReflectionIndex.java:57) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
        at org.jboss.as.server.deployment.reflect.DeploymentReflectionIndex.getClassIndex(DeploymentReflectionIndex.java:66) [jboss-as-server-7.1.1.Final.jar:7.1.1.Final]

        at org.apache.catalina.core.StandardContext.contextListenerStart(StandardContext.java:3392) [jbossweb-7.0.13.Final.jar:]
        at org.apache.catalina.core.StandardContext.start(StandardContext.java:3850) [jbossweb-7.0.13.Final.jar:]
        at org.jboss.as.web.deployment.WebDeploymentService.start(WebDeploymentService.java:90) [jboss-as-web-7.1.1.Final.jar:7.1.1.Final]
        at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811)
        at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746)
        at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) [rt.jar:1.6.0_23]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) [rt.jar:1.6.0_23]
        at java.lang.Thread.run(Thread.java:662) [rt.jar:1.6.0_23]
Caused by: java.lang.ClassNotFoundException: org.jboss.as.jmx.PluggableMBeanServerBuilder from [Module "deployment.diapason.ear.diapason-web.war:main" from Service Module Loader]

(MSC service thread 1-6) Exception sending context initialize
d event to listener instance of class org.jbpm.web.JobExecutorLauncher: org.jbpm
.JbpmException: couldn't parse jbpm configuration from resource 'jbpm.cfg.xml'
        at org.jbpm.JbpmConfiguration.getInstance(JbpmConfiguration.java:292) [j
bpm-jpdl.jar:3.2.3 (date:18-Jun-2008 00:51)]
        at org.jbpm.web.JobExecutorLauncher.contextInitialized(JobExecutorLaunch
er.java:55) [jbpm-jpdl.jar:3.2.3 (date:18-Jun-2008 00:51)]
        at org.apache.catalina.core.StandardContext.contextListenerStart(StandardContext.java:3392) [jbossweb-7.0.13.Final.jar:]
        at org.apache.catalina.core.StandardContext.start(StandardContext.java:3850) [jbossweb-7.0.13.Final.jar:]
        at org.jboss.as.web.deployment.WebDeploymentService.start(WebDeploymentService.java:90) [jboss-as-web-7.1.1.Final.jar:7.1.1.Final]
        at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811)
        at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746)

host].[/dix]] (MSC service thread 1-4) StandardWrapper.Throwable: java.lang.NoClassDefFoundError: org/mozilla/javascript/WrappedException
        at java.lang.Class.forName0(Native Method) [rt.jar:1.6.0_23]
        at java.lang.Class.forName(Class.java:169) [rt.jar:1.6.0_23]

ava.lang.IllegalAccessError: tried to access class 
org.hibernate.cfg.Configuration$1 from class org.hibernate.cfg.Configuration
08:21:17,924 ERROR [stderr] (JbpmJobExecutor:127.0.1.1:1)       at org.hibernate
.cfg.Configuration.buildMapping(Configuration.java:2923)
08:21:17,925 ERROR [stderr] (JbpmJobExecutor:127.0.1.1:1)       at org.hibernate
.cfg.Configuration.(Configuration.java:269)
08:21:17,925 ERROR [stderr] (JbpmJobExecutor:127.0.1.1:1)       at org.hibernate
.cfg.Configuration.(Configuration.java:302)
08:21:17,925 ERROR [stderr] (JbpmJobExecutor:127.0.1.1:1)       at org.jbpm.db.h
ibernate.HibernateHelper.createConfiguration(HibernateHelper.java:74)

from Service Module Loader: java.lang.LinkageError:

Caused by: java.lang.NoClassDefFoundError: org/jboss/as/clustering/infinispan/subsystem/CacheConfigurationService
        at org.jboss.as.jpa.hibernate3.HibernatePersistenceProviderAdaptor.addProviderDependencies(HibernatePersistenceProviderAdaptor.java:104)
        at org.jboss.as.jpa.processor.PersistenceUnitDeploymentProcessor.deployPersistenceUnit(PersistenceUnitDeploymentProcessor.java:345)
        at org.jboss.as.jpa.processor.PersistenceUnitDeploymentProcessor.addPuService(PersistenceUnitDeploymentProcessor.java:258)
        at org.jboss.as.jpa.processor.PersistenceUnitDeploymentProcessor.handleEarDeployment(PersistenceUnitDeploymentProcessor.java:216)
        at org.jboss.as.jpa.processor.PersistenceUnitDeploymentProcessor.deploy(PersistenceUnitDeploymentProcessor.java:119)

And so on…

Enable ehcache debug in jboss

I’ve been trying to setup ehcache clustering in JBoss and unless there is a problem I’ve noticed there is little logging involved. So enabling logging should be a straightforward operation, I said. And it sure is if you bother to consider that the default ehcache distribution uses slf4j which is packed only with the jdk logger. So by default no matter how much you configure log4j no logging will be done. Of course after you add the log4j12 logger (by downloading the corresponding jar from slf4j distribution) it’s only a matter of doing something like this in the jboss-log4j.xml file:

<appender name="EHCACHE" class="org.jboss.logging.appender.RollingFileAppender">
                <errorHandler class="org.jboss.logging.util.OnlyOnceErrorHandler" />
                <param name="File" value="${jboss.server.log.dir}/ehcache.log" />
                <param name="Append" value="true" />
                <param name="MaxFileSize" value="10MB" />
                <param name="MaxBackupIndex" value="10" />
                <param name="Threshold" value="TRACE" />
                <layout class="org.apache.log4j.PatternLayout">
                        <param name="ConversionPattern" value="%d %-5p [%c] %m%n" />
                </layout>
        </appender>
 
 
        <category name="net.sf.ehcache">
                <priority value="TRACE" />
                <appender-ref ref="EHCACHE" />
        </category>

Applies to ehcache 2.4.* and jboss < 7.

Call Oracle procedure from hibernate

After debuging for a few hours I’ve found the proper way of calling an Oracle function from hibernate and to use the return parameters. Here is the solution. (more…)

Hibernate JbossCache integration

Introduction

JbossCache is a wonderfully complex piece of software. Trying to use it with Hibernate might seem an easy task at first but in reality it can also prove wonderfully complicated.

First question is: why would you consider using it in the first place? Compared to ehcache for instance there are a few theoretical advantages: clustering (scalability), configurability and jmx monitoring.

Next question which is not quite obvious is which version to use? The answer is a bit complicated since there are a lot of changes in versions which vary from architectural to configuration points. This document is concerned with integration of hibernate 3.3.1 with jboss cache 3.1.0 (Cascabel) as they are shipped in jboss 5.1.0.GA.

Choices

I think most people consider that cache integration should be a matter of switching a config option. I cannot argue with this logic and for them the most appropriate configuration (as described in most documents) is as following (if using a hibernate-service.xml .har configuration):

<property name="cacheRegionFactoryClass">org.hibernate.cache.jbc2.MultiplexedJBossCacheRegionFactory</property>

along with activation of second level and query cache:

<property name="queryCacheEnabled">true</property>
<property name="secondLevelCacheEnabled">true</property>

This will probably work from start but also from start you will loose one of the advantages: jmx monitoring

Let’s go back to the cacheRegionFactoryClass and it’s hibernate.cache.region.factory_class equivalent. The hibernate documentation states there are 4 options for this property. Here is my understanding of them:

  • SharedJBossCacheRegionFactory will create a Cache (as in org.jboss.cache.Cache) based on a treecache.xml configuration and use it for it’s caching purposes. You can provide your configuration (in fact you must provide it) and everything seems perfect except that you cannot have jmx instrumentation. I have found no way to obtain the Cache from a SessionFactory and pass it to a CacheJmxWrapper for instrumentation.
  • JndiSharedJBossCacheRegionFactory seems the perfect solution for the above problem as you can create your cache and jmx via a -jboss-beans.xml configuration and then pass it to hibernate. Can you? No. As there is no way to bind the cache to JNDI from the -jboss-beans.xml configuration. No problem I might say. I will bind it myself. However the Cache object is not serializable and you will end with an exception. No again.
javax.naming.CommunicationException [Root exception is java.io.NotSerializableException:
  • MultiplexedJBossCacheRegionFactory is the most recommended solution. What it does is to create multiple Caches managed by a CacheManager. Remember: you can still have multiple cache regions with different eviction policies even in a single cache so the reason for multiple caches seems an extreme case for me such as: having different passivations or transport options. Note that this CacheManager is created by hibernate and is not exposed to jmx. If you want to have a clustering environment with not much fuss you will end up with jboss default cache manager which also creates several Cache’s of it’s own.
  • JndiMultiplexedJBossCacheRegionFactory seems then a wises choice as it will let you connect/use the existing CacheManager created by jboss (I will discuss configuration issues later).

Configuration

Here are some example configurations for the cases described above.

treecache.xml for the SharedJbossCacheRegionFactory

You have to put it somewhere in the classpath root, for instance in your .har file. The following example is local, does not uses jgroups and has a special region for timestamps.

<?xml version="1.0" encoding="UTF-8"?>
<jbosscache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:jboss:jbosscache-core:config:3.1">
 
	<!--
      isolation levels supported: READ_COMMITTED and REPEATABLE_READ
      nodeLockingSchemes: mvcc, pessimistic (deprecated), optimistic (deprecated)
    -->
	<locking isolationLevel="REPEATABLE_READ" lockParentForChildInsertRemove="false" lockAcquisitionTimeout="20000" nodeLockingScheme="mvcc" writeSkewCheck="false" useLockStriping="true" concurrencyLevel="500" />
 
	<!-- Used to register a transaction manager and participate in ongoing transactions. -->
	<transaction transactionManagerLookupClass="org.jboss.cache.transaction.GenericTransactionManagerLookup" syncRollbackPhase="false" syncCommitPhase="false" />
 
	<!-- Used to register JMX statistics in any available MBean server -->
	<jmxStatistics enabled="true" />
 
	<!-- If region based marshalling is used, defines whether new regions are inactive on startup. -->
	<startup regionsInactiveOnStartup="true" />
 
	<!--
      Used to register JVM shutdown hooks.
      hookBehavior: DEFAULT, REGISTER, DONT_REGISTER
    -->
	<shutdown hookBehavior="DEFAULT" />
 
	<!-- Used to define async listener notification thread pool size -->
	<listeners asyncPoolSize="1" asyncQueueSize="100000" />
 
	<!-- Used to enable invocation batching and allow the use of Cache.startBatch()/endBatch() methods. -->
	<invocationBatching enabled="false" />
 
	<!-- serialization related configuration, used for replication and cache loading -->
	<serialization objectInputStreamPoolSize="12" objectOutputStreamPoolSize="14" version="3.0.0" marshallerClass="org.jboss.cache.marshall.VersionAwareMarshaller" useLazyDeserialization="false" useRegionBasedMarshalling="false" />
 
	<!--
      Eviction configuration.  WakeupInterval defines how often the eviction thread runs, in milliseconds.  0 means
      the eviction thread will never run.
   -->
	<eviction wakeUpInterval="500">
		<default algorithmClass="org.jboss.cache.eviction.LRUAlgorithm" eventQueueSize="200000">
			<property name="maxNodes" value="5000" />
			<property name="timeToLive" value="40000" />
		</default>
 
		<region name="/TS" algorithmClass="org.jboss.cache.eviction.NullEvictionAlgorithm">
		</region>
	</eviction>
</jbosscache>

-jboss-beans.xml deployement

Of a cache which cannot be bound to jndi and passed to SharedJbossCacheRegionFactory, also local:

<?xml version="1.0" encoding="UTF-8"?>
<deployment xmlns="urn:jboss:bean-deployer:2.0">
 
   <!-- First we create a Configuration object for the cache -->
   <bean name="DiapasonCacheConfig"
         class="org.jboss.cache.config.Configuration">
      <property name="runtimeConfig">
         <bean class="org.jboss.cache.config.RuntimeConfig">
            <property name="transactionManager">
               <inject bean="jboss:service=TransactionManager" 
                       property="TransactionManager"/>
            </property>
            <!--
            <property name="muxChannelFactory"><inject bean="JChannelFactory"/></property>
            -->
         </bean>
      </property>
 
      <property name="multiplexerStack">udp</property>
      <property name="clusterName">Diapason-EntityCache</property>
      <property name="isolationLevel">REPEATABLE_READ</property>
      <property name="cacheMode">LOCAL</property>
      <property name="stateRetrievalTimeout">15000</property>
      <property name="syncReplTimeout">20000</property>
      <property name="lockAcquisitionTimeout">15000</property>
      <property name="exposeManagementStatistics">true</property>
   </bean>
 
 
   <!-- Factory to build the Cache. -->
   <bean name="DefaultCacheFactory" class="org.jboss.cache.DefaultCacheFactory">      
      <constructor factoryClass="org.jboss.cache.DefaultCacheFactory"
                   factoryMethod="getInstance" />
   </bean>
 
   <!-- The cache itself -->
   <bean name="DiapasonCache" class="org.jboss.cache.Cache">
      <constructor factoryMethod="createCache">
          <factory bean="DefaultCacheFactory"/>
          <parameter class="org.jboss.cache.config.Configuration"><inject bean="DiapasonCacheConfig"/></parameter>
          <parameter class="boolean">false</parameter>
      </constructor>
   </bean>
 
   <!-- JMX Management -->
   <bean name="DiapasonCacheJmxWrapper" class="org.jboss.cache.jmx.CacheJmxWrapper">
      <annotation>@org.jboss.aop.microcontainer.aspects.jmx.JMX(name="jboss.cache:service=DiapasonTreeCache", exposedInterface=org.jboss.cache.jmx.CacheJmxWrapperMBean.class, registerDirectly=true)</annotation>
      <constructor>
          <parameter><inject bean="DiapasonCache"/></parameter>
      </constructor>
   </bean>
<!-- a bean I tried to use to register the cache to jndi, ignore
	<bean name="CacheX" class="ro.len.CacheX">
		<property name="cache"><inject bean="DiapasonCache"/></property>
   </bean>
-->
</deployment>

MultiplexedJBossCacheRegionFactory

No config is needed in this case as hibernate will use 2 files jbc2-configs.xml and jgroups-stacks.xml both found in hibernate-jbosscache2.jar. Of course if you want to take advantage of the configurability of Jboss Cache you will have to take these files and adapt them to your need.

JndiMultiplexedJBossCacheRegionFactory

This option will give you most of the things you want and can be configured as following:

<property name="cacheRegionFactoryClass">org.hibernate.cache.jbc2.JndiMultiplexedJBossCacheRegionFactory</property>
<property name="deployedCacheManagerJndiName">java:/CacheManager</property>

This will make use of the existing CacheManager which is registered to JNDI. However if using the “default” configuration for jboss this is not the case. You will need to copy jboss-cache-manager.sar and  jgroups-channelfactory.sar from the all/deploy/cluster to default/deploy/cluster along with an extra jar for pojo cache (jbosscache-pojo.jar, still don’t know the use of that).

In order to configure your cache you will need to edit the jboss-cache-manager-jboss-beans.xml file notably the optimistic-entity entry which hibernate will use.

Conclusions

You might ask: why use jboss cache after all? it does seem a bit too complicated. I think you can find at least the following benefits:

  • Configurability related to cache regions. This seems the most interesting benefit from my point of view, can be done in any of the previous configs and does not require a CacheManager or clustering.This is where you can configure various eviction policies. You might want for instance some data to be evicted much slower than other or some data never to evicted. This means of course some mapping (.hbm) changes in case of entities consisting in adding the region attribute to the cache part of the mapping and some code change in case of queries.
  • JMX is of great use. First, it allows to see that the eviction configured really works and second it shows lock problems which unfortunately where a problem in previous jboss cache versions (as in jboss 4.2.2 GA). Let’s hope it will no longer be the case.
  • Of least importance for most people it will be clustering. But even if initially it might be of reduced importance it’s good to know if you ever need it support is already there and only some configuration is required

Links

Finally here are some links which I read a lot of times in the process of testing these configurations and are the base for this article which intended to be much more shorter: