<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title>Java-Ee on despatches</title><link>https://icle.es/tags/java-ee/</link><description>Recent content in Java-Ee on despatches</description><generator>Hugo</generator><language>en</language><lastBuildDate>Wed, 18 Mar 2026 15:13:17 +0000</lastBuildDate><atom:link href="https://icle.es/tags/java-ee/index.xml" rel="self" type="application/rss+xml"/><item><title>Getting started on seam-security, picketlink IDM and JPAIdentityStore</title><link>https://icle.es/2012/10/17/getting-started-on-seam-security-picketlink-idm-and-jpaidentitystore/</link><pubDate>Wed, 17 Oct 2012 10:40:28 +0000</pubDate><guid>https://icle.es/2012/10/17/getting-started-on-seam-security-picketlink-idm-and-jpaidentitystore/</guid><description>&lt;p>I love how JBoss 7(.1) has everything working out of the box - not much fiddling
with jars or suchlike and with Arquillian, everything really was a treat to get
started on a new project. This was until I had to sort out security with
seam-security.&lt;/p>
&lt;p>To be fair, the main issue was just poor documentation. It took me a day to sort
out what should essentially have taken an hour(or two)&lt;/p>
&lt;p>The documentation you get to from
&lt;a href="http://www.seamframework.org/Seam3/SecurityModule">http://www.seamframework.org/Seam3/SecurityModule&lt;/a> seems to be out of date. The
fact that the page referes to version 3.0.0.Alpha1 and Alpha2 should have tipped
me off but the url for the doc suggested it was the latest.&lt;/p>
&lt;p>The more up to date documentation I found was
at http://docs.jboss.org/seam/3/3.1.0.Final/reference/en-US/html/pt04.html&lt;/p>
&lt;p>I followed
&lt;a href="http://docs.jboss.org/seam/3/3.1.0.Final/reference/en-US/html/security-identitymanagement.html" title="Identity Management">chapter 33&lt;/a>
on there and I won't repeat it here for the sake of brevity.&lt;/p>
&lt;p>What follows are the additional steps I had to take to get it to work.&lt;/p></description><content:encoded><![CDATA[<p>I love how JBoss 7(.1) has everything working out of the box - not much fiddling
with jars or suchlike and with Arquillian, everything really was a treat to get
started on a new project. This was until I had to sort out security with
seam-security.</p>
<p>To be fair, the main issue was just poor documentation. It took me a day to sort
out what should essentially have taken an hour(or two)</p>
<p>The documentation you get to from
<a href="http://www.seamframework.org/Seam3/SecurityModule">http://www.seamframework.org/Seam3/SecurityModule</a> seems to be out of date. The
fact that the page referes to version 3.0.0.Alpha1 and Alpha2 should have tipped
me off but the url for the doc suggested it was the latest.</p>
<p>The more up to date documentation I found was
at http://docs.jboss.org/seam/3/3.1.0.Final/reference/en-US/html/pt04.html</p>
<p>I followed
<a href="http://docs.jboss.org/seam/3/3.1.0.Final/reference/en-US/html/security-identitymanagement.html" title="Identity Management">chapter 33</a>
on there and I won't repeat it here for the sake of brevity.</p>
<p>What follows are the additional steps I had to take to get it to work.</p>
<p>I ran into a javax.enterprise.inject.CreationException, the relevant part of the
stack trace being:</p>
```
    Caused by: java.lang.IllegalArgumentException: targetClass parameter may not be null
        at org.jboss.solder.properties.query.PropertyQuery.(PropertyQuery.java:54) [solder-impl-3.1.0.Final.jar:3.1.0.Final]
        at org.jboss.solder.properties.query.PropertyQueries.createQuery(PropertyQueries.java:39) [solder-impl-3.1.0.Final.jar:3.1.0.Final]
        at org.jboss.seam.security.management.picketlink.JpaIdentityStore.findNamedProperty(JpaIdentityStore.java:441) [seam-security-3.1.0.Final.jar:3.1.0.Final]
        at org.jboss.seam.security.management.picketlink.JpaIdentityStore.configureRoleTypeName(JpaIdentityStore.java:877) [seam-security-3.1.0.Final.jar:3.1.0.Final]
        at org.jboss.seam.security.management.picketlink.JpaIdentityStore.bootstrap(JpaIdentityStore.java:328) [seam-security-3.1.0.Final.jar:3.1.0.Final]
        at org.picketlink.idm.impl.configuration.IdentityConfigurationImpl.createRealmMap(IdentityConfigurationImpl.java:192) [picketlink-idm-core-1.5.0.Alpha02.jar:1.5.0.Alpha02]
        at org.picketlink.idm.impl.configuration.IdentityConfigurationImpl.buildIdentitySessionFactory(IdentityConfigurationImpl.java:147) [picketlink-idm-core-1.5.0.Alpha02.jar:1.5.0.Alpha02]
        ... 109 more
```
<p>To resolve this,  I had to add in the @IdentityEntity Annotation to the
IdentityObjectType class</p>
```java
    @Entity
    @IdentityEntity(EntityType.IDENTITY_ROLE_NAME)
    public class IdentityObjectType {
    ...
```
<p>The next exception was org.picketlink.idm.common.exception.IdentityException:
Error creating identity object. The relevant part of the strack trace being:</p>
```
    Caused by: java.lang.NullPointerException
        at org.jboss.seam.security.management.picketlink.JpaIdentityStore.lookupIdentityType(JpaIdentityStore.java:966) [seam-security-3.1.0.Final.jar:3.1.0.Final]
        at org.jboss.seam.security.management.picketlink.JpaIdentityStore.createIdentityObject(JpaIdentityStore.java:999) [seam-security-3.1.0.Final.jar:3.1.0.Final]
        ... 87 more
```
<p>It turned out that the entitymanager was not being picked up and it was null.
This part was probably in the documentation earlier with regards to configuring
seam but I had skipped directly to the security section so missed it. We need to
define the persistence unit with the beans.xml. I have included my full file
below.</p>
```xml
    <?xml version="1.0"?>
    <beans xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:em="urn:java:javax.persistence"
        xmlns:s="urn:java:ee"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://jboss.org/schema/cdi/beans_1_0.xsd">

        <interceptors>
            <class>org.jboss.seam.security.SecurityInterceptor</class>
        </interceptors>

        <em:EntityManager>
            <s:Produces />
            <em:PersistenceContext unitName="invision-users" />
        </em:EntityManager>
    </beans>
```
<p>This brought us further forward still. The next exception was:</p>
```
    javax.persistence.NoResultException: No entity found for query
        at org.hibernate.ejb.QueryImpl.getSingleResult(QueryImpl.java:286) [hibernate-entitymanager-4.0.1.Final.jar:4.0.1.Final]
        at org.hibernate.ejb.criteria.CriteriaQueryCompiler$3.getSingleResult(CriteriaQueryCompiler.java:264) [hibernate-entitymanager-4.0.1.Final.jar:4.0.1.Final]
        at org.jboss.seam.security.management.picketlink.JpaIdentityStore.lookupCredentialTypeEntity(JpaIdentityStore.java:1112) [seam-security-3.1.0.Final.jar:3.1.0.Final]
        at org.jboss.seam.security.management.picketlink.JpaIdentityStore.updateCredential(JpaIdentityStore.java:1633) [seam-security-3.1.0.Final.jar:3.1.0.Final]
        at org.picketlink.idm.impl.repository.WrapperIdentityStoreRepository.updateCredential(WrapperIdentityStoreRepository.java:310) [picketlink-idm-core-1.5.0.Alpha02.jar:1.5.0.Alpha02]
        at org.picketlink.idm.impl.api.session.managers.AttributesManagerImpl.updatePassword(AttributesManagerImpl.java:563) [picketlink-idm-core-1.5.0.Alpha02.jar:1.5.0.Alpha02]
```
<p>This was related to missing data in the database. It needed a credential type. I
created one for password.</p>
```sql
    INSERT INTO CredentialType(id, name) VALUES (1, 'password');
```
<p>This brought us forward on to the next exception:
org.picketlink.idm.common.exception.IdentityException: Exception creating
relationship</p>
<p>with the relevant part of</p>
```
    Caused by: javax.persistence.NoResultException: No entity found for query
        at org.hibernate.ejb.QueryImpl.getSingleResult(QueryImpl.java:286) [hibernate-entitymanager-4.0.1.Final.jar:4.0.1.Final]
        at org.hibernate.ejb.criteria.CriteriaQueryCompiler$3.getSingleResult(CriteriaQueryCompiler.java:264) [hibernate-entitymanager-4.0.1.Final.jar:4.0.1.Final]
        at org.jboss.seam.security.management.picketlink.JpaIdentityStore.lookupRelationshipType(JpaIdentityStore.java:1127) [seam-security-3.1.0.Final.jar:3.1.0.Final]
        at org.jboss.seam.security.management.picketlink.JpaIdentityStore.createRelationship(JpaIdentityStore.java:1066) [seam-security-3.1.0.Final.jar:3.1.0.Final]
        ... 86 more
```
<p>This was solved by adding in a relationship type</p>
```sql
    INSERT INTO RelationshipType(id, name) VALUES (1, 'JBOSS_IDENTITY_MEMBERSHIP');
```
<p>Both the sql statements were put into import.sql and hibernate is configured to
create tables. My test case is as follows. It was taken
from <a href="https://github.com/seam/seam-example-confbuzz/blob/develop/src/test/java/seam/example/confbuzz/test/integration/LoginIntegrationTest.java">https://github.com/seam/seam-example-confbuzz/blob/develop/src/test/java/seam/example/confbuzz/test/integration/LoginIntegrationTest.java</a> and
modified.</p>
```java
    @RunWith(Arquillian.class)
    public class LoginIntegrationTest {

        @Inject
        private IdentitySession identitySession;

        @Inject
        private Identity identity;

        @Inject
        @DefaultTransaction
        SeamTransaction tx;

        @Deployment(name = "authentication")
        public static Archive createLoginDeployment() {
            // This is the simplest way to test the full archive as you will be
            // deploying it
            final MavenDependencyResolver resolver =
                    DependencyResolvers.use(MavenDependencyResolver.class)
                        .loadMetadataFromPom("pom.xml")
                        .goOffline();

            Archive archive = ShrinkWrap
                    .create(WebArchive.class)
                    .addPackages(true, "uk.co.kraya.test-seam.auth")
                    .addAsResource("META-INF/test-persistence.xml", "META-INF/persistence.xml")
                    .addAsResource("META-INF/beans.xml", "META-INF/beans.xml")
                    .addAsResource("test-import.sql", "import.sql")
                    .addAsLibraries(resolver.artifact("org.jboss.seam.security:seam-security").resolveAsFiles());

            System.out.println(archive.toString(true));

            return archive;

        }

        @Before
        public void setupTestUser() throws IdentityException, SystemException,
                NotSupportedException, RollbackException,
                HeuristicRollbackException, HeuristicMixedException {

            if (!tx.isActive())
                tx.begin();

            final PersistenceManager pm = identitySession.getPersistenceManager();
            final AttributesManager am = identitySession.getAttributesManager();
            final RelationshipManager rm = identitySession.getRelationshipManager();

            // Setup the group we want our user to belong to
            final Group memberGroup = pm.createGroup("member2", "USER2");
            final User user = pm.createUser("test");

            am.updatePassword(user, "password");

            rm.associateUser(memberGroup, user);

            tx.commit();
        }

        @Test
        public void assertUserCanAuthenticate(Credentials credentials) {
            credentials.setUsername("test");
            credentials.setCredential(new PasswordCredential("password"));
            assertEquals(identity.login(), Identity.RESPONSE_LOGIN_SUCCESS);
        }
```
<p>Do comment and let me know if it helped :-D</p>]]></content:encoded></item><item><title>Using CXF Interceptors to do some magic around your web service calls [1105]</title><link>https://icle.es/2011/11/06/using-cxf-interceptors-to-do-some-magic-around-your-web-service-calls-1105/</link><pubDate>Sun, 06 Nov 2011 12:24:28 +0000</pubDate><guid>https://icle.es/2011/11/06/using-cxf-interceptors-to-do-some-magic-around-your-web-service-calls-1105/</guid><description>&lt;p>We use JBossWS CXF for a heavily utilised enterprise system. It links into
spring to pick up and execute beans. We have a bunch of exceptions that could
get thrown.&lt;/p>
&lt;p>To simplify it, the code was originally written to create an anonymous class a
la Runnable which is wrapped around a try catch block. The exceptions that are
thrown are then converted to a soap fault and passed back.&lt;/p>
```java
private SOAPFaultException convertToSoapException(ApplicationException e)
{
 try {
 if(null == soapFactory) {
 soapFactory = SOAPFactory.newInstance();
 }
 SOAPFault sf = soapFactory.createFault();
 sf.setFaultString( e.getMessage() );
 sf.setFaultCode( Integer.toString(e.getErrorCode()) );
 return new SOAPFaultException( sf );
 } catch(SOAPException soapException) {
 throw new RuntimeException( soapException );
 }
}
```
&lt;p>Nothing inherently wrong with this. However, there are a couple of issues with
this in that each soap method is set to throw an &lt;em>ApplicationException&lt;/em> and
there is not further documentation of which of the subclasses are actually
relevant to that method.&lt;/p></description><content:encoded><![CDATA[<p>We use JBossWS CXF for a heavily utilised enterprise system. It links into
spring to pick up and execute beans. We have a bunch of exceptions that could
get thrown.</p>
<p>To simplify it, the code was originally written to create an anonymous class a
la Runnable which is wrapped around a try catch block. The exceptions that are
thrown are then converted to a soap fault and passed back.</p>
```java
private SOAPFaultException convertToSoapException(ApplicationException e)
{
    try {
        if(null == soapFactory) {
            soapFactory = SOAPFactory.newInstance();
        }
        SOAPFault sf = soapFactory.createFault();
        sf.setFaultString( e.getMessage() );
        sf.setFaultCode( Integer.toString(e.getErrorCode()) );
        return new SOAPFaultException( sf );
    } catch(SOAPException soapException) {
        throw new RuntimeException( soapException );
    }
}
```
<p>Nothing inherently wrong with this. However, there are a couple of issues with
this in that each soap method is set to throw an <em>ApplicationException</em> and
there is not further documentation of which of the subclasses are actually
relevant to that method.</p>
<p>In a runtime environment, this is not hugely relevant. However, when generating
documentation from the WSDL&rsquo;s, it is.</p>
<p>To resolve this, we changed each method to throw their relevant exception, and
wrote an interceptor to pick up the exception and convert it&hellip;</p>
<p>The first step was to write an interceptor which is surprisingly simple
and straightforward.</p>
```java
public class ExampleSoapFaultInterceptor extends AbstractSoapInterceptor {

    Logger log = Logger.getLogger(getClass());

    public QuarkSoapFaultInterceptor() {
        super(Phase.MARSHAL);
    }

    @Override
    public void handleMessage(SoapMessage message) throws Fault {
        Fault f = (Fault) message.getContent(Exception.class);

        Throwable cause = f.getCause();
        if (cause instanceof ApplicationException) {
            log.info("Exception Thrown", cause);
            QuarkException e = (QuarkException) cause;
            f.setFaultCode(new QName("", String.valueOf(e.getErrorCode())));

        } else {
            log.warn("Unexpected Exception thrown ", cause);
        }

    }
}
```
<p>The class doesn&rsquo;t need to extend the AbstractSoapInterceptor but you would then
have to manually implement a number of mechanisms that the abstract class
provides.</p>
<p>The constructor simply defines where this interceptor should be inserted into as
part of the chain. There is a whole bunch of different places where it can be
inserted based on this. Information can be
<a href="http://cxf.apache.org/docs/interceptors.html" title="Apache CXF Interceptors">found in their documentation.</a></p>
<p>To insert this interceptor into a web service, the service needs to be annotated
as follows:</p>
```java
@WebService(endpointInterface = "uk.co.kraya.example.WebService")
@OutFaultInterceptors(interceptors= {"uk.co.kraya.example.interceptors.ExampleSoapFaultInterceptor"})
public class ExampleWebService implements ExampleAPI {
```
<p>Each exception thrown from the web service will now be intercepted. You can then
include any further further information in the soap fault.</p>
<p>In this particular case, the only thing that gets done is to update the fault
code with the error code set against the exception. Any additional information
can be set against the soap fault at this point. You can also log as we are
doing.</p>
]]></content:encoded></item><item><title>JBossWS CXF - POJO vs Stateless [1104]</title><link>https://icle.es/2011/11/05/jbossws-cxf-pojo-vs-stateless/</link><pubDate>Sat, 05 Nov 2011 15:32:32 +0000</pubDate><guid>https://icle.es/2011/11/05/jbossws-cxf-pojo-vs-stateless/</guid><description>&lt;p>Cleaning up a bunch of code to reduce object instantiations got me thinking
about the webservice layer. We are using POJO based webservices but it got to me
wondering whether useless Stateless web service beans would improve memory
usage. More accurately, whether it would improve garbage collection performance.&lt;/p>
&lt;p>To test this, the plan was to build two versions of the same web service and
load test it to see the memory and cpu utilisation to compare cost /
performance.&lt;/p>
&lt;p>In the process, I also discovered other differences.&lt;/p></description><content:encoded><![CDATA[<p>Cleaning up a bunch of code to reduce object instantiations got me thinking
about the webservice layer. We are using POJO based webservices but it got to me
wondering whether useless Stateless web service beans would improve memory
usage. More accurately, whether it would improve garbage collection performance.</p>
<p>To test this, the plan was to build two versions of the same web service and
load test it to see the memory and cpu utilisation to compare cost /
performance.</p>
<p>In the process, I also discovered other differences.</p>
<p>Both the web services were built against this interface</p>
```java
@WebService
public interface WSTest {

    @WebMethod
    public String greetClient(String name);

}
```
<p>That is of course a simple enough interface.</p>
<p>The EJB version of this is as follows:</p>
```java
@WebService(endpointInterface = "uk.co.kraya.wstest.WSTest")
@Stateless
@Remote(WSTest.class)
public class EJBWebTest implements WSTest {

    public String greetClient(String name) {
        return "EJB Says Hello to " + name;
    }

}
```
<p>Simple and straightforward enough and the POJO version is not that different</p>
```java
@WebService
public class PojoWebTest implements WSTest  {

    @WebMethod
    public String greetClient(String name) {
        return "Pojo Says Hello to " + name;
    }

}
```
<p>I also used the following web.xml. This may not be a necessary step any more.</p>
```xml
<?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>

        <display-name>Archetype Created Web Application</display-name>
        <servlet>
                <servlet-name>GreetingWebService</servlet-name>
                <servlet-class>uk.co.kraya.wstest.pojo.PojoWebTest</servlet-class>
        </servlet>
       <servlet-mapping>
                <servlet-name>GreetingWebService</servlet-name>
                <url-pattern>/*</url-pattern>
        </servlet-mapping>
</web-app>
```
<p>Now that was complete, there was the deployment to consider. I had assumed that
I could just do one build, package it as an war and just deploy it but as it
turns out, that didn&rsquo;t work. This only deployed the Pojo web service. To deploy
the EJB web service, I had to package it as an EJB (maven) and deploy a jar
file.</p>
<p>This meant that I ended up with two deployments, wstestpojo.war and
wstestejb.jar.</p>
<p>Once deployed, I used SoapUI to load test both the web services and the results
were interesting.</p>
<p>In the grand scheme of things, the difference was pretty minimal between the
two. However, the Stateless EJB web service used a little extra (3% - 5%) CPU
presumably from the pooling of the beans and accessing them.</p>
<p>I used JBoss 5.1 and ran into an issue with log pollution</p>
<p>EJBTHREE-1337: do not get WebServiceContext property from stateless bean
context, it should already have been injected</p>
<p>This was printed every time an EJB based web service was called.</p>
<p>I
<a href="http://idevone.wordpress.com/2009/09/14/howto-suppress-ejbthree-1337-warning/" title="HOWTO: Suppress EJBTHREE-1337 warning">found more information about the EJBTHREE-1337 issue and a workaround for it</a>
The workaround simply involves updating log4j to not log it which is good enough
for me&hellip; :-)</p>
<p>As a final note, I am unsure as to how this would scale with complex web
services that have multiple instantiated objects as part of it.  I have a sneaky
suspicion that web services with expensive object instantiations would perform
better if using Stateless EJB Beans as would web services that are memory
hungry. However, this has not been tested.</p>]]></content:encoded></item><item><title>Register / Attach Service to JMX</title><link>https://icle.es/2011/06/21/register-attach-service-to-jmx/</link><pubDate>Tue, 21 Jun 2011 14:40:45 +0000</pubDate><guid>https://icle.es/2011/06/21/register-attach-service-to-jmx/</guid><description>&lt;p>Registering a Bean within JMX (at least in JBoss) is very straightforward. It
requires an interface with attributes (getters and setters) and operations.&lt;/p>
```java
MBeanServer server = org.jboss.mx.util.MBeanServerLocator.locateJBoss();
ObjectName objectName = new ObjectName("jboss.cache:service=TcpCacheServer");
server.registerMBean(objectToAttach, objectName);
```
&lt;p>objectToAttach is an object with a JMX'able interface.&lt;/p></description><content:encoded>&lt;p>Registering a Bean within JMX (at least in JBoss) is very straightforward. It
requires an interface with attributes (getters and setters) and operations.&lt;/p>
```java
MBeanServer server = org.jboss.mx.util.MBeanServerLocator.locateJBoss();
ObjectName objectName = new ObjectName("jboss.cache:service=TcpCacheServer");
server.registerMBean(objectToAttach, objectName);
```
&lt;p>objectToAttach is an object with a JMX'able interface.&lt;/p>
</content:encoded></item><item><title>Java Object Size In Memory</title><link>https://icle.es/2011/04/25/java-object-size-in-memory/</link><pubDate>Mon, 25 Apr 2011 15:58:00 +0000</pubDate><guid>https://icle.es/2011/04/25/java-object-size-in-memory/</guid><description>&lt;p>Anyone who has worked with java in a high end application will be well aware of
the double edged sword that is java garbage collection. When it works - it is
awesome but when it doesn&amp;rsquo;t - it is an absolute nightmare. We work on a
ticketing system where it is imperative that the system is as near real-time as
possible. The biggest issue that we have found is the running of memory in the
JVM which causes a stop the world garbage collection. This then results in
cluster failures since an individual node is inaccessible for long enough that
it is kicked out of the cluster.&lt;/p>
&lt;p>There are various ways to combat this issue and the first instinct would be
suggest that there is a memory leak. After eliminating this as a possibility,
the next challenge was to identify where the memory was being taken up. This
took some time and effort and the hibernate second level cache was identified.
We were storing far too much in the second level cache.&lt;/p>
&lt;p>This is another double edged sword. The hibernate second level cache is
absolutely imperative to a high performance system. It does however, come with a
price. The cache needs to be managed carefully to ensure that balance between
performance and memory requirements.&lt;/p></description><content:encoded><![CDATA[<p>Anyone who has worked with java in a high end application will be well aware of
the double edged sword that is java garbage collection. When it works - it is
awesome but when it doesn&rsquo;t - it is an absolute nightmare. We work on a
ticketing system where it is imperative that the system is as near real-time as
possible. The biggest issue that we have found is the running of memory in the
JVM which causes a stop the world garbage collection. This then results in
cluster failures since an individual node is inaccessible for long enough that
it is kicked out of the cluster.</p>
<p>There are various ways to combat this issue and the first instinct would be
suggest that there is a memory leak. After eliminating this as a possibility,
the next challenge was to identify where the memory was being taken up. This
took some time and effort and the hibernate second level cache was identified.
We were storing far too much in the second level cache.</p>
<p>This is another double edged sword. The hibernate second level cache is
absolutely imperative to a high performance system. It does however, come with a
price. The cache needs to be managed carefully to ensure that balance between
performance and memory requirements.</p>
<p>To this end, it was important to be able to identify what was taking up all the
memory in the cache. Each object might only take a couple of hundred bytes, but
with our second level cache set to store hundreds of thousands of items, this
quickly takes up hundreds of megabytes. With the metadata of the cache, this
could easily hike it up near a gigabyte of memory usage. This gets substantially
worse with cache evictions and the adding of new items into the cache.</p>
<p>The correct way to resolve this is to identify specific object types that
&ldquo;overload&rdquo; the cache. i.e. items that have an large number of instances stored
in the cache. Identifying classes that store a large number of items is easy
enough - we just traverse the cache and count up the number of items. However,
there might be a class that stores a smaller number of items but take a sizeable
amount of memory. For this reason, it is important to understand the object
sizes in memory as well.</p>
<p>If you have ever tried to find a way to identify object sizes, you will know
that this is no easy task. You can calculate to some degree of accuracy the size
of an object based on the data it stores but this is a manual process.</p>
<p>The only real way to get this information is to use a java agent and use that to
calculate a more accurate memory usage. For this purpose, we used the
<a href="http://www.javamex.com/classmexer/" title="ClassMexer Java Profiling Agent">classmexer agent</a>
which requires a simple installation step of adding the following parameter to
java <code>-javaagent:classmexer.jar</code>. You can then figure out the memory utilisation
of an object by calling</p>
```java
MemoryUtil.deepMemoryUsageOf(objectInstance)
```
<p>You can also pass in a collection of objects:</p>
```java
MemoryUtil.deepMemoryUsageOfAll(objectInstanceCollection)
```
<p>This was the simple part.</p>
<p>Traversing the node structure of jboss cache and collating a collection
statistics with regards to the number of each type of object and its memory
utilisation was a little more interesting.</p>
<p>I will cover this separately</p>]]></content:encoded></item><item><title>rich:calendar and the onchange event</title><link>https://icle.es/2010/06/01/richcalendar-and-the-onchange-event/</link><pubDate>Tue, 01 Jun 2010 20:20:20 +0000</pubDate><guid>https://icle.es/2010/06/01/richcalendar-and-the-onchange-event/</guid><description>&lt;p>I wanted to trigger some validation based re-renders with the &lt;code>rich:calendar&lt;/code>
component. I was scratching my head for a while trying to figure out why it
wasn&amp;rsquo;t working.&lt;/p>
&lt;p>Then it happened, its supposed to be onchange&lt;strong>d&lt;/strong>. This particular component
requires the extra d at the end&amp;hellip; and it worked and everyone lived happily ever
after&amp;hellip;&lt;/p></description><content:encoded><![CDATA[<p>I wanted to trigger some validation based re-renders with the <code>rich:calendar</code>
component. I was scratching my head for a while trying to figure out why it
wasn&rsquo;t working.</p>
<p>Then it happened, its supposed to be onchange<strong>d</strong>. This particular component
requires the extra d at the end&hellip; and it worked and everyone lived happily ever
after&hellip;</p>
]]></content:encoded></item><item><title>Maven2, EJB3 and JBoss</title><link>https://icle.es/2008/12/28/maven2-ejb3-and-jboss/</link><pubDate>Sun, 28 Dec 2008 18:53:50 +0000</pubDate><guid>https://icle.es/2008/12/28/maven2-ejb3-and-jboss/</guid><description>&lt;p>I started work on a project called InVision about a year ago but have probably
spent about a week or two worth of effort on it in total&amp;hellip; :-(&lt;/p>
&lt;p>The Project aim was to bring together the easy time logging capabilities of
&lt;a href="http://processdash.sourceforge.net/" title="The Software Process Dashboard Initiative">Process Dashboard&lt;/a>
along with the project management capabilities of Microsoft Project (including
the Server Component). It is also to be integrated into our request tracking
System - &lt;a href="http://bestpractical.com/rt/" title="Request Tracker">Request Tracker&lt;/a>.
Eventually, it is also to integrate with our accounting system and turn into an
ERP (Enterprise Resource Planning) system and MIS (Management Information
System). There are plans to integrate with our Wiki and our Document Management
System too.&lt;/p>
&lt;p>But these are all lofty goals.  One of our recent projects introduced me to the
&lt;a href="http://www.springframework.net/" title="Spring.NET Application Framework">Spring Framework&lt;/a>.
While I am still not a fan of Spring, the scale of the project and the way of
approaching it gave me some ideas and additional tools to work with. I wanted to
bring these into the InVision Project.&lt;/p>
&lt;p>The key one here was Maven 2. InVision already used EJB3 and JBoss (4.2 as it
happened). There was one additional issue for me to resolve and that was out of
container testing. Something that is very easy to do with Spring but a little
more troublesome with EJB3 since it doesn&amp;rsquo;t have an out of container
framework&amp;hellip;&lt;/p></description><content:encoded><![CDATA[<p>I started work on a project called InVision about a year ago but have probably
spent about a week or two worth of effort on it in total&hellip; :-(</p>
<p>The Project aim was to bring together the easy time logging capabilities of
<a href="http://processdash.sourceforge.net/" title="The Software Process Dashboard Initiative">Process Dashboard</a>
along with the project management capabilities of Microsoft Project (including
the Server Component). It is also to be integrated into our request tracking
System - <a href="http://bestpractical.com/rt/" title="Request Tracker">Request Tracker</a>.
Eventually, it is also to integrate with our accounting system and turn into an
ERP (Enterprise Resource Planning) system and MIS (Management Information
System). There are plans to integrate with our Wiki and our Document Management
System too.</p>
<p>But these are all lofty goals.  One of our recent projects introduced me to the
<a href="http://www.springframework.net/" title="Spring.NET Application Framework">Spring Framework</a>.
While I am still not a fan of Spring, the scale of the project and the way of
approaching it gave me some ideas and additional tools to work with. I wanted to
bring these into the InVision Project.</p>
<p>The key one here was Maven 2. InVision already used EJB3 and JBoss (4.2 as it
happened). There was one additional issue for me to resolve and that was out of
container testing. Something that is very easy to do with Spring but a little
more troublesome with EJB3 since it doesn&rsquo;t have an out of container
framework&hellip;</p>
<p>I have grown to be a big fan of Maven 2 and using Maven 2 to configure an EJB
project is not as easy or straightforward as I would have liked: I wanted to
separate the whole project into four parts</p>
<ul>
<li>Domain Model (or just the entity beans); Also referred to as a Hibernate
Archive (HAR)</li>
<li>Stateful/Stateless Beans (Just the Beans, since I don&rsquo;t consider entities
beans in EJB3)</li>
<li>Application Client (J2SE Application)</li>
<li>Web App (Using SEAM)</li>
<li>I would also need an EAR project to deploy the DomainModel, Beans &amp; WebApp as
one pacakge into JBoss.</li>
</ul>
<p>I have not got as far as the SEAM project yet but the other ones were
straightforward enough to set up with Maven 2.</p>
<p>Both the Domain Model and the Beans project had to be set up as ejb projects and
use the maven-ejb-plugin</p>
```xml
 <build>
     <plugins>
         <plugin>
             <groupId>org.apache.maven.plugins</groupId>
             <artifactId>maven-ejb-plugin</artifactId>
             <configuration>
                 <ejbVersion>3.0</ejbVersion>
             </configuration>
         </plugin>
     </plugins>
 </build>
```
<p>I set up the persistence context within the Domain Model</p>
```xml
<persistence-unit name="em">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <jta-data-source>java:/datasource</jta-data-source>
</persistence-unit>
```
<p>I could then reference the context from the Beans project by injecting it with</p>
```java
@PersistenceContext(unitName="em")
```
<p>Easy enough!</p>
<p>Now configuring the EAR project: This was configured as an ear package which
depended on the other two projects with the following configuration</p>
```
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-ear-plugin</artifactId>
<configuration>
<version>5</version>
 <modules>
 <ejbModule>
 <groupId>uk.co.kraya.invision</groupId>
 <artifactId>beans</artifactId>
 </ejbModule>
 <ejbModule>
 <groupId>uk.co.kraya.invision</groupId>
 <artifactId>DomainModel</artifactId>
 </ejbModule>
 </modules>
 <jboss>
 <version>4.2</version>
 <data-sources>
 <data-source>invision-ds.xml</data-source>
 </data-sources>
 </jboss>
 </configuration>
 </plugin>
 <plugin>
 <groupId>org.codehaus.mojo</groupId>
 <artifactId>jboss-maven-plugin</artifactId>
 <configuration>
 <jbossHome><jboss-home-path></jbossHome>
 <hostName><hostname></hostName>
 <port>8080</port>
 </configuration>
 </plugin>
 </plugins>
 </build>
```
<p>With this configured, from the EAR project, I could do mvn ear:deploy to deploy
to JBoss.</p>
<p>Additionally, within eclipse, I created a new run-type that ran ear:undeploy
package ear:deploy to re-deploy the package to JBoss. Works a treat</p>
<p>There are still a few kinks to be ironed out.</p>
<p>I still need to install (mvn install) the two projects before the EAR will pick
it up to deploy. I need to get the ear re-deploy to re-build the other projects.
Something to look at another day.</p>
<p>I had manually deployed the DataSource file to JBoss. It might be possible to do
this via Maven.</p>
<p>I also very much liked the Eclipse automatic deploy feature. It is possible to
use the eclipse plugin on maven to get Eclipse to identify this as a JBoss
deployable project but I ran into some problems and gave up. Ideally, Eclipse
would auto-deploy the project.</p>
<p>However, the above is less relevant once Out-Of-Container testing is in place.
Now, this does work, but I will leave that to another day&hellip;</p>]]></content:encoded></item><item><title>Hibernate Domain Model Testing</title><link>https://icle.es/2008/12/23/hibernate-domain-model-testing/</link><pubDate>Tue, 23 Dec 2008 22:14:42 +0000</pubDate><guid>https://icle.es/2008/12/23/hibernate-domain-model-testing/</guid><description>&lt;p>One of my pet peeves with Hibernate has always been how difficult it was to test
it. I want to test the persistence of data, loading the data back and any
specific funtionality with the domain model.&lt;/p>
&lt;p>Simple? NO! The main problem was the management of the data set. I had set up,
in the past fairly interesting classes to test the functionality using
reflection, and injecting the data from the classes themselves through the data
provider mechanism of &lt;a href="http://testng.org/d" title="TestNG">TestNG&lt;/a>. However, this was
error prone and clunky at best. It also made dependency management of data quite
cumbersome.&lt;/p>
&lt;p>With a view to resolving this, I also looked at
&lt;a href="http://dbunit.sourceforge.net/" title="DbUnit">DbUnit&lt;/a>,
&lt;a href="http://unitils.org/" title="Unitils">unitils&lt;/a> and
&lt;a href="http://ejb3unit.sourceforge.net/" title="Ejb3Unit">Ejb3Unit&lt;/a>. They all did some
things that I liked but lacked some functionality that was important.&lt;/p></description><content:encoded><![CDATA[<p>One of my pet peeves with Hibernate has always been how difficult it was to test
it. I want to test the persistence of data, loading the data back and any
specific funtionality with the domain model.</p>
<p>Simple? NO! The main problem was the management of the data set. I had set up,
in the past fairly interesting classes to test the functionality using
reflection, and injecting the data from the classes themselves through the data
provider mechanism of <a href="http://testng.org/d" title="TestNG">TestNG</a>. However, this was
error prone and clunky at best. It also made dependency management of data quite
cumbersome.</p>
<p>With a view to resolving this, I also looked at
<a href="http://dbunit.sourceforge.net/" title="DbUnit">DbUnit</a>,
<a href="http://unitils.org/" title="Unitils">unitils</a> and
<a href="http://ejb3unit.sourceforge.net/" title="Ejb3Unit">Ejb3Unit</a>. They all did some
things that I liked but lacked some functionality that was important.</p>
<p>This led me to write a simple testing infrastructure. The goal was
straightforward.</p>
<ul>
<li>I need to be able to define data in a CSV (actually it was seperated by the
pipe character |, so PSV) based on entities.</li>
<li>The framework should automatically persist the data (and fail on errors)</li>
<li>It should test that it can load all that data back</li>
<li>It should run as many automated tests on the DOM as possible.</li>
</ul>
<p>The framework uses the CSV files to read the data for each of the classes (using
the excellent <a href="http://supercsv.sourceforge.net/" title="SuperCsv">SuperCsv</a> library).
It needs an Id field for internal reference. As long as the id&rsquo;s match within
the CSV files for the relationships, it will be persisted correctly into the
database even when the persisted id&rsquo;s are different.</p>
<p>For example, I could have a Contact.csv with 5 records (ids 1 through 5) and a
Company.csv with 3 records (ids 1 through 3).</p>
<p>The Contact.csv records can map to the id specified in the Company.csv file and
when the records get persisted, they will be associated correctly, even if the
id&rsquo;s in the database end up being different.</p>
<p>The framework also looks for the CSV file which has the same name as the class
within the location defined within the configuration file. This means that as
long as the filename matches the class name, the data loading is automatic.</p>
<p>For simple classes, the Test case is as simple as:</p>
```java
public class CompanyTest extends DOMTest<Company> {

public CompanyTest() { super(Company.class); } }
```
<p>The system (with the help of testNG) is also easily flexible to define object
model dependencies. Just override the persist method (which just calls the
super.persist) and define the groups to be persist and <code>&lt;object&gt;.persist</code></p>
<p>in this particular case, it would be</p>
```java
@override
@Test(groups={"persist", "Company.persist"}
public void persist() {
    super.persist();
}
```
<p>For all dependent classes, I then depend on the Company.persist group (For the
ContactTest class for example, since it needs to link to the Company object)</p>
<p>You can specify OneToOne and ManyToOne relationships with just the CSV files -
just defining the field name and the id of the object to pull in.</p>
<p>ManyToMany is more complex and requires an interim object to be created within
the test section. If the Contact to Company relationship above was ManyToMany,
we would create a ContactCompany class with just the two fields - Contact &amp;
Company, then create a csv file with three fields, id, Contact, &amp; Company. The
framework currently always needs an id field.</p>
<p>You would then need to write a method within the ContactTest or CompanyTest(I
use the owning side) to read the CSV file in and pump the data. This process is
a little bit complex just now.</p>
<p>With an appropriate amount of test data, you are able to write a test suite that
can consistently test your domain model. More importantly, you can configure it
to drop the database at the start of each run so that once the tests are
complete, you have a database structure and data than can be used for testing of
higher level components (EJB/Spring/UI/WebApp)</p>
<p>We currently use this framework to test the domain model as well as distribute a
data set for development and testing of the higher tier functionalities.</p>
<p>For the future, there are several additional features this framework needs:</p>
<ul>
<li>It currently needs the setters/getters &amp; constructors to be public. This needs
to be FIXED</li>
<li>Refactor the ManyToMany Relationship code to make it easier and simpler to
test and pump data</li>
<li>See if we can ensure that additional tests which data is done within a
transaction and rolled back so that the database is left in the &ldquo;CSV Imported&rdquo;
state on completion of tests</li>
<li>Easier Dependency management if possible</li>
</ul>
<p>This framework is still inside the walls of Kraya, but once the above issues are
resolved and it is in a releasable state, it will be published into the open
source community. If you are interested in getting a hold of it, email me and
I&rsquo;ll provide you with the latest version.</p>
<p>The easier and quicker it is to test, the more time we can spend on writing
code&hellip; :-) The higher the coverage of the tests, the more confident you can be
of your final product.</p>
<p>To more testing&hellip;</p>]]></content:encoded></item></channel></rss>