I have not been quite impressed with MyEclipse’s Maven4MyEclipse plugin. The most disappointing thing about this is that after checking out an existing project from source control, I cannot add Maven “capabilities” using the context menu (which could be easily done with m2eclipse).

For the last couple days, I am running into this wierd bug with the “Java Maven Wizard”: When I try to check out an existing project from SVN using: “Find/Check Out As” -> “Check Out as a project configured using the New Project Wizard” -> “Java Maven Project” into a location other than the default location provided by the wizard, the wizard still checks out the project into the default location.

Hopefully I will have some solution in the Maven4MyEclipse forum.

Problem: Accessing MBeans in WebLogic versions 8.1 SP5 and after results in
javax.naming.NoPermissionException: User <anonymous> does not have permission on weblogic.management.home to perform lookup operation.

Solution:  A quick fix to this problem is to enable anonymous admin lookup in WebLogic server. In WebLogic 10, this option is available under Security tab of the domain.

Here is a small tip for eclipse users: running eclipse with -clean option once in a while can improve its startup time.

The clean option removes any cached data stored by eclipse runtime and forces cache reinitialization.

The heap size of the Jvm used by Maven (invoked via mvn.bat) can be changed using MAVEN_OPTS parameter at the OS level. For windows, this would be an environment variable.

Variable name: MAVEN_OPTS

Variable value: -Xmx512m

Here is some code to send a message to a JMS queue using Spring:

ConnectionFactory connectionFactory = // Look up connectionfactory from JNDI
    Queue queue = // Look up distributed queue from JNDI
    JmsTemplate jmsTemplate = new JmsTemplate(connectionFactory);
    jmsTemplate.send(queue, new MessageCreator() {
        public Message createMessage(Session sessionthrows JMSException
        {
          ObjectMessage message = session.createObjectMessage();
          // Set the message content
          message.setObject(new Object());
          return message;
        } }
    );

… grass grows on your keyboard :)

While I was on vaccation, Matt came up with this evil plan to water and grow grass on my keyboard.

It is not uncommon for enterprises to store their employee information in LDAP. Now this poses an interesting challenge for building ORM applications that need access to employee information. For example, consider writing an application that tracks the projects an employee is currently working on. Such an application would have the following simple domain model:

An ORM mapping tool such as Hibernate can easily map this domain model to a database backend. However, since the employee data comes from LDAP, hibernate out of box cannot create the mapping between Project and Employee domain objects. One way to solve this problem would be to implement a custom EntityPersister. In this post I will show a simple hack for achieving this using JPA EntityListeners.

First let us create Java objects and relationships between them. Here is some minimal code:

public class Employee implements Serializable
{
  private Long id;
  private String firstName;
  private String lastName;
  
  // Other fields, getters, setters and other logic
}

public class Project implements Serializable
{
  private Long Id;
  private String name;
  private String description;
  
  private Employee employee;
  
  // Getters, setters and other logic  
}

The next step is to define tables in the database. Here is the table structure:

PROJECT
———–
PROJECT_ID | NAME | DESCRIPTION | EMPLOYEE_ID |

EMPLOYEE
—————-
EMPLOYEE_ID |
Since all the employee information (including EMPLOYEE_ID) is available in LDAP, this table simply holds the unique id of an employee.

Then, create mappings for the domain objects using JPA. The mapping for Application is straightforward:

@Entity
@Table(name=“PROJECT”)
public class Project implements Serializable 
{
  @Id
  @Column(name=“PROJECT_ID”)
  // Sequence generator declarations
  private Long Id;
  
  @Column(name=“NAME”)
  private String name;
  
  @Column(name=“DESCRIPTION”)
  private String description;
  
