Showing posts with label JAVA EE. Show all posts
Showing posts with label JAVA EE. Show all posts

Sunday, February 14, 2016

EJB Good Practices

EJBs abstract your middleware or business logic layer. They are transactional in nature so when you hit your persistence layer (mostly through JPA), the transaction is already there for your database session. As a result, all DB operations are going to complete or none of them, i.e. EJB operation is atomic. Let's cover some of the good practices:

Don't create EJB methods for CRUD operations

Imagine creating operations in your EJB for creating, fetching, updating or deleting your entity. It's not going to serve the purpose; quite clearly, CRUD operations are not your business logic!

In fact, CRUD operations will be part of your more sophisticated business operations. Let's take that you want to transfer x amount from a bank account A to another account B. There should be just a single method which reads appropriate records from DB, modifies them and performs the update.

Also, creating a CRUD operation gives the impression that EJB is created for each entity. We should create EJB for a group of related problems like manage accounts, policy manager etc. You can abstract your CRUD operations in Data Access Layer though!

Minimise Injecting EJBs in the Presentation layer

Imagine yourself working in the presentation layer (Servlets, web services, ..) and having to deal with multiple EJBs to delegate the call. You are going to struggle to find appropriate EJB and then a method for delegating the incoming calls.  Especially when someone else is taking care of business layer!

This is going to defeat the separation of concern principle which is important to manage your complex distributed system. So what's the solution to deal with this - Bundle related EJBs in a single (super) EJB and inject this super EJB. 

But make sure that, in doing so, you are not putting un-related EJBs together just for the sake of minimizing the number of EJBs.  Each EJB (including super) should adhere to the single responsibility principle

Reusing EJB methods

Suppose you have quite complex use cases which resulted in a big EJB class definition. So, the obvious question would be, how do you achieve reusability with EJB methods?

Just like a normal Java class, you can create helper EJBs with reusable methods. Multiple EJBs can use the services provided by this helper EJB. And to make these helper utilities more clear, you can put this in a utility or helper package inside your main EJB package. 


References

---
would love to hear your suggestions/feedback about this post.

Wednesday, December 30, 2015

Entity States

Java applications contain a mix of transient and persistent objects. Transient (or normal objects) has a limited lifetime and is bounded by life of the process that instantiated it.  But persistent objects (or Entity) can be stored on disk or file system to create again in the future. 

The Java Persistence API (JPA) is part of EJB 3.0 specification (EJB 3.0 itself is part of Java Enterprise Edition). JPA refers to persisted or persistable  classes as Entity.  Technically, it's  just a POJO class which maps to a database table/view. Instance of an entity can represent a single row of a table. This post will cover different states an instance of an Entity could be in. In context of JPA, object and entity refers to the same thing (more details here)

Entity States 

  1. New/Transient Object which got instantiated using new operator is in transient state as it's not yet associated with any persistence context. It's not mapped yet to a record/row in database. It's just another object; and in fact JPA specification doesn't give any name for this state. 
  2. Managed/Persistent Object has a database identity. This means the instance has a valid primary key value to uniquely identity it in the database (or more specifically in a table). These instances are associated with a persistence context. 
  3. Detached As long as persistence context is active entity is in managed state. Once transaction (or unit of work) completes, persistence context is closed but the application still has handle to the entity. So such entities are in detached state. 
  4. Removed During the transaction we can delete or remove an entity. It's still associated with persistence context but it get's scheduled for deletion (at the end of transaction). So a removed object shouldn'd be reused and any reference holding it should be discarded. 
Image Reference : http://openjpa.apache.org

Let's Code

Let's code to explain the above states:

New

Student student = new EngineeringStudent();
student.setName(..);
student.setGrade(..);
student.setXX(..);

Managed

entityManager.persist(student);    //JPA
session.save(student);                  //Hibernate 

Delete
session.delete(student);
entityManager.remove(student);

Detached
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

Student student = fetchStudentWithIdFromDb(id);
student.setGrade(..);
tx.commit();
session.close();

student.setXX(..);   //student is detached here

Detaching Inside a transaction
session.evict(student);  //detaches one object
session.clear(); //detaches all objects

Sunday, July 26, 2015

Why EJB (3+)

I have heard people mentioning, why do you need EJBs; my project is great without them. In early days, I too wasn't very convinced. What value it adds ? Can't we leave without EJBs ?

The answer to most of such questions would be; may be!

It's not that you can't implement a distributed application without EJBs. I have worked on couple of quite successful distributed applications which didn't use EJB at all. For that matter, there is no framework/technology which is must in a given situation. There are always few alternatives, but the question is what's the cost or advantages for making a particular choice?

Let's try to understand EJB and other server side Java components:

Where it fits

