Scanning classes for src/test/resources/META-INF/persistence.xml

Submitted by Jochus on Sun, 31/01/2010 - 19:28 | Posted in: Java
Posted in

So, as you all know, you can define a persistence unit as:

<persistence>
	<persistence-unit name="myPersistenceUnit">
		<provider>org.hibernate.ejb.HibernatePersistence</provider>
		<jta-data-source>myDataSource</jta-data-source>
		<properties>
			<property name="hibernate.hbm2ddl.auto" value="update" />
			<property name="hibernate.show_sql" value="true" />
			<property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.DefaultComponentSafeNamingStrategy"/>
		</properties>
	</persistence-unit>
</persistence>

So your persistence unit is depending on a JTA datasource which is configured in your application server.

Now, you want to run some tests from Eclipse/Netbeans/... without using the datasource of the application server. Then the persistence.xml could look like this:

<persistence>
	<persistence-unit name="myTestPersistenceUnit">
		<provider>org.hibernate.ejb.HibernatePersistence</provider>
 
		<properties>
			<property name="hibernate.connection.url"
				value="jdbc:oracle:thin:@myServer:myPort:myDataBase" />
			<property name="hibernate.connection.username" value="myUserName" />
			<property name="hibernate.connection.password" value="myPassword" />
			<property name="hibernate.connection.driver_class" value="oracle.jdbc.driver.OracleDriver" />
			<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" />
			<property name="hibernate.hbm2ddl.auto" value="create" />
			<property name="hibernate.cache.use_query_cache" value="false" />
			<property name="hibernate.cache.use_second_level_cache"
				value="false" />
			<property name="hibernate.show_sql" value="true" />
			<property name="hibernate.format_sql" value="true" />
		</properties>
	</persistence-unit>
</persistence>

To use this persistence.xml, you could use the following abstract class (from which you will extend your unit testing)

public abstract class AbstractTransactionalDBUnitTest {
   private EntityManagerFactory emf;
   private EntityManager entityManager;
   private CachedDataSet cachedDataSet;
   private IDatabaseConnection con;
   private String persistenceUnitName = "myTestPersistenceUnit";
 
   /**
    * Creates a normal AbstractTransactionalDBUnitTest
    */
   public AbstractTransactionalDBUnitTest() {
      // DO NOTHING
   }
 
   /**
    * Creates an AbstractTransactionalDBUnitTest, but based on another persistence unit
    * @param aPersistenceUnitName the name of the persistence unit that will need to be used
    */
   public AbstractTransactionalDBUnitTest(String aPersistenceUnitName) {
      this.persistenceUnitName = aPersistenceUnitName;
   }
 
   /**
    * Initialize the database by creating an {@link EntityManagerFactory}
    */
   @BeforeClass
   public void initDB() {
	   try {
		   this.emf = Persistence.createEntityManagerFactory(this.persistenceUnitName);
	   } catch (PersistenceException pe) {
		   pe.printStackTrace();
	   }
   }
 
   /**
    * Gets an {@link EntityManager} from the {@link EntityManagerFactory}
    * 
    * @return an {@link EntityManager}
    */
   public EntityManager getEntityManager() {
      if (this.entityManager == null) {
         this.entityManager = this.emf.createEntityManager();
      }
      return this.entityManager;
   }
 
   /**
    * Prepare the database with test data before every method. Starts a transaction.
    * 
    * @throws IOException when there's a problem reading the XML file with test data
    * @throws DatabaseUnitException when there's a problem with the DBUnit (config, setup, ...)
    * @throws SQLException when there's a prolem with the SQL statements
    */
   @SuppressWarnings("deprecation")
   @BeforeMethod
   public void beforeMethod() throws IOException, DatabaseUnitException, SQLException {
      IDataSetProducer producer = new CustomFlatXmlProducer(new InputSource(this.getDataFileName()), false, true);
      this.cachedDataSet = new CachedDataSet(producer);
      Session session = (Session) this.getEntityManager().getDelegate();
      con = new DatabaseConnection(session.connection());
      con.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new OracleDataTypeFactory());
      con.getConfig().setFeature(DatabaseConfig.FEATURE_SKIP_ORACLE_RECYCLEBIN_TABLES, true);
      con.getConfig().setFeature(DatabaseConfig.FEATURE_QUALIFIED_TABLE_NAMES, true);
      this.getEntityManager().getTransaction().begin();
      DatabaseOperation.REFRESH.execute(con, this.cachedDataSet);
   }
 
   /**
    * Ends the transaction after every method
    */
   @AfterMethod
   public void afterMethod() {
      if (this.getEntityManager().getTransaction().isActive()) {
         this.getEntityManager().getTransaction().rollback();
      }
      try {
         con.close();
      } catch (SQLException e) {
         // absorbed
      }
   }
 
   /**
    * Closes the {@link EntityManagerFactory}
    * 
    * @throws DatabaseUnitException when there's a problem with the DatabaseUnitException
    * @throws HibernateException when there's a problem with Hibernate
    * @throws SQLException when there's a problem with SQL
    */
   @AfterClass
   public void closeDB() throws HibernateException, DatabaseUnitException, SQLException {
      this.emf.close();
   }
 
   /**
    * Gets the name of the file on which test data is located This method has to be overwritten for every DAO test class
    * 
    * @return the name of the file on which test data is located
    */
   public abstract String getDataFileName();
 
}

