pvillega’s posterous

pvillega’s posterous

Pere Villega  //  Born in Barcelona, living in Dublin, and tagged as geek since youth. Developer in the path to becoming a software architect. I swear this is not a proper blog :)

Feb 16 / 8:18am

EJB Concepts and Services

This page contains a brief summary of EJB 3.0 Services and related concepts. It only gives basic information, for more details about life cycle and other functionalities check the EJB 3.0 reference or some book like EJB3 in Action.

Next I will describe some key concepts related to EJB 3.0

EJB Context

The EJBContext interface (definition available here) provides methods to interact with services like transaction, security, timer or even to do JNDI lookups. Both Session and Message beans implement this interface through inheritance.

You can access this interface through the SessionContext object to be able to call its methods. Depending on which bean are you using (Session or MDB) the container will add some extra methods to the object that may be useful for your bean. Examples of use of context in Session and Message-Driven beans:

@Stateless
public class PlaceBean implements PlaceLocal {

@Resource
private SessionContext context;
}


@MessageDriven
public class MDBTestBean implements MessageListener {

@Resource
private MessageDrivenContext context;
}

Dependency Injection

JEE 5 introduces dependency injection to remove all the hassle related to JNDI calls. You still can do JNDI calls using SessionContext objects but the easiest and recommended way is to use DI.

There are several annotations for this purpose. @EJB is used to inject beans while @Resource can be used as a more versatile mechanism of DI. @Resource allows you to provide a JNDI name of a resource defined in the container and it processes all the calls needed to load that resource, and it can be related to an instance variable or a setter method that follows java bean format.

Examples of dependency injection:

@Stateless
public class OtherBeanBean implements OtherBeanLocal {

@Resource(name = "jms/ShippingErrorQueue")
private Destination errorQueue;
}

@Stateless
public class PlaceBean implements PlaceLocal {

@EJB
private OtherBeanLocal otherBeanBean;
}

Interceptors

Interceptors are a form of Aspect-Oriented Programming (AOP) in EJB 3. They are objects that are automatically triggered when some EJB method is invoked.

This is achieved using the @Interceptors annotation, which can be applied to a method or an entire class (in that case it will affect all methods of the class, you can use the annotation @ExcludeClassInterceptors on a method to ignore the interceptor for that method). The annotation receives as parameters a list of class objects that are used as interceptors.

Each interceptor class must contain one (and only one) method annotated as @AroundInvoke, that signals the method to be used as interceptor. This method always has the same format, returning an Object and receiving as its only parameter an InvocationContext object. This class provides methods to check the name of the method called, parameters and other details and allows us to modify the parameters passed to the business method if needed.

The interceptor to end always with a call to the "proceed" method of InvocationContext to signal teh container it can proceed with the next step (next interceptor or the original method itself). Not calling proceed will halt the chain and the business method will never be accessed. One example of an interceptor and the method intercepted:

public class InterceptorExample {

@AroundInvoke
public Object logMethod(InvocationContext invocationContext) throws Exception{
log.warn("Method: "+invocationContext.getMethod().getName());
return invocationContext.proceed();
}
}

@Stateless
public class PlaceBean implements PlaceLocal {

@Interceptors(InterceptorExample.class)
public void method(){

}
}

Timer

EJB 3 includes a basic timer service to schedule jobs. You can queue objects into the timer inside a bean and assign a method of that bean to process the timer events. Timer can be used to schedule single-events or recurring ones.

One bean can have only one @Timeout method and it must follow the same structure (void return and receiving a Timer as parameter). You can only receive timer events in the same bean they were created (not same instance!) so you can't use Timer to send message across beans by itself, you will need to use JMS in the @Timeout method.

Example of a simple timer service with a method setting the timer and the @Timeout consumer:

@Stateless
public class PlaceBean implements PlaceLocal {

@Resource
TimerService timerService;

public void createTimer(){
String attachment = "attachment";
timerService.createTimer(10*1000, 10*1000, attachment);
}

@Timeout
public void scheduledMethod(Timer timer){
String attachment = (String) timer.getInfo();
}

}

Transactions

The JEE container does most of the heavy lifting on transactions, as implementing a working transaction manager is no easy task and is prone to errors. You should review concepts like ACID (atomicity, Consistency, Isolation, Durability) and two-phase commit before proceeding, to properly understand what's going on behind the scenes. In JEE the JTA API is responsible of transaction management.

There are two kind of transactions, container managed transaction (CMT) and bean managed transaction (BMT). CMT is simpler and the container does most of the work while the BMT provides more control over the process in exchange of more coding effort.

To use CMT we annotate with @TransactionManagement the class of the bean, indicating with the parameter the transaction will be managed by the container. Then we can flag the class or any transactional methods with @TransactionAttribute. This annotation tells the container how to behave when running the bean/method annotated: create a new transaction, reuse any existing transaction, never use a transaction... We must be aware our method may be called form another method that has started its own transaction, so its important to specify the behaviour of our bean. It has 6 choices: Required, Requires New, Supports, Mandatory, Not Supported and Never.

To rollback a transaction you must use the EJBContext, calling its "setRollbackOnly" method. You can check if any underlying CMT transaction has been marked for rollback using "getRollbackOnly", that way you can exit long operations before they finish as the transaction will fail anyway. An example of a CMT bean:

@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
public class CMTBean implements CMTLocal {

@Resource
private SessionContext context;

@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void transactionMethod(String p1, String p2) {
try{
//code
}catch(Exception e){
context.setRollbackOnly();
}
}

}

BMT is the other type of transaction, one which gives us a granular control over the transaction itself. Instead of it being related to a method we can specify the start of the transaction and its end. It works around the UserTransaction interface of the JTA API, using this interface to start, commit and rollback the transaction. The only annotation used is @TransactionManagement, to tell the container this bean is BMT.

The interface also contains some additional methods to manage the transactions. The method "setRollbackOnly" is used to mark the transaction as "roll back" if our BMT interacts with CMT beans, The method "getStatus" gives us detailed information of the transactional status, while "setTransactionTimeout" allows us to change the timeout of the transaction.

An example of BMT:

@Stateless
@TransactionManagement(TransactionManagementType.BEAN)
public class BMTBean implements CMTLocal {

@Resource
private UserTransaction userTransaction;

public void transactionMethod(String p1, String p2) {
try{
userTransaction.begin();
//code
userTransaction.commit();
}catch(Exception e){
userTransaction.rollback();
}
}
}

Security

JEE provides a flexible security model, based on the standard concepts of users, groups and roles, that manages both authentication and authorization. This is achieved using the JASS API, that abstract the underlying authentication systems (like LDAP). If you use a web front-end you will probably define some security aspects in web.xml. This section will only review the part related to EJB.

The most common use case is called "declarative security", consisting on some annotations that tell the container who can access which method. One example should be enough to understand it:

@DeclareRoles({"RoleA", "RoleB", "RoleC"})
@Stateless
public class DeclarativeSecurityBean implements DeclarativeSecurityLocal {

@RolesAllowed({"RoleA","RoleC"})
public void businessMethod1() {
}

@PermitAll
public void businessMethod2() {
}

@DenyAll
public void businessMethod3() {
}

}

On the other hand, programmatic security uses the EJBContext to check the role of the user. This system should not be used unless completely necessary due to requirements, as it makes the security layer much harder to manage, One good point about this kind of security is that it can be used along interceptors, but even with this advantage if we have several roles managing the system is no easy task.