EJBs runs inside EJB container (of application server) for abstracting your business logic. Below diagram shows different server side components and their relationship with EJB (just shown some of them). When EJB is not there the line gets blurred and the business logic is spread across servlet and other middle layer components like JPA, JDBC, JMS etc.





Why do we need it ?

Business logic shouldn't be performed by web interface component and similarly by persistence layer as well. Web-interface should specialize in handling http request and delegating it appropriately to business component and persistence layer should focus on CRUD operations.  If your business logic is spread across multiple component, it's not easy to manage it. You are violating loose coupling and separation of concern design principles (not following MVC architectural pattern).

If your business logic is light-weight then you might go on with this approach. But are you sure, that it's going to remain light weight forever? Change is inevitable!

When you have a truly distributed application with multiple server side components and business logic is not so trivial, you will feel the need to bring in an specialized component sooner or later. EJB integrates quite easily with other server side components like JPA (for persistence services), JTA (for transaction services), JMS (for providing messaging services), JNDI (for providing directory services) etc. EJB helps scaling out your application.


Arguments given here are generic, but have written this article keeping in mind features and power of EJB 3+.  Development with EJB 3+ is quite simple - no complex configuration in XML, simple POJO class, uses annotation, and makes development quite a breeze. 

---
happy learning !

Monday, July 20, 2015

What is Java EE container

For Java SE (or J2SE) applications JVM provides runtime environment, but the moment you switch to Java EE (or earlier known J2EE), runtime environment is provided by web or application servers.

JVM executes/runs Java applications and also provides some of the runtime services like lifecycle management for objects and API support etc. Life is not so rosy in the distributed environment and that's why we have servers for specific jobs. These servers basically fall into two categories, application servers like JBoss(Wildfly) and Glassfish and web servers like Tomcat and Jetty. These servers are also referred to as containers (in a more technical sense). So what are containers?

Java EE Container

Java EE containers are runtime environments for Java Enterprise Edition applications. As containers are implemented on top of JVM, they provide all services provided by JVM (to Java SE applications) and along with that they also provide services specific to the distributed environment. Java EE containers refer to two different types of containers known as Web/Servlet container and EJB container. They are classified in terms of what technologies they support. Let's go through both these containers in more detail:

Web Container:
Web containers run web applications which use Servlet, JSP and JSF pages and respond to HTTP calls from HTTP clients like browsers, mobile devices or other Java (SE or EE) applications. It can also host RESTful and SOAP web services. Now a subset of EJB 3.1 (added in Java EE 6), known as EJB lite can also be deployed in web containers (in fact EJB lite can also run on JVM). So, it intercepts HTTP(S) request from the client and then identifies, instantiates, initializes appropriate servlet/service endpoint; and then returns back the appropriate HTML page or response in JSON/XML/Text format. 

EJB Container:
EJB containers run enterprise applications made up of Enterprise Java Beans within the Application server. It abstracts business logic of your Java EE application and usually takes request from Servlets,  web services,  queue or other application servers. And just like servlet containers, EJB containers manages lifecycle of EJBs and provides services like transaction management, security, concurrency, naming services or ability to be invoked asynchronously.

Please note that Java EE compliant application servers support Servlet containers along with EJB containers; you can run full stack Java Enterprise Edition application. I have come across situations where people (loosely) refer to Applications servers as EJB containers. 
In the application server, web container and EJB container both share the same JVM instance. 

---

happy learning !!!

Monday, June 8, 2015

Brief overview of JPA

JPA(Java Persistence API) came into the picture to bring object-oriented and relational model together. It's basically an abstraction on top of JDBC (and is part of EJB 3.0 specification); to let you deal with tables without using SQL. Before this, the persistence model of Java was called as Entity Bean and was part of Enterprise Java Beans specification. Entity Bean wasn't lightweight, and hence got replaced by this new (new age) API.

Relational databases store data in tables in form of rows and columns. So dealing with tables directly was not very convenient in Java where objects rule. JDBC bridged the gap a bit but wasn't able to remove SQL altogether. JPA consists of two broad components to solve the full problem - first is the mapping of objects to tables and second is providing the ability to query. Let's cover them briefly:

Mapping (ORM): JPA maps Java objects to relational database tables. Mapping is achieved through ORM metadata. The metadata describes the mapping between table and objects (and attributes and columns). It was initially achieved by a descriptor XML file, but it got further simplified and now annotations are preferred approach (Use of annotations brought convention over configuration technique). So, just put annotations at Class, field/method level and boy you are done with mapping.

A common confusion is that hand-coded SQL queries are going to be as fast as one automated by ORM tool or maybe even better. So is it recommended to use ORM tools?

Yeah, it's safe to assume that hand-coded SQL/JDBC can be easily analyzed and optimized. But, ORM tools like Hibernate gives much more optimizations like automated queries and caching out of the box. It hides a lot many details and allows the programmers to focus on core business problems. Also, these tools abstract your underlying database as well. 