Now, the problem you will run into is that your classes will not be scanned. This is normal, as you're not having the functionality of the J2EE server. No scanning is no registration of your classes in the persistence unit.
To solve this, I implemented a scenario like this:

  • scan target folder on classes with the annotation Entity
  • manually attach those classes to the EntityManagerFactory (which holds the EntityManager)
  • open transaction
  • fill up DB with test data
  • run tests
  • close transaction

To scan the target folder, you can use the Scannotation framework. Now, you just have to add the scanned classes:

        AnnotationDB db = new AnnotationDB();
        db.setScanFieldAnnotations(false);
        db.setScanMethodAnnotations(false);
        db.setScanParameterAnnotations(false);
 
        File f = new File("target/classes/");
        URL url = new URL("file://" + f.getAbsolutePath() + "/");
        db.scanArchives(url);
 
        Map < String, Set < String >> annotationIndex = db.getAnnotationIndex();
        // get all entity annotated entity classes from the package we are
        // interested.
        Set < String > entities = annotationIndex.get(Entity.class.getName());
        CollectionUtils.filter(entities, new Predicate() {
            public boolean evaluate(final Object someObject) {
                String className = (String) someObject;
                return className.startsWith("be.jochusonline.cms.model");
            }
        });
 
        AnnotationConfiguration cfg = new AnnotationConfiguration();
        cfg.setProperty(Environment.DIALECT, DB_DIALECT);
 
        // Add all entity classes to the annotation config.
        for (String entityName : entities) {
            cfg.addAnnotatedClass(Class.forName(entityName));
        }

Sony Ericsson G502 firmware upgrade (part 2)

Submitted by Jochus on Sun, 31/01/2010 - 15:43 | Posted in:

In november vorig jaar heb ik een firmware upgrade uitgevoerd op mijn G502 toestel. Ondertussen zijn we 2 maand verder en kan ik zeggen dat alle problemen van de baan zijn. Het toestel valt nooit meer uit. Toch ondervind ik dat het toestel wel traag wordt als er héél veel berichten inzitten. Op tijd je inbox uitkuisen is en blijft de boodschap.

Wat me ook opvalt, en ik weet nu niet of het aan de firmware upgrade ligt, maar de batterij gaat niet zo lang meer als vroeger. Vroeger kon ik gerust 6, 7 dagen zonder batterij halen. Nu moet ik om de 3 à 4 dagen herladen. Het zou ook kunnen dat de batterij gewoon aan het verslijten is.

Voor de rest: firmware upgrade op G502 is een aanrader!

Above & Beyond: Trance Around The World

Submitted by Jochus on Fri, 29/01/2010 - 21:20 | Posted in:

Op Tomorrowland 2009 het einde van hun liveset gezien (dankzij Ruben, die zei dat ik zeker eens moest gaan luisteren!). Op die avond heb ik heb een fenomenale liveset gehoord. De beste progressive trance muziek en crowdsurfing DJ's:

... na enkele maanden ben ik geabonneerd op hun podcast. Iedere week brengen zij een prachtige, 2uur durende, set uit. De sets liggen op in de auto, thuis, op 't werk, ... echt ... overal :-). Ik durf zelfs zeggen ... en jawel, iedereen weet dat ik MEGA fan ben van Tiësto, dat ik ze beter vind dan Tiësto.

Een tijdje geleden brachten ze episode 300 uit, waar luisteraars hun BESTE track ooit mochten kiezen. Het resultaat kan je hier beluisteren: http://media.libsyn.com/media/tatwpodcast/TATW300_771.mp3. Het is voor mij de beste set die ik al ooit van hun gehoord heb. De podcast, Trance Around The World, is een aanrader voor echte trance liefhebbers: http://www.tatw.co.uk/podcast.xml

