Java EE 7: The Big Picture

This is my personal summary of the book “Java EE 7: The Big Picture – Master the code, Applications, and Frameworks of Java Platform, Enterprise Edition 7” from Dr. Danny Coward.

Chapter 1: The Big Picture

Java EE Architecture

JavaEEPlatformArchitecture

  • Java EE container (‘Java EE’)
    • Runtime environment provided by the Java EE application server.
    • All the Java EE code runs in this environment.
    • Can mediate or intercept calls to and from the application code, and insert other kinds of logic that qualify and modify the calls to and from the application.
      Example: The security service that the Java EE container provides: the Java EE container can enforce security rules on the application that is running.
    • Supports a wide variety of protocols that clients may use to interact with a running Java EE application. Example: HTTP, WebSockets, RMI
    • Contains a variety of services that a Java EE application may choose to use:
      • Security: restrict access to its functions to only a certain set of known users.
      • Dependency Injection (DI): delegate the lifecycle management and discovery of some of its core components.
      • Transaction: define collections of methods that modify application data in such a way that either all the methods must complete successfully, or the whole set of method executions is rolled back as though nothing has ever happened.
      • Java Message Service (JMS): reliably send messages to other servers in the deployment environment of the Java EE application server.
      • Persistence service: enable application data in the form of a Java object to be synchronized with its equivalent form in the tables of a relational database.
      • JavaMail service: send email. Useful in the kind of application that take some action initiated by and on behalf of a user, and which needs to notify the user at some later time of the outcome of the action.
      • Java EE Connector Architecture (JCA): framework into which a new service that is not a standard part of the Java EE plaform may be added and that can then be utilized by a Java application running in the plaform.
      • Java Database Connectivity (JDBC) API: supports traditional storage and retrieval of Java EE application data in a relational database using the SQL query language.
  • Web container
    • Runs the web components: web pages, Java servlets, and other web components that can interact with clients connecting to the Java EE application with standard web protocols.
  • Enterprise JavaBeans (EJB) container 
    • Runs the application logic
    • EJB are Java classes that contain and manipulate the core data structures
  • Database tier
    • Holds all application data that the Java EE application needs to exists longer than the scope of a single session of the application, or simply between different steps in the application that are separated in time.

Hello World Application

helloWorldApplication

Structure of the Java EE application

  • DisplayServlet is responsible for :
    • rendering the web page seen from the browser
    • creating the HTML elements that make up the web page
    • displaying the message that the Java EE application is holding
  • WriteServlet is responsible for:
    • processing the message that is input to the application
    • passing the hello-message and formulates a Java object from the Message class that is part of the application
    • passing the message to an Enterprise Bean component, called ModelEJB.
  • ModelEJB is responsible for:
    • processing the message and formulates a Java object from the Message class.
    • storing the message object in the database using the Java Persistance API (JPA).
    • retrieve the message in DB on behalf of the DisplayServlet, when the servlet needs to create the web page to display.

Roles

  • Browser client: render the HTML content that the Java EE application creates for it, and send a message typed in by the user.
  • Web components (DisplayServlet and WriteServlet): create the HTML content for the browser and to direct the incoming user message to the correct portion of the application that can handle the message processing logic (ModelEJB).
  • ModelEJB: process, store and retrieve the user message to the database.

WriteServlet code

The browser formulates an HTTP POST request and sends it to the Java EE server, to a URL that will look like http://localhost:8080/HelloJavaEE-war/WriteServlet. As you shall see, the WriteServlet is mapped to the WriteServlet, and because of this fact, the Java EE server routes the HTTP POST request to the WriteServlet. Remark: this web component intercepts HTTP POST requests, because it has a doPost() method. WriteServlet is a HttpServlet.

@WebServlet(name = "WriteServlet", urlPatterns = {"/WriteServlet"})
public class WriteServlet extends HttpServlet {
  @EJB
  private ModelEJB ModelEJB;
  private static String PUT_MESSAGE = "put_message";

  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String message = request.getParameter(PUT_MESSAGE);
    if ("".equals(message)) {
      ModelEJB.deleteMessage();
    } else {
      try {
        ModelEJB.putUserMessage(message);
      } catch (MessageException nme) {
        throw new ServletException(nme);
      }
    }
    response.sendRedirect("./DisplayServlet");
} }