Querying: Mapping will not make much sense if we still have to write SQL queries so JPA tweaked SQL to come up with its own query language, JPQL(Java Persistence Query Language). JPQL queries entity objects.  JPQL doesn't understand underlying row/columns and tables, it queries objects so uses familiar notation i.e. dot (.). 

Evolution of JPA

JPA 1.0 (May 2006, EJB 3.0) brought the object-oriented and relational model together. It was bundled as part of J2EE 1.3 and then later J2EE 1.4 as well.

JPA 2.0 (Dec 2009, Java EE 6) It extended JPQL, added second-level cache, pessimistic locking (criterial API)

JPA 2.1(Apr 2013, Java EE 7) supports schema generation (persistance.xml), converters, CDI, stored procedures, bulk update and delete queries, enhanced criteria API (update and delete)
more here - http://www.thoughts-on-java.org/jpa-21-overview/

* From version 5, J2EE is known as Java EE, and similarly J2SE is know as Java SE.


Entity

Objects which get persisted through JPA provider(like hibernate) is referred to as Entity. Entities live shortly in memory and persistently in a database. So you basically perform all operations on Entity which are POJO and it typically represents a row of a table. Entity class should satisfy below conditions:
  • Entity class must be annotated with @javax.persistance.Entity
  • The class must have public or protected no arg constructor (it can have other constructors as well)
  • The class must not be declared as final. No method or persistent instance variable must be declared as final
  • The class must not be enum or interface 
  • If the instance has to be passed by value as the detached object, the entity class must implement Serializable interface
@Entity
public class Employee{..}

@Entity annotation converts the Employee class into an entity (in above snippet).  Also going by convention over configuration rule, the table name is same as class name (i.e. Employee).


JPA Frameworks/Implementation

  • Hibernate open source implementation, supports JPA from version 3.2, influenced JPA specification
  • TopLink commercial implementation
  • Java Data Objects (JDO)
  • EclipseLink also supports object XML mapping. Reference implementation of JPA. 

Note: Persistence provider or provider refers to JPA implementation. 

Saturday, May 16, 2015

Websocket in Java

Covered the fundamentals of web sockets (vs HTTP) in the previous post, here

WebSocket protocol is part of HTML5 specification to provide full-duplex bi-directional communication channel over single TCP socket. It got added in Java EE version 7 (JRS 356). In this post, I will dig dipper into WebSockets and how can we implement it in Java. 


WebSocket uses HTTP connection to bootstrap itself. HTTP sends a normal request to initiate WebSocket connection but it has upgrade header (wiki link). Through this upgrade header, clients say that it would like to upgrade current HTTP connection to a different protocol connection.  If sever has support for it websocket connection gets established. Once the connection is established, both ends can transfer data.


Life Cycle of WebSockets

  1. The client sends an HTTP request to the server with an upgrade header having value websocket.
  2. If Server supports WebSockets then it responds with HTTP header having status code 101, which means now onwards the connection is upgraded to WebSockets (no more HTTP).
  3. Now both client and server can send any number of messages to each other.  Server needs to obtain the session object to send message to client. 
Image Source

Client Request
GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
Origin: http://example.com

Server Response
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat

Implementation

Specification JRS 356, covers standards for Java client side as well as server-side WebSocket implementation. This is part of Java EE 7, so all Java EE 7 compliant application servers should provide WebSockets support. There are also independent libraries/jars which can be used to support this feature on non EE 7 compliant servers. 

Any POJO class can be turned into a WebSocket server endpoint by annotating it properly. As shown in below diagram, the class needs to be annotated with @ServerEndPoint and specify URL as the value. You just need to provide implementations of the callback methods which will be called appropriately during the lifespan of the connection. Your server will ensure that these methods get invoked appropriately.




Just like a server endpoint, client endpoint can also be created in Java by annotating the class with @ClientEndPoint and by providing implementations of lifecycle methods. WebSocket client endpoint initiates the connection and WebSocket server endpoints await for the request and establish it. Once the connection is established the request data will be received in the onMessage callback method. So this is the place where business logic will be put. Both client and server can keep sending the data to the other party unless the connection is closed.

Over the internet, clients will mostly be a browser, so make sure that your browser supports this. Both endpoints (client and server) have callback listeners- onOpen, onMessage, onError, onClose.

Please refer to this link which describes steps to create WebSocket in Java.

I have also hosted a hello world WebSocket application on GitHub (websockets).

Security

This is a new technology and hence concern for security is legitimate. Here is a nice article which covers some of the important aspects. 