One example will show why is not recommended (think about an application with several beans and roles):

@Stateless
public class ProgrammaticSecurityBean implements ProgrammaticSecurityLocal {

@Resource
private SessionContext context;

public void businessMethod() {
if(!context.isCallerInRole("RoleA") && !context.isCallerInRole("RoleB")){
 return;
}
//code for other roles
}
}

Loading mentions Retweet

Filed under // ejb ejb context ejb services java

Comments (0)

Feb 16 / 8:13am

Java Persistence API

This page contains a brief summary of Java Persistence API (JPA). It only gives basic information, for more details about life cycle and other functionalities check the EJB 3.0 reference or some book like EJB3 in Action.

Persistence is probably one of the biggest concerns of most enterprise applications. Data is key and we have to be sure it's consistent and our application can manage its changes properly. To that end lots of alternatives have been developed, with O/R mapping systems taking the led in the latest years due to the benefits of using an intermediate API that's closer to the OO model used in the business layer instead of direct interaction with the RDBMS.

EJB entities are the answer of EJB 3,0 to the persistence issue and it's implementation using JPA follows the same basic patterns as other components like session beans. That means they are POJOs with specific annotations (@Entity for JPA entities) that are capable of inheritance and whose non-abstract classes requires a public or protected no-argument constructor.

JPA is the most complex part of EJB 3.0. Not only controls the most critical component of our application but it provides a large number of options for a developer to be able to adapt it to his needs. I will try to break this complexity in some sections, like they do in the book EJB in Action, focussing on a few aspects of JPA. Remember this is just a quick summary that won't cover lots of aspects of JPA.

Basic domain concepts: entities and primary keys

As said above JPA is an O/R mapping system. That means it maps Java POJOs (objects) to data stored in the database as tables and rows (relational data). To achieve this JPA does a heavy use of annotations. In this section I will show basic POJOs with some common annotations and explain how they are used. That will enables us to map our tables to the application, although by itself it won't let our application work. Let's start with a basic entity:

@Entity
public class BasicEntity implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@Transient
private String disposableCode;

/**
* Get the value of disposableCode
*
* @return the value of disposableCode
*/
public String getDisposableCode() {
return disposableCode;
}

/**
* Set the value of disposableCode
*
* @param disposableCode new value of disposableCode
*/
public void setDisposableCode(String name) {
this.disposableCode = name;
}

public Long getId() {
return id;
}


public void setId(Long id) {
this.id = id;
}

@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}

@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof BasicEntity)) {
return false;
}

BasicEntity other = (BasicEntity) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}

return true;
}

@Override
public String toString() {
return "jpa.BasicEntity[id=" + id + "]";
}
}

In this example we can see some interesting characteristics of an entity. First one, the entity is marked with the @Entity annotation, that identifies this POJO as an EJB 3,0 entity. Another important step is to override the methods hashcode, equals and toString. This is not mandatory but it's considered a best practice to implement hashcode and equals so they use our primary key to identify our entity, and changing toString allows us to log and debug the application easily.

The persistence provider will store the values of any property or field that has public or protected setters and getters, which can't be declared final, so no especial annotation is required to enable their persistence. In this example you can see we use a @Transient annotation in one field. This is equivalent to the transient keyword related to Serialization and tells the persistence manager to not persist that specific field.

Another detail about the annotations: in this example they are on the fields of the classes. You could write them on the getter methods of those fields, but whatever system you choose you have to stick to it for all you entities. The only difference is that using field-annotation you could make your fields public and not use any getter or setter method and they would be persisted, while using the annotation in the getter method obliges you to implement all the getters/setters and make the field private. Given that the first way is a very dangerous and bad practice, so you will have a private field with getter and setters in your entities, choosing one over the other is usually a matter of taste.

I've left the @Id annotation for last. This annotation, as you can guess, tells the entity where is stored our unique id. The field that can be marked as Id has some restrictions: it must be a primitive, its wrapper or a Serializable type. Types like double or float are forbidden due to their lack of precision (due to the way computers work, you should know what I mean) and that could cause two different entities to be considered the same.

But the @Id annotation is marking only one field and we can't have more than one @Id in our class, so what happens if we have a primary key that uses several fields? There are two approaches to it.

The first approach uses the @IdClass annotation as follows:

@Entity
@IdClass(BasicEntityPK.class)
public class BasicEntity implements Serializable {
@Id
private Long id;

@Id
private String name;

//other non Id fields
//no need to implement equals and hashcode
//getters and setters

}

public class BasicEntityPK implements Serializable {
Long id;
String name;

public BasicEntityPK(){}

//implement equals and hashcode
}

As you can see we have our main entity class with several @Id fields assigned and a related class that contains the same fields. In this case we implement the equals and hashcode methods in the PK class, not in our entity. With this approach the container will use the entity to persist data and will map internally the fields to the PK class, which will be used when it needs to compare two entities.

The other alternative is the use of the @EmbeddedId annotation, like this:

@Entity
public class BasicEntity implements Serializable {

@EmbeddedId
private BasicEntityPK basicEntityPk;
//other fields
  //no need to implement equals and hashcode
//getters and setters

}

@Embeddable
public class BasicEntityPK{

Long id;
String name;

public BasicEntityPK(){}
//implement equals and hashcode
}

The skeleton is quite similar to the @IdClass one but in this case instead of having the primary key fields on both classes, we just put them in our PK class, and we embed that class into our entity as its primary key. Choosing between any of those methods is a matter of personal taste: one is harder to maintain due to replication, the other makes access to PK fields more awkward. Keep in mind that although you can use those structures sometimes is preferable the use of a surrogate key (we will review it later) as Id, as it will free you code from extra classes and it has better performance.

Now that we have talk about the @Embeddable annotation it might be a good time to explain its meaning. In our data model we may have some data that's always related to a certain object but that has sense by itself, like the address of a user. This address contains several fields (city, street) so it may be an entity but it's always related to a user. So in the object model it makes sense to implement it as its own object but in the relational model it will be in the same table as the user. To solve this JPA has the option to embed objects into entities, allowing us to declare this kind of relationship. An example:

@Entity
public class UserEntity implements Serializable {

@Id
protected Long id;
protected String name;
//other fields

@Embedded
protected Address address;

//implement equals and hashcode
//getters and setters

}


@Embeddable
public class Address implements Serializable {

protected String street;
protected String city;
//other fields

//implement equals and hashcode

}

Basic domain concepts: entities relationships

The data components in our model will have some kind of relationships between them: one-to-one, one-to-many, many-to-one or many-to-many. These relationships must be defined in our entities so the persistence provider can maintain the proper relations and the data consistency. In this section I will describe the annotations that manage that.

First one is the @OneToOne annotation, that defines a one-to-one relationship.This relationship can be unidirectional or bidirectional. Let's start with a bidirectional one:

@Entity
public class UserEntity implements Serializable {

@Id
protected Long id;

@OneToOne
protected VisaInfoEntity visaInfoEntity;
//other fields

//implement equals and hashcode
//getters and setters
}

@Entity
public class VisaInfoEntity implements Serializable {

@Id
protected Long id;

@OneToOne(mapedBy = "visaInfoEntity", optional = "false")
protected UserEntity userEntity;

//other fields
//implement equals and hashcode
//getters and setters
}

