02 August 2011

Hibernate/JPA Identity Generators

Bambitroll @ 16:05
While googling for some answer regarding JPA identity generators and how they behave according to which DB you use, I found this very nice blog post!

Very informative!

31 May 2011

SOAPUI and dynamic XML values

Bambitroll @ 17:44
I am currently using SOAPUI to load test an application via web services.
In order to do that, I need to be able to change the value of some XML elements on the fly.
Here is how you can do that:
- Create a Test Suite
- Create a Test Case (which will contains Test Steps)
- Your first test step will be a SOAP request called TestReq1
- In the Test Case Editor, you can create a Setup Script

Here is the Groovy script I use to set the value of one element dynamically (in this case the element attribute called Version):
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
def holder = groovyUtils.getXmlHolder("TestReq1#Request")
holder.setNodeValue("//@Version","7.2")
holder.updateProperty()

At the moment the script is not so useful since it dynamically sets the element to the same value. But there are several strategies to use different values each time, from reading from a file or a DB to writing a little generator in Groovy.


Another thing which is useful with SOAPUI is to be able to create a mock-up response which is dynamically created according to the incoming data. Once you have created your mock-up service, here is how to fetch data from the request and paste it in the response. First the incoming XML and then the Groovy script changing the response (in this example both the request and the response have a Version attribute on an element and we simply return the value we get in):

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:abc="http://my.project.com/abc">
   <soapenv:Header/>
   <soapenv:Body>
      <abc:customerApp Version="${version}" />
   </soapenv:Body>
</soapenv:Envelope>

def holder = new com.eviware.soapui.support.XmlHolder(mockRequest.requestContent)
context.version = holder["//@Version"]

28 March 2011

Testing Databases with JUnit and Hibernate

Bambitroll @ 13:51
Here a 3 part blog post showing how to use JUnit and Hibernate (and Hypersonic) to test your database layer. Often using an ORM makes this superfluous but in some cases it can be an interesting to do.

Part 1
Part 2
Part 3

23 March 2011

Socket connection error when using remote JBoss AS

Bambitroll @ 10:05
I spent most if the afternoon on this problem yesterday and I thought I
could just share the solution since this might be a good tip for everyone...

I have Arquillian tests which used to run flawlessly and which stopped
working out of the blue! The problem was, according to the JUnit logs, a
socket connection error when using remote JBoss AS.

After a lot of searching and great help from Aslak Knutsen on
#jbosstesting, I found out that the problem was in /etc/hosts!


More info and the solution from JBoss community.

28 February 2011

Improving your laptop battery life

Bambitroll @ 08:14
-
According to this page, you should avoid charging your laptop if its battery is nearly full. Indeed, it destroys your battery capacity in the long run.

Running Ubuntu on a Thinkpad (mine is a T510), you can set up the thresholds for when to start and stop charging yourself.

Here is how:
# aptitude install tp-smapi-dkms
# modprobe tp_smapi
# echo 40 > /sys/devices/platform/smapi/BAT0/start_charge_thresh
# echo 70 > /sys/devices/platform/smapi/BAT0/stop_charge_thresh
# cat /sys/devices/platform/smapi/BAT0/*_charge_thresh

Then to have the settings loaded at each startup:
# apt-get install sysfsutils
And add the following in /etc/sysfs.conf
# For a LiIon battery in a Thinkpad
devices/platform/smapi/BAT0/start_charge_thresh = 50
devices/platform/smapi/BAT0/stop_charge_thresh =85

All the info is here.

Once you are done are reboot the machine, you will need to run the "modprobe tp_smapi" command to be able to access /sys/devices/platform/smapi
-

23 February 2011

Arquillian testing - JBoss 5.1.0 - EJB3

Bambitroll @ 11:17
I started using Arquillian to test my business logic code directly in my running JBoss 5.1 instance, and after some fighting I got it working pretty nicely!

So here is what I had to do:
1. Add a profile for running the Arquillian Integration tests in Maven

<profiles>
   <profile>
      <id>it</id>
      <activation>
        <activeByDefault>false</activeByDefault>
      </activation>
      <build>
        <defaultGoal>verify</defaultGoal>
        <plugins>
          <plugin>
            <artifactId>maven-failsafe-plugin</artifactId>
            <version>2.6</version>
            <executions>
              <execution>
                <goals>
                  <goal>integration-test</goal>
                </goals>
              </execution>
            </executions>
          </plugin>
        </plugins>
        <testResources>
            <testResource>
                <directory>src/test/resources</directory>
            </testResource>
        </testResources>
      </build>
      <dependencies>
        <dependency>
            <groupId>org.jboss.arquillian.container</groupId>
            <artifactId>arquillian-jbossas-remote-5.1</artifactId>
            <version>1.0.0.Alpha4</version>
            <scope>test</scope>
          </dependency>
        <dependency>
          <groupId>org.jboss.jbossas</groupId>
          <artifactId>jboss-as-client</artifactId>
          <version>5.1.0.GA</version>
          <type>pom</type>
        </dependency>
      </dependencies>
    </profile>  