Notice that there is no constructor. In fact, the Java EE containers manage the lifecycle of components. In particular, the web container manages the lifecycle of Java servlet components, so the developer can focus on the application logic instead.

ModelEJB code

The ModelEJB is an Enterprise Bean, which is mostly a Plain Old Java Object (POJO).

@Stateful
public class ModelEJB {
  @PersistenceUnit
  private EntityManagerFactory emf;
    
  public void putUserMessage(String messageString) throws MessageException {
    this.deleteMessage();
    try {
      String decodedMessage = URLDecoder.decode(messageString, "UTF-8");
      Message message = new Message("1", "(" + messageString + ")" + " in a database");
      EntityManager em = emf.createEntityManager();
      em.persist(message);
    } catch (UnsupportedEncodingException uee ) {
      throw new MessageException("something odd about that message..." + messageString);
    }
  }

  public String getStoredMessage() throws MessageException {
    EntityManager em = emf.createEntityManager();
    List messages = em.createNamedQuery("findMessages").getResultList();
    if (messages.size() > 0) {
      Message message = (Message) messages.get(0);
      return "(" + message.getMessageString() + "), inside an EJB";
    } else {
      throw new MessageException("There was nothing in the database.");
    }
  }

  public void deleteMessage() {
    EntityManager em = emf.createEntityManager();
    em.createNamedQuery("deleteMessages").executeUpdate();
} }

What makes this Java class an Enterprise Bean is the annotation @Stateful. This means that the Enterprise Bean container will create one instance of the bean for each client that talks to it.

Message class code

Looks like a normal class but has been annotated with @Entity. Because of that it can be persisted and managed within a database.

@Entity
@Table(name = "MESSAGE")
@NamedQueries({
  @NamedQuery(
    name="findMessages",
    query="select m from Message m"),
  @NamedQuery(
    name="deleteMessages",
    query="delete from Message"
  )
})
public class Message implements Serializable {
  @Id
  @Column(name = "ID")
  private String id;

  @Column(name = "MESSAGE")
  private String messageString;
  public Message() {
  }

  public Message(String id, String messageString) {
    this.id = id;
    this.messageString = messageString;
  }

  ... //getters and setters
}

DisplayServlet code

This servlet queries the ModelEJB for the stored message and create the HTML that forms the web page that is shown to the user. It has a doGet() method so that it will intercept any HTTP GET requests.

@WebServlet(name = "DisplayServlet", urlPatterns = {"/DisplayServlet"})
public class DisplayServlet extends HttpServlet {
  @EJB
  private ModelEJB modelEJB;

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
      out.println("<html>");
      out.println("<head>");
      out.println("<title>Hello Java EE</title>");
      out.println("</head>");
      out.println("<body>");
      out.println("Enter a message for Java EE which will pass through the web tier, the EJB tier to the database, and back again !");
      out.println("<form action='./WriteServlet' method='POST'>");
      out.println("<input type='submit' value='Enter'>");
      out.println("<input type='text' name='put_message'> ");
      out.println("</form>");
      String displayMessage;
      try {
        String storedMessage = modelEJB.getStoredMessage();
        displayMessage = "Hello from (" + storedMessage + "), inside a web component";
      } catch (MessageException nme) {
        displayMessage = "you should enter a value...";
      }
      out.println("The current message from Java EE: <br><b>" + displayMessage + "</b>");
      out.println("</body>");
      out.println("</html>");
    } finally {
      out.close();
} } }

The Many Variations of Java EE Applications