In this example we see the relation defined by the annotations in the parameters. Each class contain a parameter of the class that represents the entity related to it marked with @OneToOne. Notice that VisaInfoEntity adds some parameters to it's annotation, telling the persistence provider that the "owner" of the relation is the UserEntity class and which field is leading that mapping. The optional parameter set to false tells us there will always be a VisaInfoEntity for each user and a user for each VisaInfoEntity. If we want to convert this to a unidirectional link we just need to remove the reference to UserEntity and its annotation from VisaInfoEntity. With that the container will know our UserEntity may have zero or one VisaInfoEntity related to it.

The second type of relation is defined by the annotations @OneToMany and @ManyToOne. Those annotations usually go in pair to define both sides of the relation one-to-many. Usually in these relations one entity has a field of type Set or List of the other entity. One example:

@Entity
public class UserEntity implements Serializable {

@Id
protected Long id;

@OneToMany (mappedBy ="userEntity");
protected Set visaInfoEntity;
//other fields
//implement equals and hashcode
//getters and setters

}


@Entity
public class VisaInfoEntity implements Serializable {

@Id
protected Long id;

@ManyToOne
protected UserEntity userEntity;

//other fields
//implement equals and hashcode
//getters and setters

}

As you can see the owning part of the relation is VisaInfoEntity. In these type of relations the many-to-one part is always the leader, something to be aware of.

Last type of relations is defined by the annotation @ManyToMany. The relation is quite similar to the one-to-many explained above, but we can choose which entity is leading the relationship. An example:

@Entity
public class UserEntity implements Serializable {

@Id
protected Long id;

@ManyToMany (mappedBy ="userEntity");
protected Set visaInfoEntity;

//other fields
//implement equals and hashcode
//getters and setters

}


@Entity
public class VisaInfoEntity implements Serializable {

@Id
protected Long id;

@ManyToMany
protected Set userEntity;

//other fields
//implement equals and hashcode
//getters and setters

}

Mapping entities to DB

We know how to build entities and define relations between them. Now we need to map those entities to the tables of the database, as we will see next. Before looking at the example, be aware that using annotations for that purpose hard-codes the structure, so any changes to it will require a new version of the application. This is usually not a big deal but if you need to be able to change the mappings without compiling, use the XML descriptor version of the fields.

Next there's an example of a mapped entity. The meaning of the annotations is quite obvious, I will comment them after the code:

@Entity
@Table(name = "USERS")
@SecondaryTable(name = "USER_PICTURES", pkJoinColumns = @PrimaryKeyJoinColumn(name = "USER_ID"))
public class UserEntity implements Serializable {
  private static final long serialVersionUID = 1L;
 
  @Id
  @Column(name = "USER_ID", nullable = false, insertable=false, updatable=false)
  @GeneratedValue(strategy = GenerationType.AUTO)
  protected Long id;


  @Column(name = "USER_NAME", nullable = false)
  protected String name;

  @Column(name = "USER_LOGIN", nullable = false, length = 5)
  protected String login; @Enumerated(EnumType.ORDINAL)

  @Column(name = "USER_TYPE", nullable = false)
  protected UserType userType;

  @Column(name = "PICTURE", table = "USER_PICTURES")
  @Lob
  @Basic(fetch = FetchType.LAZY)
  protected byte[] picture;

  @Column(name = "CREATION_DATE", nullable = false)
  @Temporal(TemporalType.DATE)
  protected Date creationDate;

  @Embedded
  protected Address address;

  //setters, getters, hashcode, equals, etc

}

@Embeddable
public class Address implements Serializable {

//fields, setters, getters, hashcode, equals, etc
}

The first annotation which we must pay attention to is @Table. This annotation specifies which table contains the columns we will use for the entity. If not specified (both the name or the tag) the system will use a table with the same name as the class.

The @Column annotation declares the mapping to a column of the table. As you can see, accepts some extra parameters to indicate if the field can be null or it can be modified using update or insert. The persistence manager assumes the columns exist in the class table, but you can specify another table if needed as you can see at the picture field. As with the @Table annotation, if you don't define the name of the column or you8 don't add the annotation it will be assumed the column has the same name as the field.

There are some extra annotations for specific types of data. The @Enumerated annotation allows us to store enumerations. We can use two modes: Ordinal or String. The first will store the integer associated to the enumeration value while the second will store the complete string.

The @Lob annotation tell the manager this field will be stored in a CLOB (for char[] or String fields) or BLOB (any other type) column in the database. Usually you add the @Basic annotation to a @Lob object to enable lazy loading, as @Lob objects are usually very memory intensive.

The @Temporal allows us to store date-related information. By default it uses a granularity of timestamp, but we can choose between DATE, TIME or TIMESTAMP.