</profiles>

2. Make sure you are using the correct version of the javassist library in your business logic project. It has to be version 3.10.0.GA. The one coming with JBoss AS 5.1.0 GA is older (3.9.0) and will not work properly!

3. Write your test classes and run them using "mvn -Pit"!

4. Here is an example of a simple class just calling a EJB3 SLSB (test-persistence.xml has to be in src/test/resources together with jndi.properties):
import javax.naming.Context;
import javax.naming.InitialContext;

import junit.framework.Assert;
import myclasses.ejb.actions.interfaces.AuthenticatorLocal;
import myclasses.ejb.valueobjects.RequestorInfo;

import org.jboss.arquillian.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ArchivePaths;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(Arquillian.class)
public class AuthenticatorBeanIT {
 @Deployment
 public static JavaArchive createDeployment() {
  return ShrinkWrap.create(JavaArchive.class, "testAuthenticatorBean.jar")
  .addClasses(AuthenticatorBean.class, AuthenticatorLocal.class, RequestorInfo.class)
  .addManifestResource("test-persistence.xml", ArchivePaths.create("persistence.xml"));
 }

 @Test
 public void isAuthenticatedTest() throws Exception {
  Context ctx = new InitialContext();
  AuthenticatorLocal auth;

  Object obj = ctx.lookup("AuthenticatorBean/local");

  auth = (AuthenticatorLocal) obj;
  RequestorInfo req = new RequestorInfo();

  // Trying with a valid user (according to import.sql!)
  req.setRequestorId("0123456789");
  req.setPassword("secret");
  Assert.assertTrue(auth.isAuthenticated(req));
  
  // Trying with a invalid user
  req.setRequestorId("0123456789");
  req.setPassword("incorrect");  
  Assert.assertFalse(auth.isAuthenticated(req));
 }
}


5. Here is an example of a class persisting something to the DB and cleaning up after itself (Note: you have to lookup the EntityManager and EntityTransaction yourself. They can not be injected since you are not in an EJB(:
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import junit.framework.Assert;
import myclasses.ejb.actions.interfaces.MyClassLocal;
import myclasses.ejb.valueobjects.Info;

import org.jboss.arquillian.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ArchivePaths;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(Arquillian.class)
public class BarCodeBoardingPassBeanIT {
 @Deployment
 public static JavaArchive createDeployment() {
  return ShrinkWrap.create(JavaArchive.class, "testBarCodeBoardingPassBean.jar")
  .addClasses(MyClassLocal.class)
  .addManifestResource("test-persistence.xml", ArchivePaths.create("persistence.xml"));
 }

 @Test
 public void persistBoardingPassInfoTest() throws Exception {
  Context ctx = new InitialContext();
  MyClassLocal mcl;

  Object obj = ctx.lookup("MyClasssBean/local");

  mcl = (MyClassLocal) obj;
  
  Info info = new Info("XXX");
  mcl.persistInfo(info);
  
  
  // Now checking that the data is properly persisted in the DB
  EntityManagerFactory emFactory = (EntityManagerFactory) ctx.lookup("java:/myTestEntityManagerFactory");
  EntityManager em = emFactory.createEntityManager();
  EntityTransaction tx = em.getTransaction();
  tx.begin();

  Query query = em.createQuery("From Info where text=:info");
  query.setParameter("info", "XXX");
  runQuery(query);
  
  // Cleaning up
  query = em.createQuery("delete from Info where text=:info");
  query.setParameter("info", "XXX");
  query.executeUpdate();
  
  tx.commit();
 }
 
 private void runQuery(Query query) {
  try {
   query.getSingleResult();
   Assert.assertTrue(true);
  } catch (Exception e) {
   Assert.assertTrue(false);
  }
 }
}

6. For the previous test class to work you need a persistence.xml which looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
    version="1.0">

     <persistence-unit name="myTestPU" transaction-type="RESOURCE_LOCAL" >
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <non-jta-data-source>java:/myAppDS</non-jta-data-source>
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
            <property name="hibernate.current_session_context_class" value="jta"/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.format_sql" value="true"/>
            <property name="hibernate.default_schema" value="public"/>
            <property name="hibernate.hbm2ddl.auto" value="validate" />
            <property name="jboss.entity.manager.factory.jndi.name" value="java:/myTestEntityManagerFactory"/>
            
        </properties>
    </persistence-unit>

</persistence>