Have fun listening!

CompizConfig Settings Manager in Ubuntu

Submitted by Jochus on Thu, 28/01/2010 - 23:58 | Posted in: Linux
Posted in

Last week, I installed the CompizConfig Settings Manager :-)

<a href="mailto:jochen@baileys">jochen@baileys</a> $ sudo aptitude install compizconfig-settings-manager

It can give you some great effects :p. They don't bring any advantage, but they are just cool :-). I configured the ...

  • Desktop cube
    • Desktop: desktop cube & rotate cube
    • Make sure you have 4 workspaces! (right click on it > Preferences > Columns: 4 > Rows: 1)
  • Wobbly Windows

Watch some of the effects here:

Installing Eclipse & Maven 2 using Synaptic

Submitted by Jochus on Thu, 28/01/2010 - 21:00 | Posted in: Java
Posted in

Since the beginning of this Ubuntu installation, I installed Eclipse Galileo manually. I don't know why I didn't use Synaptic :p, but I just didn't.

I sometimes had the problem I couldn't click on some buttons (in Eclipse). I could solve this by executing the following commands in my gnome-terminal

<a href="mailto:jochen@baileys">jochen@baileys</a> ~ $ export GDK_NATIVE_WINDOWS=1  
<a href="mailto:jochen@baileys">jochen@baileys</a> ~ $ cd APPZ/eclipse/galileo/
<a href="mailto:jochen@baileys">jochen@baileys</a> ~ $ ./eclipse 

Now, I realised the 3.5 Galileo version of Eclipse is in the Ubuntu repository. So I tried installing it:

<a href="mailto:jochen@baileys">jochen@baileys</a> ~ $ dpkg -l | grep eclipse
ii  eclipse                              3.5.1+repack~1-0ubuntu3                    Extensible Tool Platform and Java IDE
ii  eclipse-jdt                          3.5.1+repack~1-0ubuntu3                    Eclipse Java Development Tools (JDT)
ii  eclipse-pde                          3.5.1+repack~1-0ubuntu3                    Eclipse Plug-in Development Environment (PDE
ii  eclipse-platform                     3.5.1+repack~1-0ubuntu3                    Eclipse platform without plug-ins to develop
ii  eclipse-platform-data                3.5.1+repack~1-0ubuntu3                    Eclipse platform without plug-ins to develop
ii  eclipse-plugin-cvs                   3.5.1+repack~1-0ubuntu3                    Eclipse Team Integration (CVS support)
ii  eclipse-rcp                          3.5.1+repack~1-0ubuntu3                    Eclipse Rich Client Platform (RCP)

.. and the GUI problems were gone :p !!!

Small tip

Even the latest version of Maven 2 is in the repo !

<a href="mailto:jochen@baileys">jochen@baileys</a> ~ $ dpkg -l | grep maven2
ii  libmaven2-core-java                  2.2.1-1                                    Core libraries for Maven2
ii  maven2                               2.2.1-1                                    Java software project management and compreh

PS3 Media Server

Submitted by Jochus on Tue, 26/01/2010 - 22:37 | Posted in: Lifetime
Posted in

Een tijdje geleden heb ik eens wat verder zitten spelen met mijn PS3. De meeste mensen denken dat een PS3 enkel een game console is, maar voor mij is het een echt multimedia toestel. Ik speel heel eenvoudig blu-ray films af en ik ben enkele weken terug zelfs nog een stapje verder gegaan.

Ik installeerde op mijn laptop het programma PS3 Media Server. Mijn laptop en PS3 zijn wireless verbonden met mijn thuisnetwerk en het programma doet sowieso bij het opstarten een broadcast op mijn subnet (maw: hij gaat op zoek naar een PS3). Alles ging heel vlotjes en ik kreeg dit scherm te zien:



(klik op de foto om te vergroten)

Vervolgens ga je naar tabblad: Navigatie/Share Instellingen. In dit tabblad stel ik alles in wat ik wil sharen. Ik zou graag foto's en MP3's kunnen afspelen op mijn TV, dus ik toon ook aan waar die bestanden zich bevinden



(klik op de foto om te vergroten)

Vervolgens klik je op HTTP server herstarten om de wijzigen op te slaan en door te geven aan de PS3. Dan loopt ge naar uwe zetel en pakt ge uwe PS3 controller. Vervolgens ga je naar het menu Foto. Als je dit opent, zal je automatisch je PC zien tevoorschijn komen:



(klik op de foto om te vergroten)

Vervolgens open je deze media server en dan browse je gewoon de mapjes alsof je op je PC aan het browsen bent. Uiteindelijk kan je foto's openen en in-memory gaan draaien, vergroten, bijsnijden, ... zonder het originele bestand te beschadigen.



(klik op de foto om te vergroten)

Idem dito voor het afspelen van MP3's. Lijkt op zich dom, maar mijn PS3 hangt via de AUX aan mijn stereo waardoor ik aan een véél betere kwaliteit MP3's kan afspelen (de speakers van mijn laptop zijn niet écht optimaal :p). Zo speelt er altijd wel iets van muziek in het appartement :-) ...