  @ManyToOne(cascade= {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
  @JoinColumn(name=“EMPLOYEE_ID”)
  private Employee employee;

  // Getters, setters and other logic  
}

@Entity
@Table(name=“EMPLOYEE”)
public class Employee implements Serializable
{
  @Id
  @GeneratedValue(generator=“assigned”)
  @GenericGenerator(name=“assigned”, strategy=“assigned”)
  @Column(name=“EMPLOYEE_ID”)
  private Long id;
  
  @Transient
  private String firstName;
  
  @Transient
  private String lastName;
  
  // Getters, setters and other logic
}

With these mappings in place, hibernate can easily load the Project
object and the corresponding Employee object. To populate the
transient fields in the Employee object, an EntityListener needs to be
created. Here is a simple implementation for the entity listener:

public class EmployeeEntityListener
{
  @PostLoad
  public void loadEmployee(Employee employee)
  {
    Map<String, String> employeeData = // Read the employee data from LDAP using the employee Id as the key
    employee.setFirstName(employeeData.get(“FIRST_NAME”));
    employee.setLastName(employeeData.get(“LAST_NAME”));
  }
}

Finally register this entitylistener:

@Entity
@Table(name=“EMPLOYEE”)
@EntityListeners(EmployeeEntityListener.class)
public class Employee implements Serializable
{
  ——-

MDP (Message Driven Pojo) introduced in Spring 2.x offers a nice alternative to EJB’s Message Driven Beans.

package com.inflinx.test.mdp;

import javax.jms.Message;
import javax.jms.MessageListener;

public class TestMdp implements MessageListener
{
  public void onMessage(Message message)
  {
    System.out.println(message);
  }
}

Creating and configuring a MDP in Spring is a pretty straight forward process. The first step is to create a class that implements javax.jms.MessageListener interface.

Once the message listener is in place, the next step is to configure the MDP and related JMS components in Spring application context.  
<bean id=“testMdp” class=com.inflinx.test.mdp.TestMdp” />
<jee:jndi-lookup id=“connectionFactory” jndi-name=“jms.testConnectionFactory” />
<jee:jndi-lookup id=“queue” jndi-name=“jms.testQueue” />
<bean id=“jmsTransactionManager” class=“org.springframework.jms.connection.JmsTransactionManager”>
<property name=“connectionFactory” ref=“connectionFactory” />


</bean>



<bean id=“jmsContainer” class=“org.springframework.jms.listener.DefaultMessageListenerContainer”>

<property name=“connectionFactory” ref=“connectionFactory”/>

<property name=“destination” ref=“queue”/>

<property name=“messageListener” ref=“testMdp” />

<property name=“transactionManager” ref=“jmsTransactionManager” />

</bean>

Recently I came across this line of code:


private static final SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm a");

Unfortunately, this code belongs to a class whose instances will be used by multiple threads. Even though the API documentation for SimpleDateFormat mentions it being not thread safe, somehow it failed to get the developers attention.

As I got to think more about this, a @ThreadSafe JavaDoc element might be useful for API writers to convey their intent more clearly. Perhaps the generated JavaDoc for a thread safe class can use a different color or font making the distinction more visual.

DBUnit is a very effective tool for testing persistence layer code. But before we can test any persistence code, we need to “seed” the database with some test data. This is where a dataset comes into picture.  I personally like to store this data in an XML file (XML dataset) and load it before a test is run. XML datasets can be easily created by exporting data from an existing database. Here are three simple steps for doing this:

  1. Create a connection to the database. Using plain JDBC, here is what the code would look like:   

        Class.forName(“com.mysql.jdbc.Driver”);

        Connection jdbcConnection = DriverManager.getConnection(“jdbc:mysql://localhost:3306/test”,“user”,“pwd”);

        IDatabaseConnection connection = new DatabaseConnection(jdbcConnection);

  2. Create a QueryDataSet object and add a query for extracting the data:

        QueryDataSet dataSet = new QueryDataSet(connection);
        dataSet.addTable("Person""SELECT * FROM PERSON");
  3. Save the extracted data into an XML file.

        FlatXmlDataSet.write(dataSet, new FileOutputStream("person.xml"));

Each XML element in the dataset created will correspond to a row in the table with the element name being the name of the table. Here is a portion of dataset generated:

<Person ID=”9″ First_NAME=”JOHN” LAST_NAME=”DOE”/>
<Person ID=”10″ First_NAME=”JUDY” MIDDLE_NAME=”B” LAST_NAME=”TEST”/>
<Person ID=”11″ First_NAME=”JANE” MIDDLE_NAME=”S” LAST_NAME=”DOE”/>

An interesting thing to keep in mind is that when DBUnit is used to load this dataset into a database, it would read the first element to figure out the table metadata. Now, if the first element does not have a column (MIDDLE_NAME in this case) included, it would make DBUnit ignore that column in all other elements. This behavior can be avoided by generating a DTD that contains table column information. This is done using the following code:

FlatDtdDataSet.write(dataSet, new FileOutputStream("person.dtd"));

Once the DTD is in place, it can be included in the dataset doctype declaration. In this example, it would look something like: <!DOCTYPE dataset SYSTEM “person.dtd”>

Putting it all in a single method:

public void generateDataSet() throws Exception
  {
    Class.forName("com.mysql.jdbc.Driver");
    Connection jdbcConnection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","mysql");
    IDatabaseConnection connection = new DatabaseConnection(jdbcConnection);
    
    QueryDataSet dataSet = new QueryDataSet(connection);
    dataSet.addTable("Person""SELECT * FROM PERSON");
    
    FlatDtdDataSet.write(dataSet, new FileOutputStream("person.dtd"));
    FlatXmlDataSet.write(dataSet, new FileOutputStream("person.xml"));
    
    jdbcConnection.close();
  }

Next Page »