Final Note

  1. WebSocket protocol is supported in major browsers- Chrome, IE, Firefox, Safari. It also requires support from the server web app. Check for its support on your Android/iOS version if you want to use it for the mobile client. 
  2. It opens connections on TCP port 80. 
  3. WebSockets transmissions are described as messages, where a single message can be optionally split across several data frames. 
  4. Good to validate Origin header before establishing connection on server side to avoid any security threat. 
  5. WebSocket protocol defines a ws:// and wss:// prefix to indicate a WebSocket and a secure WebSocket connection, respectively. 
  6. WebSocket is stateful (unlike http which is stateless), so it doesn't scale up nicely. 
  7. One of the issue with WebSockets is that, what if proxy times out connection after some inactivity? Client and server should re-handshake to ensure that connections gets established again. 
  8. Another legitimate question is, what if either of proxy or browser doesn't support it. You can use portable frameworks like Atmosphere. It transparently falls back to HTTP in such case. 

References:

---
keep coding !

Saturday, February 28, 2015

Understanding JAVA EE Interceptors

Interceptors are used to implement orthogonal or cross-cutting concerns such as logging, auditing, profiling etc in Java EE applications. In this aspect, it is similar to aspect-oriented programming (AOP).

In Java EE 5, Interceptors were part of EBJs, but in later versions, Interceptors have evolved into a new specification of its own. Interceptors were split into an individual spec in Java EE 7 (Interceptors 1.2) and are part of Context and Dependency Injection(CDI) specification.  They can be applied to any managed classes/beans like EJBs, Servlets, SOAP and RESTful web services. Managed Beans are container-managed objects (unlike Java Beans or POJOs which run inside JVM).  In Java EE 7, Dependency Injection (JSR 330) and  CDI (JSR 299) are merged. You can refer to managed beans as CDI bean as well. These managed beans are injectable and interceptable.

In this post, I will be using terms CDI bean and managed bean interchangeably.

Interceptors

Interceptor is a class whose methods are invoked when methods on a target class are invoked. And this invocation of interceptors methods is performed by the container. Obviously, this would be possible if the target class and the interceptors both are managed by the container.  This is possible because beans managed by containers (servlet or EJB) provides the ability to intercept method invocation through interceptors. 


Interceptors are powerful means to decouple technical concerns from business logic. And it uses strongly typed annotations to achieve it instead of String-based identifiers. This way usage of XML descriptors is minimized. Interceptors use a mandatory deployment descriptor, bean.xml. This is required so that CDI is able to discover the bean from the classpath.

Below are interceptor metadata annotations (from javax.interceptor ):
  • @AroundConstruct associates with the constructor of the target class
  • @AroundInvoke associates with a business method and gets called while entering and exiting
  • @AroundTimeout associates with timeout methods
  • @PostConstruct & @PreDestroy on corresponding lifecycle events of the target class

Using Interceptors

Interceptors, intercept a particular target class so they have the same life cycle as that of the target class. Target class can have any number of associated interceptors.

Intercepting a REST Service

Interceptors can intercept any managed bean; so it can intercept servlet, REST entry point, EJB etc. I will be showing an example of intercepting a REST service.

import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.interceptor.InterceptorBinding;

/**
 * Interface for logging/auditing JAX-RS requests
 *
 */
@Inherited
@InterceptorBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface Auditor {
}



import javax.inject.Inject;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
/**
 * CDI/Managed bean which intecepts REST API
 * Add @Interceptors(RestAuditor.class) to the target class/method
 *
 */
@Interceptor
@Auditor
public class RestAuditor {
 @AroundInvoke
 public Object intercept(InvocationContext context) throws Exception {
  //context.getMethod().getName())
               // audit/log the request
  return context.proceed();
  //control comes back after target method execution 
 }
}


<beans xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="
      http://java.sun.com/xml/ns/javaee 
      http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
   <interceptors>
        <class>RestAuditor</class>  <!--fully qualified class name -->
    </interceptors>
</beans>

So interceptor definition and the declaration of the interceptor in bean.xml completes the interceptor part. Now next step is to use above defined interceptor on a REST service. Please note that the intercept method will be called before actually calling the REST method and then again once REST method is complete, the control comes back. So the request as well response both can be logged in the intercept(..) method. Using the interceptor is quite trivial, we just need to annotate the REST class as shown below :

@Path("/sample")
@ApplicationScoped
@Interceptors(RestAuditor.class)
public class SampleRestService implements Serializable {  
 @GET
 @Produces(MediaType.APPLICATION_JSON)
 public boolean getLogs() {
  boolean resp = true;
  return resp;
 }
}

That's it!

Important Points

  • If the application contains several jar files and you want to enable CDI across the application then you need to have beans.xml in each jar. Only then CDI will trigger bean discovery for each jar. 
  • Interceptors can be applied to method as well as class level. If you want to intercept a specific method then put the annotation at method level only (NOT at class level as shown above).