O ja, PS3 Media Server is geschreven in Java :p !

JBoss Tools HTML editor: default tab: source

Submitted by Jochus on Tue, 26/01/2010 - 22:12 | Posted in: Java
Posted in

I'm using the JBoss Tools (Eclipse plugin) for a while now, and it gives me a lot of advantages while I'm programming. It has a lot of features and one of them is the JBoss Tools HTML editor. I'm using that editor to quickly create some XHTML files. The problem is that this plugin always starts the editor in DESIGN/SOURCE mode. I never use the DESIGN mode, so I just want to have the SOURCE mode.

After searching the preferences, I found a setting to set this to the DEFAULT configuration:

  • Window > Preferences
  • JBoss Tools
  • Web
  • Editors
  • Visual Page Editor



(click to enlarge)

Facelets Essentials

Submitted by Jochus on Tue, 26/01/2010 - 20:04 | Posted in: Java
Posted in

Some time ago, a colleague at work recommended me this book. It's really small (only counts 84 pages), but it's really good written! It reads fast en it makes a new Facelets developer very easy to start working with Facelets.

Most of the things, I was already familiar with. But I discoved a nice tag to use: < ui:debug.. />

The UI Debug tag allows you to display helpful information about the JSF component tree and scoped variables in your browser when you test your JSF pages. The hotkey attribute specifies a key combination (CTRL + SHIFT + D is the default value) to display the popup window containing the information. The UI Debug tag can be enabled or disabled by setting the rendered attribute.

It didn't work in the first time. I forgot to specify the facelets.DEVELOPMENT parameter in the web.xml (well, in my opinion, the book wasn't very clear on this one ...)

<context-param>
    <param-name>facelets.DEVELOPMENT</param-name>
    <param-value>true</param-value>
</context-param>

After a redeploy, there was a popup providing me a lot of information about the JSF component tree!

Ubuntu Karmic Koala 9.10 (part 2)

Submitted by Jochus on Tue, 26/01/2010 - 19:55 | Posted in: Linux
Posted in

Een tijdje geleden blogte ik over een switch van Windows naar Ubuntu op het werk (zie hier) Ondertussen werk ik al een tijdje met Linux en ik zou nooit meer terug kunnen naar mijn vorige manier van werken. Ik werk STUKKEN sneller. Alles opent in een flits, builden gaat snel, starten/stoppen van mijn JBoss server, de navigatie in mijn IDE, Eclipse Galileo, is SUPER, ... Ale, 'k heb eigenlijk niets slechts te zeggen. Maar, nja, er is een maar, helaas heb ik het probleem dat ik voor sommige zaken nog steeds een IE nodig heb (ook zijn we verplicht testen uit te voeren tegen deze browser), dus ik heb nog steeds een dual boot system nodig.

Maar voor de rest kan ik iedere Java developer zeker dit OS aanraden als development systeem :-) !

/etc/environment file in Ubuntu

Submitted by Jochus on Tue, 26/01/2010 - 19:45 | Posted in: Linux
Posted in

Environment variables provide a way to influence the behavior of software on the system. For example, the "LANG" environment variable determines the language in which software programs communicate with the user.

The meaning of an environment variable and the format of its value are determined by the application using it. There are quite a few well-known environment variables for which the meaning and the format have been agreed upon and they are used by many applications.

After installing Java, I needed to set the JAVA_HOME var, which was pointing to my JVM installation (/usr/lib/jvm/java-6-sun). Normally, I always set these vars in ~/.bashrc. But a lot of applications didn't seem to pick up this variable. I most of the time received errors as "JAVA_HOME NOT SET".

After Googling a while, I came to the conclusion that you have to set these vars in /etc/environment. In this way, all applications seem to pick up the JAVA_HOME variable :-)