For the primary key of the application you may use (if it's a surrogate key) the @GeneratedValue annotation. This annotation will tell the persistence manager the field's value is generated by the database. That means it will only exist once the entity has been commited, so we careful when accessing items not commited yet as they will have a null here.

The @GeneratedValue annotation has 4 available strategies to assign the value. The simplest one is IDENTITY and assigns an incremental value to the key. The second one is SEQUENCE, that requires a sequence to be defined both in the database and in EJB (using @SequenceGenerator). The third one is TABLE, which uses a a table as generator of the values (with @TableGenerator). The last strategy is AUTO, where the persistence manager decides which one is the best strategy.

I have skipped an annotation in the class header, @SecondaryTable. This one is used when we need to map an entity to several tables, in this case because we store the BLOB object in another table. As you can see, we tell the annotation which table it has to use and the name of join field. You can use several secondary tables in the same entity. Although this annotation doesn't seem so useful, it allows you to distribute content on several tables, which can improve the performance of the RDBMS as it happens in this example where the BLOB would slow queries done to the user table. That said be aware that this annotation is not the same as @Embedded, which we saw before and refers to content in the same table.

As you look at the code, you might wonder if maybe we need to specify join keys for tables relationship as we did in the @SecondaryTable annotation. The answer is yes, there are some annotations (three) to that end. I will briefly comment them:

  • @JoinColumn: this annotation allows you to specify primary/foreign relations in the database model, when the referencing entity has a primary key and the referenced entity it's own primary key and a foreign key mapped to the primary key of the referencing entity. It can be used in one-to-one and one-to-many/many-to-one relations.
  • @PrimaryKeyJoinColumn: this annotation allows you to specify primary/foreign relations in the database model when both referencing and referenced entities share the primary key of the referencing table and the referenced table uses it's primary key as foreign key. It can be used in one-to-one relations.
  • @JoinTable: this annotation allows you to specify primary/foreign relations in the database model when you have a many-to-many relation so you need to use an intermediate table to store the mappings. Is used in conjunction with the @JoinColumn annotation to specify the relation between the main tables and the intermediate one.

One last subject to talk about is how to map inheritance. As we said, JPA are POJO and they can use OO characteristics as inheritance, but how can we write that into the database? I won't enter in too much detail, but to this aim we have the @Inheritance annotation. It has 3 related strategies:

  • Single table: all data of the different subclases will be stored in the same table and we use one column (specified in the @DiscriminatorColumn annotation) to differentiate between subclasses. Each subclass will be marked with @DiscriminatorValue to tell the persistence manager which value maps to that type of entity.
  • Joined Tables: we use one-to-one relations to model the inheritance. @DiscriminatorColumn and @DiscriminatorValue are used the same way but we also need to define the @PrimaryKeyJoinColumn between the tables. Is the recommended method.
  • Table per class: we use one table per class, including one for the parent entity. No relations must be defined, and the inherited columns are duplicated across tables.Due to possible issues with polymorphism and entity retrieving, is not recommended to use this method

Entity Manager

We've seen how to map the entities to the database, but you'll probably noticed I said nothing about how the entities are persisted. This section will talk about the Entity Manager, the interface responsible of all CRUD operations that allows you to retrieve and store entities from/into the database. An important consequence of this is that JPA being managed by this interface and not the container they don't have access to services like injection, timers, etc. It's not a big loose due to the way entities are (commonly) used but it's something to be aware of. I won't talk about the lifecycle in detail, just keep in mind the Entity Manager is only aware of entities in it's context (that can be as short as a method call or as long as a session), and an entity is not managed until you persist it.

A basic demonstration of the use of the Entity Manager follows. I won't comment the code as it's quite obvious:

@Stateless
public class ItemManagerBeanBean implements ItemManagerBeanLocal {

@PersistenceContext(unitName="contextName")
private EntityManager em;

public Item addItem(String[] params...){
Item it = new Item();
//do something
em.persist(it);
return it;
}

public Item updateItem(Item it){
em.merge(it);
return it;
}

public Item undoItemChanges(Item it){
//we merge to attach to the entity manager before refreshing
em.refresh(em.merge(it));
return it;
}

public void deleteItem(Item it){
//we merge to attach to the entity manager before removing
em.remove(em.merge(it));
}

public Item getItem(long key){
return em.find(Item.class, key);
}

}

There's a scenario that we must discuss in more detail. We may have an entity that contains another entity (maybe in a one-to-one relation) and both are new entities not stored (yet) in the database. Although it seems a logic behaviour that when we persist the enclosing entity both are saved into the database, this is not the default behaviour. This is justified as cascading can be resource intensive when propagating to several instances, and probably most of them have not been modified which means we are wasting resources.

This functionality is defined by the "cascade" property that you can set when declaring relationships between entities (@OneToOne, etc). By default this property is empty so no persistence operation applied to one entity is propagated to related entities. You can change this by setting cascade to one of these values: MERGE, PERSIST, REFRESH, REMOVE or ALL. The first four tell the Entity Manager to propagate only the selected operation while the last one propagates all the persistence operations.

Query API

The query API is a mechanism that allows you to find entities using SQL or JPQL, hiding the datasource behind the Entity Manager. It's a complement to the find method that allows you to recover several related entities a once. It allows for two kind of queries: named and dynamic.

Named queries are intended to be stored and reused, allowing for some optimizations. They are defined at class level and can receive parameters, and one entity may have several named queries. Using named queries you can isolate the SQL/JPQL from the places where is used, making it more maintainable. You may even define them in xml descriptors, decoupling them from the code.

An example of a named query would be:

@Entity
@NameQuery(name="findAll", query="Select c from category c where c.name like :name");
public class category implements Serializable{
//fields and methods

public Category getCategoryByName(String name){
//assume em is an instance of the Persistence Manager (Entity Manager)
Query query = em.createNamedQuery("findAll"); //find named query by name
query.setParamenter("name",name);
return query.getResultList(); //returns list of entities
}
}

Dynamic queries are generated "on the fly", usually queries received from some other component. When possible is recommended to work with named queries, due to the performance enhancements they allow. En example of a dynamic query:

     //assume em is an instance of the Persistence Manager (Entity Manager)
Query query = em.createQuery("Select c from categories c");
return query.getResultList(); //returns list of entities

JPQL and SQL

JPA accepts both JPQL and SQL for queries. Although they look quite similar, SQL works with the relational environment while JPQL works with entities, thus behaving in quite a different way behind the curtain. The recommendation for JPA is to use JPQL always, unless some odd exception requires us to use SQL.

I wont enter in details about JPQL as a brief tutorial wont cut it. Instead I point you to the official SUN tutorial which should help you understand this language.

Loading mentions Retweet

Comments (0)

Feb 16 / 8:02am

Message-Driven Beans

This page contains a brief summary of EJB 3.0 Message-Driven Beans (MDB). It only gives basic information, for more details about life cycle and other functionalities check the EJB 3.0 reference or some book like EJB3 in Action.

Message-Driven Beans are an abstraction over Java Messaging Service (JMS). They are used to send and receive messages in your application without having to know all the details about JMS. That said a good understanding of JMS is important for the correct use of MDB. The advantages of MDB over standard JMS coding are the services provided by the container (like pooling) and the reduction on code size due to automation of tasks.

By message (in the context of a JEE application) we mean an asynchronous and loosely coupled communication between system components. Using Message-Oriented Middleware (MOM) messages sent are stored until a consumer is available to read them. We consider two types of communication:

  • Point-to-point: the message is stored in a queue and received by one of the N possible consumers of the message
  • Publish-Subscribe: message is received by N subscribers that belong to a specific group of receivers

MDB are POJOs like other EJB and require a public constructor without arguments. You can't throw any RuntimeException or RemoteException as that would cause the MDB to be terminated. They also have the following requirements:

  • Implement MessageListener interface
  • use @MessageDriven annotation to configure the queue they are listening and some JMS properties (using @ActivationConfigProperty). Values include:
    • acknowledgeMode: (on Queues) to notify the consumption of the message
    • subscriptionDurability: (on Topics) guaranties delivery of message to offline subscribers
    • messageSelector: filters messages consumed using a property of the message included in the message header
  • it has two lifecycle callbacks (@PreDestroy and @PostConstruct) equivalent to the Session Bean ones.
  • can send messages but you need to follow the JMS API for that, using a Connection Factory, etc.
  • by default the "onMessage" method creates a transaction that rolls-back if there's any error while processing the message, leaving the message in the queue for another consumer.

Example of MDB listening to a Queue (point-to-point communication) named SampleServerQueue:

@MessageDriven(mappedName = "SampleServerQueue", activationConfig = {
@ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue")
})
public class MDBTestBean implements MessageListener {

//create the references to a destination Queue where we will send messages using DI
@Resource(name = "jms/ShippingErrorQueue")
private Destination errorQueue;

@Resource(name = "jms/QueueConnectionFactory")
private ConnectionFactory connectionFactory;

private Connection jmsConnection;

public MDBTestBean() {
}

//message consumer, reads a message from the queue
public void onMessage(Message message) {
}

//send a message
public void sendMessage() {

try {
Session session = jmsConnection.createSession(true, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = session.createProducer(errorQueue);
ObjectMessage message = session.createObjectMessage();

//add info to message
message.setObject("Message");

producer.send(message);
session.close();

} catch (JMSException ex) {
Logger.getLogger(MDBTestBean.class.getName()).log(Level.SEVERE, null, ex);
}
}


@PostConstruct
private void onConstruct() {

try {
jmsConnection = connectionFactory.createConnection();
} catch (JMSException ex) {
Logger.getLogger(MDBTestBean.class.getName()).log(Level.SEVERE, null, ex);
}
}


@PreDestroy
private void onDestroy() {

try {
jmsConnection.close();
} catch (JMSException ex) {
Logger.getLogger(MDBTestBean.class.getName()).log(Level.SEVERE, null, ex);
}
}

}

Loading mentions Retweet

Filed under // ejb java message driven beans

Comments (0)

Feb 16 / 7:44am

Packaging EJB Applications

This page contains a brief summary about Packaging of EJB applications. It only gives basic information, for more details about life cycle and other functionalities check the EJB 3.0 reference or some book like EJB3 in Action.

What's packaging? To be able to interact with a JEE application you have to put that application inside a JEE container, a process called deployment. But a normal (and reasonably complex) JEE application consists of several pieces: JSF, Session Beans, MDB, JPA and more. To facilitate the deployment process JEE allows you to group these components into files, in a process called packaging. The different files (ear, war, jar) are zip files with a specific structure and a specific extension to indicate the type of contents it has. Each file has a descriptor, an xml file with configuration related to its contents.

These formats and processes are defined in the JEE standard, which means they are completely portable between different servers making sure the code you write will work on any server that follows the standard. They are:

  • CAR (client application archives). Descriptor: application-client.xml. Contains: thick Java clients for EJB
  • EAR (enterprise application archives). Descriptor: application.xml. Contains: other JEE modules such as WAR and EJB-JAR
  • EJB-JAR (EJB Java archives). Descriptor: ejb-jar.xml/persistence.xml. Contains: Session beans and MDB. If it includes persistente.xml then we can add JPA entities
  • RAR (resource adapter archives). Descriptor: ra.xml. Contains: Resource adapters
  • WAR (web application archives). Descriptor: web.xml/persistence.xm. Contains: Web application. If it includes persistente.xml then we can add JPA entities

Next I will explain the format of EJB-related files (it's a part of the SCBCD exam so pay attention!)

EAR files

An example of a typical EAR file can be:

META-INF/application.xml
file1-ejb.jar
file2.war
file3-client.jar
lib/lib1.jar
lib/lib2.jar

While the contents of application.xml follow a structure similar to:


file1-ejb.jar
file2.war
file2
file3-client.jar

EJB-JAR files

An example of a typical EJB-JAR file can be:

META-INF/MANIFEST.MF
META-INF/ejb-jar.xml
package/*.class

While the contents of ejb-jar.xml follow a structure similar to:

       BeanOne
package.BeanOneRemote
package.BeanOne
stateless

Container
BeanOne
*

Required
users

Although this is just a small fraction of the possible contents of this file (like interceptor, etc.) you can observe all the values have their counterparts as annotations. Choosing one over another is a matter of taste, although usually annotations make a simpler way of managing the beans (except in cases where we can't hardcode the value). As a matter of fact you can use both at the same time, and any configuration in the descriptor file will override the annotations.

You must be aware the standard don't define some aspects (like the passivation mechanism), leaving them to vendors. That means vendors usually have another descriptor, with a proprietary format, to manage those configurations. For example JBoss uses the "jboss.xml" file. Although the vendors usually provide annotations for those aspects, it's not recommended to use them as that would break the portability of the code. Is better to use the proprietary xml descriptors so you can replace them as needed if you change your container.

Entities

As you may remember entities don't have their own archive file, but they are deployed along EJB or WAR packages. That said, they need their own configuration files so in a package with JPA entities you will find a file named "persistence.xml" in the META-INF folder and the corresponding class files in their packages. You may have a file named "orm.xml" inside META-INF. This optional files describes OR mappings for you files.

The persistence.xml file has a structure similar to:

oracle.toplink.essentials.PersistenceProvider
jdbc/ApplicationDS
secondORmap.xml
entities/EntitiesFile.jar
package.Class1
package.Class2

As you can deduce from the format you can define several persistence units in the same file, and map them to their OR xml files using the mapping-file tag. Those OR xml files have

Loading mentions Retweet

Comments (0)

Feb 16 / 7:42am

EJB 3.0 Performance (basic)

This page contains some basic information about Performance and Scalability with EJB 3.0. It only gives basic information, for more details about life cycle and other functionalities check the EJB 3.0 reference or some book like EJB3 in Action

Entity locking

JPA entities work directly with the database. On any medium-sized application our database is prone to concurrency errors due to users modifying the data while other transactions are in progress. RDBMS vendors implement several procedures to ensure the integrity of transactions and JPA makes use of those procedures to ensure data consistency. From all the different solutions available, JPA only requires optimistic locking using entity versioning. Some JPA implementations may provide other locking mechanisms but they will be vendor specific.

Optimistic locking in JPA is based on an additional column in each table that stores a version number for the entity. That value is marked with the @Version annotation and is managed by the JPA provider, so we can ignore it in the application. The downside of this mechanism is that our table needs an additional column of int or long type to be able to process the locks, but in exchange we will be notified (with an exception) if there is some data inconsistency, so we can tell the user and show the proper data. An example of an entity implementing optimistic locking:

@Entity
@Table(name="ITEMS")
public class Item implements Serializable{

@Id
@Column(name ="ITEM_ID")
protected Long itemId;

//more data
@Version //optimistic locking value
@Column(name ="OPT_LOCK")
private Long version;
}

This mechanism is used automatically when the Entity Manager detects the existence of a @Version field, but you can request a read or write locking for an entity. This is rarely used due to the performance penalties it may create, but it's useful in situations like creating a report, when you need a read lock to avoid other users changing the contents of the report.

Entity performance

Usually bad performance in a JEE application is due to issues with the persistence layer. The wrong database structure or bad tuning can degrade the performance by a factor of 2 or even 10. Next there's a non-exhaustive list of tricks to improve entity performance:

  • Merge tables: don't try to follow the normalization rules too strictly. If you find 1-to-1 relations or data that's retrieved always (or most of the time) together, merge the tables. You can then create an @Embedded object inside the main entity to maintain the logical separation, but you have avoided a join every time you retrieve that data.
  • Divide tables: this may seem a contradiction of the previous point, but it's not. Sometimes you have a table with data that you don't use too often. That's the case when you have some fields marked as @Lob (lazy loading). If those fields include BLOB probably you are better creating a new table with a 1-to-1 relationship and lazy loading that new entity. The reason is that lazy loading of BLOB objects is not mandatory on EJB 3 and for fields you won't use frequently that can be a huge penalty for the entity.
  • Choose the right inheritance strategy: JPA supports 3 inheritance mapping strategies. If possible try to use the single-table strategy as it has no need of joins, improving the overall performance
  • Properly size the connection pool: JPA uses JDBC to connect to the database, so strategies that improve JDBC performance also have an impact on JPA. Is important to check you pool is big enough to serve as many users as possible, to avoid delays due to users waiting for a free connection.
  • Cache statements: most vendors support SQL caching, reducing the time needed to answer a select query, but JDBC will only catch queries that use parameter binding so try to build the queries that way.
  • Use named queries: use named queries (annotation @NamedQuery) to enhance even more the performance of your queries. They are cached and can receive parameters but suffer of extra optimization which makes them better than normal queries that use parameter binding.
  • Avoid read-only transactions: by default a session bean has a "Required" transaction attribute. Establishing a transaction environment is expensive so if your method won't update the database set the transaction to Not_Suported for better performance.
  • Chang fetch type: by default JPA does a lazy loading for one-to-many or many-to-many relations and eager loading for one-to-one and many-to-one relations. If you don't need the data right away, switch to lazy loading when possible as it uses queries with less joins that are easily cacheable.
  • Be careful with locking: even if your vendor supports pessimistic locking, be careful due to the performance penalties it implies. Try to use a read optimistic lock instead.
  • Set the proper cascade: when setting the cascade property be careful to choose the proper value as it creates extra queries that may not be needed for your application
  • Bulk updates: sometimes you need to apply updates to a group of entities you retrieve with a select. If possible do this using a single Update query with the proper where clause, that way you run 1 query instead of x Update queries (one per entity recovered)
  • Avoid association tables: association tables (@JoinTable) are used on one-to-many relationships but they require several extra queries that relieve heavily i joins, degrading the performance. Avoid them if you can.
  • Be careful with the generated SQL: with EJB you create JPQL queries that are translated to SQL. Try to be careful with the syntax of your queries as it may have a huge impact on performance. As an example, if you run "SELECT FROM Item I" you will do a full scan of the table when you may not need all the existing items and can add some "WHERE" clause to obtain only the needed items. Also be careful to use only indexed fields for filtering, entities relationship or ordering.

EJB Components

Although they don't create too many performance issues and most of them are related to heavy algorithms in the business layer, EJB components like Session beans and MDB can be optimized. Next there a non-exhaustive list of good practices to that end:

  • Use the proper interface: if your beans will be used in the same container use your @Local interface instead of the @Remote one, as it will allow for some runtime optimizations.
  • Use the proper session bean: never use a stateful session bean unless necessary as they can't be pooled and have a much worse performance
  • Use Facades: try to use facades in front of your fine-grained beans so the client uses just one bean. This is a good design approach and improves the performance when using the @Remote interface.
  • Check transaction attribute settings: if you use CMT by default all methods Require a trnasaction, while in fact most of them don't. Set the Not_Supported attribute to those methods.
  • Tweak the pool: stateless session beans are pooled, and usually the vendor of the container allows you to configure the pool. Try to set it at the proper size.
  • Set the passivation policy: stateful session beans don't use a pool but have a cache and policies related to their passivation. Try to set the proper policies to avoid too much passivation as it has a direct impact on performance.
  • Use the Remove method: stateful session beans have the option of marking at least one method with the @Remove annotation so the bean is scrapped when the method is called. Use it to free resources and avoid unnecessary passivations.
  • Tweak the JMS provider: most of the performance of MDB is bounded to the JMS provider you are using, so check its documentation and set the proper configuration for your usage scenario, like pool size, etc.
Loading mentions Retweet

Filed under // ejb java performance

Comments (0)

Feb 16 / 7:39am

Session Beans

This page contains a brief summary of EJB 3.0 Session Beans. It only gives basic information, for more details about life cycle and other functionalities check the EJB 3.0 reference or some book like EJB3 in Action.

Session Beans' usage is mainly to store business logic and make that logic available to clients. They can be accessed locally, remotely or via web services. The container gives some services to enhance these beans like thread safety, transaction and timer services amongst others.

Session Beans (SB) are POJOs with some annotations that tell the container this class is an EJB, and at least one interface (EJB use interface-based programming). As POJO all SB can use inheritance. All SB need at least one no-argument constructor (public or protected) and all the business methods must have public access but no static or final modifiers. There are two kinds of SB: stateless and stateful.

Stateless Session Beans

These beans don't maintain any conversational state so each call is like a new call from a new client. They have no "memory". They are ideal for fast operations and as interfaces to webservices. It may have 3 interfaces, not all of them have to expose the same business methods:

  • Local (@Local) can only be accessed from the same container. No special restrictions.
  • Remote (@Remote) can be accessed remotely using RMI. All parameters and return values must be serializable.
  • Webservice (@Webservice) allows access using SOAP protocol. No special restrictions.

It allows up to two method callbacks to manage bean status that don't need to be public. Usually they are used to load/free resources like DB connection. They are:

  • PostConstruct (@PostConstruct) is run after the bean it's been loaded, to initialize it's status
  • PreDestroy (@PreDestroy) is run before scrapping the bean, to close any resource it's using

An example of stateless bean with two interfaces, one local and one remote:

@Stateless

public class Test2Bean implements Test2Remote, Test2Local {

//loads a jndi resource using DI
@Resource(name = "HSQLDB")
private DataSource HSQLDB;

public void businessMethod1(String parameter1) {
}

public String businessMethod2() throws FileNotFoundException {
return null;
}

//life cycle methods (below) can be non-public
@PostConstruct
private void methodConstruct(){
}

@PreDestroy
protected void methodDestroy(){
}

}

An example of Local interface for the previous bean:

@Local
public interface Test2Local {
void businessMethod1(String parameter1);
String businessMethod2() throws FileNotFoundException;
}

An example of Remote interface for the previous bean:

@Remote
public interface Test2Remote {
void businessMethod1(String parameter1);
String businessMethod2() throws FileNotFoundException;
}

Sateful Session Beans

These beans maintain status between calls. This means they have a performance penalty as can't be pooled and one instance is launched per client, but are perfect tools for multi-step processes like wizards. They have an extra restriction: all it's instance variables must be serializable, due to how the container manages this type of beans. A stateful bean may have 2 interfaces, not all of them have to expose the same business methods:

  • Local (@Local) can only be accessed from the same container. No special restrictions.
  • Remote (@Remote) can be accessed remotely using RMI. All parameters and return values must be serializable.

It allows up to five method callbacks to manage bean status that don't need to be public. Usually they are used to load/free resources like DB connection. They are:

  • PostConstruct (@PostConstruct) is run after the bean it's been loaded, to initialize it's status
  • PreDestroy (@PreDestroy) is run before scrapping the bean, to close any resource it's using
  • PrePassivate (@PrePassivate) is run before passivating the bean. Usually it's similar to PreDestroy
  • PostActivate (@PostActivate) is run after restoring the bean. Usually it's similar to PostConstruct
  • Remove (@Remove) is called by the client to notify the server it can destroy the bean. It's important to call it to free unused resources. More than one method in the same bean can have this annotation.

An example of stateless bean with two interfaces, one local and one remote:

@Stateful
public class TestStatefulBean implements TestStatefulRemote, TestStatefulLocal {

//we call another bean using DI
@EJB
private Test2Local test2Bean;


public void businessMethod1() {
}

@Remove
public String businessMethod2() {
return null;
}

@PostConstruct
@PostActivate
private void methodConstruct() {
}

@PreDestroy
@PrePassivate
protected void methodDestroy() {
}

}

An example of Local interface for the previous bean:

@Local
public interface TestStatefulLocal {

void businessMethod1();
String businessMethod2();
}

An example of Remote interface for the previous bean:

@Remote
public interface TestStatefulRemote {

void businessMethod1();
String businessMethod2();
}

Loading mentions Retweet

Filed under // ejb java session beans

Comments (0)

Feb 16 / 7:28am

Web services (JAX-WS)

This page contains a brief summary of Web services. It only gives basic information, for more details about life cycle and other functionalities check the EJB 3.0 reference or some book like EJB3 in Action.

Java gives support to several implementations of web services, as REST, XML-RPC or SOAP. Sadly JEE 5 doesn't require support for REST so it's covered by proprietary extensions, but it covers pretty well XML-RPC and specially SOAP using JAX-WS. In this section I won't discuss the particulars of web services like UDDI or WSDL. Suffice to say JAX-WS 2.0 is the API to use for managing web services and it provides compatibility with JEE 1.4 XML-RPC calls although it favours SOAP web services. This library allows you to use both POJOs or EJB as web services. Although each one has its advantages (like POJOs being able to run in tomcat while EJB aren't) the usage of EJB as web services is recommended as you obtain extra container functionalities like timers, transactions, security and more that plain POJOs lack.

An example of stateless Session bean being exposed as web service:

//We use annotations to generate our web service interface over a stateless bean
//WebService is the only required annotation and defines de urn
//SOAPBinding can be document (SOAP) or RPC (XML-RPC)

@WebService(targetNamespace ="urn:DemoWebService")
@SOAPBinding( style = SOAPBinding.Style.DOCUMENT)
@Stateless
public class WebServiceBean implements WebServiceLocal {

//these annotations allows us to control the names of the params and return value
//of the exposed method
@WebMethod
@WebResult (name = "webNumber")
public Long webMethod(@WebParam(name = "user") String user) {
return Long.MAX_VALUE;
}
}

The only required annotation is @WebService. Other annotation allows us to configure details like the binding (SOAP or RPC), which methods are exposed and the names of the parameters in the WSDL.

@WebService can be added to the bean or to one interface. If added to the interface all its methods will be exposed, while if we use it on the bean it will expose all the bean methods, unless we mark them explicitly with @WebMethod to identify the ones which should be exposed. @WebMethod can also be used to mark methods that must be hidden user the parameter "exclude" in the annotation.

@WebParam can be used to customize parameters (and @WebResult for the return value) of a method. It allows to change the exposed name and the mode (IN, OUT, INOUT) of each parameter along with other properties. There are some other annotations in the specification, like @OneWay, used to mark method with no output so they are optimized, or @HandlerChain to set up web service specific interceptors.

To consume those web services, you can use the @WebServiceRef annotation both in Java clients or EJB. In the latter case the annotation can be used to perform dependency injection.

Loading mentions Retweet

Filed under // ejb java jax-ws web service

Comments (0)

Feb 16 / 7:26am

EasyMock

EasyMock provides Mock Objects for interfaces in JUnit tests by generating them on the fly using Java's proxy mechanism. A Mock Object is a test-oriented replacement for a collaborator. It is configured to simulate the object that it replaces in a simple way. In contrast to a stub, a Mock Object also verifies whether it is used as expected. EasyMock creates mock objects using the java.lang.refect.Proxy object. When a mock object is created, a proxy object takes the place of the real object. The proxy object gets its definition from the interface or class you pass when creating the mock. EasyMock has two sets of APIs. One is intended for creation and manipulation of mock objects that are based on interfaces, the other on classes (org.easymock.EasyMock and org.easymock.classextensions.EasyMock respectively). Both provide the same basic functionality; however classextensions does not have quite as extensive as an API as the regular EasyMock does.

Basics

Similar to JUnit a mock object in EasyMock has a life cycle of 4 steps: create, expect, replay and verify. These steps are used to record the expected behaviour of the object in the test and to validate the result. If the verify step fails the test will fail. Before creating an object with EasyMock you must know there are 3 types of objects defined:

  • Regular: A test fails if a method is called that is not expected or if a method that is expected is not called. Order of method calls does not matter.
  • Nice: A test fails if a method is expected but not called. Methods that are called but are not expected are returned with a type appropriate default value (0, null or false). Order of method calls does not matter.
  • Strict: A test fails if a method is called that is not expected or if a method that is expected is not called. Order of method calls does matter.

Creating mock objects

There are two main ways to create a mock object using EasyMock, directly and through a mock control. When created directly, mock objects have no relationship to each other and the validation of calls is independent. When created from a control, all of the mock objects are related to each other. Examples of these ways are:

Direct creation of mock objects

@Overridepublic

void setUp() {

UserDAO userDAO = EasyMock.createMock(UserDAO.class);

CustomerDAO customerDAO = EasyMock.createMock(CustomerDAO.class);

}

Creation of a mock object using a control

@Overridepublic

void setUp() {

IMocksControl mockCreator = EasyMock.createControl();

UserDAO userDAO = mockCreator.createMock(UserDAO.class);

CustomerDAO customerDAO = mockCreator.createMock(CustomerDAO.class);

}

The API to create mock objects consists on 3 versions of the method createMock, one for each type of object: createMock, createNiceMock and createStrictMock.

Recording Behaviour

Once we have created our mock objects we need to record its behaviour to be able to validate it later. There are three groups of scenarios that exist when recording behaviour: void methods, non void methods and methods that throw exceptions. Void methods are the easiest behaviour to record. Since they do not return anything, all that is required is to tell the mock object what method is going to be called and with what parameters. This is done by calling the method just as you normally would.

Code being tested

foo.bar();

String string = “Parameter 2”;

foo.barWithParameters(false, string);

Mocking the behavior

Foo fooMock = EasyMock.createMock(Foo.class);

fooMock.bar();

fooMock.barWithParameters(false, “Parameter 2”);

When methods return values a mock object needs to be told the method call and parameters passed as well as what to return. The method EasyMock.expect() is used to tell a mock object to expect a method call.

Code to be tested

String results = foo.bar();

String string = “Parameter 2”;

BarWithParametersResults bwpr = foo.barWithParameters(false, string);

Mocking the behaviour

Foo fooMock = EasyMock.createMock(Foo.class);

EasyMock.expect(foo.bar()).andReturn(“results”);

EasyMock.expect(foo.barWithParameters(false, “Parameter 2”)).andReturn(new BarWithParametersResults());

In order to be able to test that a method throws the appropriate exceptions when required, a mock object must be able to throw an exception when called.

Code to be tested

try {

String fleName = “C:\tmp\somefle.txt”;

foo.bar(fleName);

} catch (IOException ioe) {

foo.close();

}

Mocking the behaviour

Foo fooMock = EasyMock.createMock(Foo.class);

EasyMock.expect(fooMock.bar(“C:\tmp\somefle.txt”)) .andThrow(new IOException());

foo.close();

There are times where a method will be called multiple times or even an unknown number of times. EasyMock provides the ability to indicate those scenarios with the .times(), .atleastOnce() and .anyTimes() methods.

Replaying and validating

Once the behaviour of the mock objects has been recorded with expectations, the mock objects must be prepared to replay those expectations. Mock objects are prepared by calling the replay() method and passing it all of the mock objects to be replayed.

   Foo fooMock = EasyMock.createMock(Foo.class);

EasyMock.expect(fooMock.doSomething(parameter1, parameter2)).andReturn(new Object());

EasyMock.replay(fooMock);

The final step in the mock object life cycle is to validate that all expectations were met. That includes validating that all methods that were expected to be called were called and that any calls that were not expected are also noted. To do that, EasyMock.verify() is called after the code to be tested has been executed. The verify() method takes all of the mock objects that were created as parameters, similar to the replay

() method.

   Foo fooMock = EasyMock.createMock(Foo.class);

EasyMock.expect(fooMock.doSomething(parameter1,Parameter2)).andReturn(new Object());

EasyMock.replay(fooMock);

Bar bar = new Bar();

bar.setFoo(fooMock);

EasyMock.replay(fooMock);

bar.runFoo();

EasyMock.verify(fooMock);

Real example

EasyMock can be quite confusing so I add an example of a "real case" scenario on how it would be used to mock an object in a certain unit test:

     private LoginServiceImpl service;

private UserDAO mockDao;

@Before

public void setUp() {

service = new LoginServiceImpl();

mockDao = createStrictMock(UserDAO.class);

service.setUserDAO(mockDao);

}

public void testRosyScenario() {

User results = new User();

String userName = "testUserName";

String password = "testPassword";

String passwordHash = "534h345kfswd3453"; //this should be a hash of the password

expect(mockDao.loadByUsernameAndPassword(eq(userName), eq(passwordHash)))

.andReturn(results);

replay(mockDao);

assertTrue(service.login(userName, password));

verify(mockDao);

}

Credit of this text to the amazing refcard of Dzone: http://refcardz.dzone.com/refcardz/junit-and-easymock

Loading mentions Retweet

Comments (0)

Feb 16 / 7:25am

Exception Handling

One important aspect of your code is how it handles errors. Long gone are the times of C programming where you had to check global variables or method's return values to detect and identify errors. Exception handling, the new paradigm, is more convenient for the developer, specially the novice one, but it has a downside: is really easy to do it the wrong way. With C-style control error you have a pattern to check for errors. Yes, it's verbose and repetitive, but it's hard to mess with it. With Java, exceptions are much easier to manage and they are enforced by the compiler (at least checked exceptions, the ones you can expect your code to throw back on you) but is so easy to do things like:

  try{

//code

}catch(Exception e){

log.error("Error");

}

A piece of perfectly worthless code. Yes, you catch the exception, but what information is given to identify why it happened? How can you solve the error (in case you have to)? And this kind of code is quite common. Handling exceptions in Java is not as obvious as handling errors in C, but we can generate a list of things to do and things to avoid. That's is my objective in this post.

The basics

One of the most important concepts about exception handling to understand is that there are three general types of throwable classes in Java: checked exceptions, unchecked exceptions, and errors. Checked exceptions are exceptions that must be declared in the throws clause of a method. They extend Exception and are intended to be an "in your face" type of exceptions. A checked exception indicates an expected problem that can occur during normal system operation, like problems with parameters. Unchecked exceptions are exceptions that do not need to be declared in a throws clause. They extend RuntimeException. An unchecked exception indicates an unexpected problem that is probably due to a bug in the code. The most common example is a NullPointerException. Errors are serious problems that are almost certainly not recoverable. Some examples are OutOfMemoryError, LinkageError, and StackOverflowError.

Guidelines to consider

There are some guidelines on how to handle exceptions. They've been told again and again in books, conferences, blogs and whatsoever, but as they are probably ignored by the developers it's not a bad idea to list them again:

  • Throw exceptions early in your methods, so the stack trace is easy to follow
  • Catch exceptions as late as possible, where your program can either meaningfully recover from the exception and continue, or provide the user with specific information.
  • Every error must be reported on screen, to notify the user so it expects misbehaviour of the code. Logs are good to trace the source of the issue, but you won't have people looking at them constantly to detect errors.
  • Don't catch an exception you will throw again, let the method throw it
  • If you won't handle the error, let the application fail. Is better to have an application exception that ignoring there was an error and what caused it.
  • Use a logging system! Output to System.out is slow and unreliable, and is lost eventually.
  • Only log the exception when you handle it. The exception message contains the stack trace so there's no need to log it on each method that receives the error.
  • Add useful information on your log, like values of parameters, any relevant environment variable and so.
  • Don't pack exceptions in a superclass, as it hides information about the real cause of the error. Throwing Exception from a method should be forbidden!

A note about logging systems: If you are using commons-logging or Log4j, the error, warn, info, and debug methods are overloaded with one version that takes only a message parameter, and one that also takes a Throwable as the second parameter. Make sure that if you are trying to log the fact that an exception was thrown, you pass both a message and the exception. If you call the version that accepts a single parameter, and pass it the exception, it hides the stack trace of the exception.

What you must NOT do

The following code hides what happened, so you will never know why your application is misbehaving:

  try{

//code

}catch(Exception e){

}

Next fragment writes on err output, a channel that you will (probably) not check in production and no one will notice the error so it will be ignored while your application crumbles.

  try{

//code

}catch(Exception e){

System.err.println(e);

}

Next code contains a not so uncommon error, adding the error messages into DEBUG level of logging. This is the same issue as the previous cases: when deploying the application you will never know there was an error, so it's useless. Because you don't deploy applications with DEBUG

logging enabled, do you?

  try{

//code

}catch(Exception e){

log.debug("Error!"+e.getMessage());

}

Although the following code is better as we log the issue, we are not notifying the user of the application there's been an error so it will go unnoticed and, even worse, that user won't know why the application starts to behave erratically (and will have "happy" thoughts on ourselves and relatives). We could also add some extra information to the message, like possible sources of the error, to save us time not having to trace all the code.

  try{

//code

}catch(Exception e){

log.error(e.getMessage());

}

This code below uses Exception, a parent class, to throw the error. This hides the real source of the failure making impossible to know what happened and trying to fix it if it's possible.

public void foo() throws Exception {

This use of catch is wrong because it hides the origin of the exception, misleading both developer and user about what happened.

  try{

//code

}catch (NoSuchMethodException e) {

throw new MyServiceException("Blah: " +

e.getMessage());

}

The following fragment is usually wrong (although there may be exceptions), as you are exchanging an exception for an "error value". Is better to ignore that exception so the caller catches it. Also, this code contains e.printStackTrace, a method that its only useful (and not always!) on development if you check the console often. Should be replaced by a log annotation.

  try{

//code

}catch (NoSuchMethodException e) {

e.printStackTrace();

return null;

}

I've never used e.getCause, but it seems some people do, creating code like the fragment below. This is dangerous (and wrong) as the exception hierarchy or the method's throw clauses may change and your code would become useless, but no one will notify you about that.

  try{

//code

}catch (MyException e) {

if (e.getCause() instanceof FooException) {

//code

}

And last a warning: the following code seems correct but it's wrong. The reason is that in a concurrent application (web or even Swing applications as you have all those Swing threads running) both messages can end up far away form each other if other messages are sent between them. Always create one unique log message for each log entry you do to avoid those issues.

 LOG.debug("Using cache policy A");
LOG.debug("Using retry policy B");

One way to do it

It's hard to define a pattern for exception handling. There may be situations where you should log an re-throw an exception for a very good reason (although that's not a common case), and times when you can copy-paste the try-catch block (dont!) because it's repetitive. So more than looking for a pattern just try to avoid the "do not" situations listed above. If you want an example of good exception handling you may look at this code where we are processing a file. The code checks all possible exceptions and acts accordingly:

File prefsFile = new File(prefsFilename);

try

{

readPreferences(prefsFile);

}

catch (FileNotFoundException e)

{

// alert the user that the specified file

// does not exist

}

catch (EOFException e)

{

// alert the user that the end of the file

// was reached

}

catch (ObjectStreamException e)

{

// alert the user that the file is corrupted

}

catch (IOException e)

{

// alert the user that some other I/O

// error occurred

}

Sources

All merits on this post belong to them:

Loading mentions Retweet

Comments (0)

Feb 16 / 7:24am

Google Collections

Google Collections is a library that extends the capabilities of Java Collections. The library consists of:

  • New Collection types: Multimap, Multiset, BiMap and others
  • High-performance immutable implementations of the standard collection types, for example ImmutableSet
  • MapMaker, a builder for concurrent hash maps with many advanced features
  • Ordering, which can only be described as a "Comparator on steroids"
  • Iterators and Iterables utility classes: element-based equality, cycle, concat, partition, filter with predicate, transform with function, and much more
  • Lists, Sets and Maps utility classes: a plethora of convenient factory methods and much more
  • Forwarding collections, such as ForwardingSet, allowing you to customize collection behaviour without subclassing

The API is not frozen until 1.0 is released, so changes are common, but the library is safe to use as it's being actively tested on applications like Gmail or Adwords, which take advantage of the new collections. They are a nice alternative to Apache Collections, Java 1.5 compliant and with a focus on scalability and performance (as they are used on Google's massive applications!), so adding them to your code can only be beneficial. Check the Javadoc or a presentation they did on 2008 about the project for more details.

Loading mentions Retweet

Comments (0)