Many Flavors of Web Interface

  • Original purpose: replace CGI programming and kind of all-purpose server-side component model for handling any request/response style network protocol, not just HTTP.
  • Inconvenience: as seen, embedding HTML inside Java code is too cumbersome approach. But Java EE offers a superior web component model to generate dynamic web content for browsers of all kinds: JavaServer Pages (JSP) and JavaServer Faces (JSF). Both are based on Java servlets.
  • Java EE platform contains a variety of web components that can handle and respond to incoming web service calls. Known as Java Web Service components, these components are to both Simple Object Access Protocol (SOAP) and to Representational State Transfer (REST) web services what Java servlets, JSPs, and JSF are to HTML content.
  • WebSockets are web components that give a server component the ability to send data out to interested clients.

Many Kinds of Application Logic

  • Statefull session beans
    • are instantied by the EJB container each time a new client wishes to uses it.
    • hold its application state for each of its connected clients.
    • E.g.: shopping cart
  • Stateless session beans
    • are brought into existence  each time they are called.
    • perform very well in large-scale systems, beause these beans are instantiated only when needed and can easily be instantiated on a node in a cluster.
  • Singleton session beans
    • are ideal for representing an application state that is common to all connected clients of the application
    • are instantiated only once in the Java EE application
    • E.g.: modeling a news feed viewable by all logged-in users, or a high score table.
  • Message-driven beans
    • offer a programming model wherein instead of making method invocations, tasks are initiated by sending a message, with task completion occuring asynchronously with the sending of another message.
    • Well suited for long-running activities, such as backing up large amounts of data, handling a complicated purchase order.

Different Ways to Store Application Data

  • JPA (Java Persistence API) offers a high-level framework with which applications perform object-relational mapping: data objects you want to model can easily be translated into equivalent data tables in a relational database, which can be a shortcut to designing relational schemas and the various queries needed to store and retrieve the data.
  • JDBC (Java Database Connectivity) API models connections to the relational database and the execution of SQL statements to store, manage, and retrieve that data.
  • Java Transaction API allows multiple activities to be grouped into a single atomic action that either succeeds, meaning each member of the atomic action succeeds, or fails, in which case the individual activities that completed before the failure are reversed, in which case the overall effect is as though nothing had happened.

Interfacing with Other Systems

  • Java web services APIs
    • not a framework of reliable messaging
    • allows for loosely coupled interactions, where systems evolve and add functionality separately from their peers without disrupting a working system.
    • E.g.: analytics servers, purchasing systems, order management servers
  • Java Message Service
    • provides reliable asynchronous message mechanism
    • E.g.: financial purchase transaction, ordering a part number, or requesting a delivery scheme in order to complete its work.
  • Java EE Connector Architecture
    • is a all-purpose extensibility mechanism
    • enables a class of Java EE applications that uses it to rely on arbitrary external information systems.

Packing and Deploying the Hello Java EE Application

The Hello Java EE application consists of web components and an Enterprise Bean and data code.

Web ARchive file (WAR)

  • is the vehicle for deploying the web components in a Java EE application
  • is a kind of ZIP file, with a predefined structure consisting of a
    • root directory to hold any textual web pages such as HTML pages, JSP, or JSF files.
    • /WEB-INF directory under which any Java class files they need, such as Java servlets, are held, in addition to other configuration information.
/META-INF
   /MANIFEST.MF
/WEB-INF
   /classes
      /javaeems
         /web
            /DisplayServlet.class
            /WriteServlet.class

Enterprise Bean JAR

  • packages the Enterprise Bean code in a archive
  • uses the /META-INF directory to store configuration information about the Enterprise Beans it contains, together with the class files that the beans use at the root level of the archive.
  • held the persistence.xml in the META-INF directory to ensure that ModelEJB can access the database through the Java Persistence layer.
/META-INF
   /MANIFEST.MF
   /persistence.xml
/javaeems
   /model
      /ModelEJB.class
      /Message.class
      /MessageException.class

Enterprise ARchive (EAR)

  • allows a Java EE application to be packed into one single, self-contained file.
  • /META-INF held the configuration information
/META-INF
   /MANIFEST.MF
/HelloJavaEE-jar.jar
/HelloJavaEE-war.war

Screen Shot 2016-06-18 at 21.48.18.pngOnce a Java EE application has been package into this form, it can be deployed to any Java EE server.

 

Advertisements
Java EE 7: The Big Picture