Showing posts with label Java EE(English). Show all posts
Showing posts with label Java EE(English). Show all posts

Maintaining state in Java Webservice(JAX-WS)

Maintaining state in Java Webservice(JAX-WS)


Introduction

This little article start point is the need of get the current session from a flash swf.
I try to explain: The web application has a login form and after the user is authenticated a session is created and mantained, so the need is to access to this value into the session from flash that calls a webservice in the same service.

recapitulate.

Server side: JSP, Servlet etc. for user login.
Server side: Webservice for reporting stuff.

Client side: html form for login
Client side: flash swf (created with flex) for reporting gui. it access the webservice to obtaining reporting data and draw it. when the webservice is called the session data created in login step is required.


The Webservice

The webservice is created like in the previouse article.
But in order to get the current session a MessageContext is required.
So declare it by the @Resouce annotation, and get the HttpSession from it!

@WebService()
public class testWS {

    @Resource
    private WebServiceContext context;
    /**
     * Web service operation
     */
    @WebMethod(operationName = "sayHello")
    public String sayHello(@WebParam(name = "name")
    String name)
    {
        String ret = "";
        MessageContext mc = context.getMessageContext();
        HttpSession session = ((HttpServletRequest) mc.get(MessageContext.SERVLET_REQUEST)).getSession(false);
        if (session == null)
        {ret =  "hello: NO SESSION";}
        else
        {
            Enumeration en = session.getAttributeNames();
            while (en.hasMoreElements())
            {
                String key = (String) en.nextElement();
                ret += key + " " + session.getAttribute(key) + "\r\n";
            }
        }
        return ret;

    }

}

That's all.
The client side you can see in the previous article


Conclusion

For a complete discussion about session mantaining

Request header too large Exception

Request header too large Exception
G.Morreale


In a production system, in calling a webservice I encounter this problem:

..WEB0777: Unblocking keep-alive exception
java.lang.IllegalStateException: PWC4662: Request header is too large
at org.apache.coyote.http11.InternalInputBuffer.fill(InternalInputBuffer.java:740)
at org.apache.coyote.http11.InternalInputBuffer.parseHeader(InternalInputBuffer.java:657)
at org.apache.coyote.http11.InternalInputBuffer.parseHeaders(InternalInputBuffer.java:543)
at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.parseRequest(DefaultProcessorTask.java:712)
at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.doProcess(DefaultProcessorTask.java:577)
at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.process(DefaultProcessorTask.java:831)
at com.sun.enterprise.web.connector.grizzly.DefaultReadTask.executeProcessorTask(DefaultReadTask.java:341)
at com.sun.enterprise.web.connector.grizzly.DefaultReadTask.doTask(DefaultReadTask.java:263)
at com.sun.enterprise.web.connector.grizzly.DefaultReadTask.doTask(DefaultReadTask.java:214)
at com.sun.enterprise.web.portunif.PortUnificationPipeline$PUTask.doTask(PortUnificationPipeline.java:380)
at com.sun.enterprise.web.connector.grizzly.TaskBase.run(TaskBase.java:265)
at com.sun.enterprise.web.connector.grizzly.ssl.SSLWorkerThread.run(SSLWorkerThread.java:106)
|#]

I solve it, by using maxPostSize property.

In order to setup this value open admin console, go to Configuration->Http Service->Http Listener and add the property
maxPostSize.

The default value is 4096, so increment it until the exception doesn't appear anymore.

Facebook Java Api(ENG)

Facebook Java Api Example
G.Morreale




Introduction:

This article explain the facebook java api through an example.
First you need a facebook account, and you have to enable "Developer" application.

Then you must configure you account and make a new application configuration in order to obtain 
"api key" and "secret key".
This can be accomplished by reading http://developers.facebook.com/get_started.php


The Server

You need a java web server (tomcat, glassfish, jboss etc.) available by the web.
Localhost server isn't ok to facebook integration purpose.

Facebook Java Api

If you want to interact with facebook platform a client library can be very useful.
Client library are available in different languages:http://wiki.developers.facebook.com/index.php/Client_Libraries

There isn't a officiale Java api but you can choose alternative unofficial ones:


I prefer the last one.
So go to http://code.google.com/p/facebook-java-api/ and download facebook-java-api-2.0.4.bin.zip (or later).
When you download it, extract the jar into a directory and get it available in you facebook example application classpath.

Facebook server make available user data, photos, groups infos etc by rest api:http://wiki.developers.facebook.com/index.php/API

The Facebook Client Project

Make a new Web project, and make a new empty servlet.
The servlet url-pattern configured in web.xml must be the same indicated in facebook application configuration.

The Source Code

public class index extends HttpServlet
{

    //facebook give it!
    String apiKey = "your api key";
    String secretKey = "your secret key";

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try
        {
            out.println("<h2>User information</h2>");

            //facebook login mechanism give you by http parameter the session key
            //needed for client api request.
            String sessionKey = request.getParameter(FacebookParam.SESSION_KEY.toString());

            //initialize a facebook xml client (you can choose different client version: xml, jaxb or json)
            //the init is done by apiKey, secretKey and session key previosly requested
            FacebookXmlRestClient client = new FacebookXmlRestClient(apiKey, secretKey, sessionKey);

            
            //This code line obtain the user logged id
            Long uid = client.users_getLoggedInUser();

            //print user info.
            out.println(printUserInfo(uid, client, sessionKey));
}



 

private String printUserInfo(Long uid, FacebookXmlRestClient client, String sessionKey) throws FacebookException
    {
        StringBuffer ret = new StringBuffer();
        //init array parameter
        ArrayList<Long> uids = new ArrayList<Long>(1);
        uids.add(uid);
        //init field parameter - we choose all profile infos.
        List<ProfileField> fields = Arrays.asList(ProfileField.values());
        //init the client in order to make the xml request
        client = new FacebookXmlRestClient(apiKey, secretKey, sessionKey);
        //get the xml document containing the infos
        Document userInfoDoc = client.users_getInfo(uids, fields);
        //for each info append it to returned string buffer
        for (ProfileField pfield : fields)
        {
            ret.append(pfield.fieldName()).append(" <b>").append(userInfoDoc.getElementsByTagName(pfield.fieldName()).            item(0).getTextContent()).append("</b>");
            ret.append("</br>");
        }
        return ret.toString();
    }

Conclusion 
In this simple manner you can print all logged facebook user info into facebook application. In order to make a cleary client authentication by using java servlet filter you can read this:
http://www.theliveweb.net/blog/2007/10/31/facebook-authentication-using-java/ 

TrovaTv Samsung and facebook



 

MDB(Message Driven Bean)(ENG)

MDB - Introduction on Message Driven Bean through an Example
G.Morreale

clicca qui per la versione italiana
Introduction:

MDB (Message Driven Bean) is a special type of bean that can perform certain acts in relation to the receipt of a JMS message.
It therefore does not respond to requests for a client but does the connection with "receiving a message."

Receiving a second domain chosen either on a topic or a tail.

The MDB is nothing but a JMS client operating currently received on a queue.

The Example

Suppose you want to create a MDB can process the web requests arriving on a given url(a servlet).
The MDB collect data on the object HttpServletRequest in order to keep a log file.

So any access to the MDB opens the file, and writes in the information: IP address of the client, user-agent, etc timestamp of the request.

But why have carried out such operations all'MDB? The JMS asynchronous system does not block the execution of the servlet pending operations (opening, writing files etc.) Log (useless to the user).

Initialize projects

In order to implement the project to create an application form with EAR WEB and EJB module.
The WEB module include the producer of messages EJB put the consumer: the MDB.

Elements from the example

As in any application will JMS 3 key elements:

  • provider of messages
  • client that produces messages
  • client that consumes messages

Comments about our 3 element list

  • provider messages - Queue to create the server resources in a position to collect the messages produced.
  • client that produces messages - Servlet (or rather a filter) that sends the message
  • client that consumes messages - MDB that processes the message by storing some data on file.

Configuring the JMS Provider 

I state that the provider, or rather its configuration, idepend on application servers used in this case it is used Glassfish V2.

Open the administration panel. For example, on localhost: 4848.
On Resources -> JMS Resources -> Connection Factories
You can create a new connection factory:


insert the JNDI name, or the value that allows you to find resource in the container, set as a kind of resource QueueConnectionFactory because we want to use in a specific queue and leave all other options.

note:
Glassfish creates a pool of connections to the queue so as to maximize the reuse of open connections to the factory in the same way that optimizes for example jdbc to a db.

Likewise, you can create a Destination:

Choosing as usual the JNDI name, the name of the physical destination and type of destination that, in this case is a queue.

Client that produces messages

The message will be produced in relation to access to a given url, we will use

http://localhost/mdb/test

So we must create and test a servlet filter to test the servlet, in the web of course (war).

note:
The filters intercept request so permits to edit request and the response of a given url pattern to forward the servlet or jsp or call or one or more other filters. They provide the ability to create units of code across multiple riusabile url (servlet or jsp) and create real chains filters (structuring development in a kind of plugins)

About the servlet build a trivial hello world servlet:

package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author PeppeM
 */
public class test2 extends HttpServlet {
   
    /** 
    * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
    * @param request servlet request
    * @param response servlet response
    */
    protected void processRequest(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>Servlet test2</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>ESEMPIO MDB - WEB TRACKING</h1>");
            out.println("</body>");
            out.println("</html>");            
        } finally { 
            out.close();
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
    * Handles the HTTP <code>GET</code> method.
    * @param request servlet request
    * @param response servlet response
    */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
    * Handles the HTTP <code>POST</code> method.
    * @param request servlet request
    * @param response servlet response
    */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
    * Returns a short description of the servlet.
    */
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}

Prepare an object DTO (Data Transfer Object) 

Able to encapsulate the data that will serve the consumer client! 
This subject should be put in the EJB project and not in the WEB. 


import java.io.Serializable;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;


public class RequestDTO implements Serializable{
    String user_agent;
    private String remote_addr;
    private String query_string;
    private String method;
    private Date date;

    public String getMethod()
    {
        return method;
    }

    public void setMethod(String method)
    {
        this.method = method;
    }

    public String getQuery_string()
    {
        return query_string;
    }

    public void setQuery_string(String query_string)
    {
        this.query_string = query_string;
    }

    public String getRemote_addr()
    {
        return remote_addr;
    }

    public void setRemote_addr(String remote_addr)
    {
        this.remote_addr = remote_addr;
    }

    public String getUser_agent()
    {
        return user_agent;
    }

    public void setUser_agent(String user_agent)
    {
        this.user_agent = user_agent;
    }
   
    public RequestDTO(HttpServletRequest request)
    {
        user_agent = request.getHeader("user-agent");
        remote_addr = request.getRemoteAddr();
        query_string = request.getQueryString();
        method = request.getMethod();
        date = new Date();
    }

    @Override
    public String toString()
    {
        return date + " " + this.remote_addr + " " +  this.getMethod() + " " +  this.getUser_agent() + " " +  this.query_string + "\r\n";
    }
}


It is a simply object that extracts the necessary data and makes them available through the methods accessories. 
Note: The object must be Serializable! 

Also noteworthy is the override of the toString method to copy the value of all fields in a string DTO. 

The filter should instead look into the production of messages.

Create a new filter, using the wizard of NetBeans.
Still using the NetBeans wizard can automatically generate the code for the connection factory and the tail set up earlier.
In that case, click the right mouse button on the code of the filter and select

Enterprise Resources -> Send JMS Message

Setting the correct values in how to create resources referencing application server.

Or you can write by hand the following methods:


 private Message createJMSMessageFormyDestination(Session session, Object messageData) throws JMSException
    {
        ObjectMessage m = session.createObjectMessage((Serializable)messageData);                
        return m;
    }

    private void sendJMSMessageToMyDestination(Object messageData) throws NamingException, JMSException
    {
        Context c = new InitialContext();
        ConnectionFactory cf = (ConnectionFactory) c.lookup("java:comp/env/myQueueFactory");
        Connection conn = null;
        Session s = null;
        try
        {
            conn = cf.createConnection();
            s = conn.createSession(false, s.AUTO_ACKNOWLEDGE);
            Destination destination = (Destination) c.lookup("java:comp/env/myDestination");
            MessageProducer mp = s.createProducer(destination);
            mp.send(createJMSMessageFormyDestination(s, messageData));
        } finally
        {
            if (s != null)
            {
                s.close();
            }
            if (conn != null)
            {
                conn.close();
            }
        }
    }

automatically generated by NetBeans. 

To sum up the code to send the message you perform the following steps:

  1. Lookup resource ConnectionFactory
  2. creation of the connection
  3. creation of the session
  4. Lookup of destination
  5. Creation of client producer
  6. Sending message
  7. Closing session and connection

Then in the main method of filtering doFilter(ServletRequest request, ServletResponse response,                FilterChain chain)

you can call the method of sending the message

sendJMSMessageToMyDestination(new RequestDTO(request));

The content of the message will be the object of type HttpServletRequest request.
This object contains all the useful information log on to writing required on MDB.

Test production of messages 

Before you generate the client can consume messages produced by the filter, you should check if it works as a production, and launch the project and EAR call servlet test on which the filter is mapped. 

You may experience the following problem: 

javax.naming.NameNotFoundException: myQueueFactory not found
        at com.sun.enterprise.naming.TransientContext.doLookup(TransientContext.java:216)
        at com.sun.enterprise.naming.TransientContext.lookup(TransientContext.java:188)

This indicates that the value used in JNDI lookup phase is erroneous. 
In our case, for example NetBeans default considers the resources located in the path JNDI java: comp / env / resourcename, but when creating Glassfish included resources in the root, then you must make the following changes being lookup: 

ConnectionFactory cf = (ConnectionFactory) c.lookup("myQueue");

Destination destination = (Destination) c.lookup("myDestination");

Client that consumes messages - The MDB

Inside the EJB project, create an MDB. 

Once again you can use the wizard of NetBeans. 


Or hand-write the following code: 

package MDB;

import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.Message;
import javax.jms.MessageListener;

@MessageDriven(mappedName = "myDestination", activationConfig =  {
        @ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
        @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue")
    })

public class myMDBBean implements MessageListener {

   
    public myMDBBean() {
    }

    public void onMessage(Message message) {
    }
   
}



Through the use of dependency injection with a few notes you can instantiate the client JMS (the MDB).

@MessageDriven(mappedName = "myDestination", activationConfig =  {

        @ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),

        @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue")

    })

  It indicates that the bean is MessageDriven and add a couple of properties to indicate the type of destination (queue or topic) and the destination itself (previously set by the system). 
  With only another step you end configuration dell'MDB it is necessary to implement the MessageListener 
public class myMDBBeanimplements MessageListener {
public void onMessage (Message msg) {
FileWriter fw = null;
try
{
ObjectMessage m = (ObjectMessage) message;//casting per estrarre la corretta tipologia di messaggio
RequestDTO requestDTO = (RequestDTO) m.getObject();//estrazione dei dati dal messaggio

//open. write and close the file
fw = new FileWriter("c:\\logmdb.txt", true); //look! the windows path.
fw.append(requestDTO.toString());

} catch (IOException ex)
{
Logger.getLogger(myMDBBean.class.getName()).log(Level.SEVERE, null, ex);
} catch (JMSException ex)
{
Logger.getLogger(myMDBBean.class.getName()).log(Level.SEVERE, null, ex);
} finally
{
try
{
fw.close();
} catch (IOException ex)
{
Logger.getLogger(myMDBBean.class.getName()).log(Level.SEVERE, null, ex);
}
}

}


  Conclusion 

The example is able to process data without losing time, "the servlet so that they write in a log file.
Indeed launching 'n' times the servlet will notice the inclusion of n lines in the log file.

Note: Possible Problems
If the file server.log Glassfish note of the following string

DirectConsumer: Caught Exception delivering messagecom.sun.messaging.jmq.io.Packet can not be cast to com.sun.messaging.jms.ra.DirectPacket

know that this is a know issue https://glassfish.dev.java.net / issues / show_bug.cgi? id = 3988
  With the technology JMS client even if the consumer is not active at the time was posted, the messages will be delivered later. 
To demonstrate this, it is possible
  • delete temporary the mdb project;
  • delete the log file "logmdb.txt"
  • build and redeploy the project on the serv
  • launch the servlet test (which will generate a message to every call).

  • remake the MDB
  • build and redeploy the project on the server

  WITHOUT launch servlet will notice that the logs were put on the line calls when the MDB 
was not completely present.



The MVC Design Pattern in Java EE (Eng Ver)

MVC - Java EE (Eng Ver)
Introduction

MVC is a design pattern (a general design solution for problem solving) widely used in software design. 
MVC Stands for Model Controller View. 
MVC is achieved through 3 components: 

  • the model contains the data and provides methods for accessing them;
  • The view displays the data in the model;
  • the controller receives the commands(usually through the view) and implement them by changing the status of the other two components

This pattern ensures the division between business logic(managed by the model) and user interface (run by and view controller). 

Wanting to apply this pattern to the Java EE, you can use the following Java technologies applied to various components of the pattern. 

Model: This component can be implemented through the entity bean and session bean 
Controller: It can be implemented by the servlet. 
View: The latter through jsp and / or jsf. 

The entity bean will be an abstraction and then to represent the data, the session bean can perform operations on the entity, 
the servlet will collect input from jsp (you) to make requests to the session bean and communicate results to jsp and so on. 

Example: 

You have to implement a web application that allows you to view / edit the data in a table "users" in a db. 

Table: Users 
The columns: id, name, first name 

Insert into table one data row in order to have at least one default user. 

Suppose you use a persistence provider, for example hibernate 
For this element(users table) you can create an entity bean. 
Make a session bean with entitymanager that realize the methods "edit" and "find." 

  • edit - Will carry out the update users compared to the database using the entitymanager method merge.
  • find - made an id, returns the entity bean that represents the data in the table that are in line with id indicated.
  • .. You can also implement the methods "create", "erase" to complete.

By implementing this portion of the project, it gets the "Model" 

We implement a servlet(the servlet user) that calls through resource injection, @EJB, the session bean. 
Then by invoking the servlet model and using the method find(1) you can get the equivalent entity containing the data with id = 1; 

If the servlet receives the GET or POST parameter "id", "name" and "surname" then perform the upgrade db, creating a new entity with the data passed through http parameters and calling the method of the edit session bean. 
(Note that when you leave the entity EJB components, which are used for example, web components, entering into a state-managed ..) 

The servlet in this case the controller realized. 

The servlet article in question sets the request attribute "user" setting the panel obtained from the user session bean and using a RequestDispatcher performs a forward to a jsp that takes care to show a html form that allows the reading and editing of data. 
The modification done by calling the servlet users start moving their appropriate values. 

This short article does not have the presumption to be exhaustive, as implied in various concepts and technologies .. may be the point of departure for an approach to MVC in Java EE. 

For a complete example click here

Glassfish VS Tomcat (ENG ver)

Glassfish VS Tomcat (ENG Ver.)
G.Morreale

Introduction:

Forums often gets confused about the use of Glassfish or Tomcat, asking if it rather than use one another.
Looking at the logs blog often arrives people performing their research "Glassfish Tomcat VS" or "Glassfish or Tomcat" or "against Glassfish Tomcat" then it is clear that a newbie who comes close to Java EE is a bit of confusion about this choice.

The dispute has been clarified .. It 'a comparison that does not make sense!

Glassfish is a 4x4 off-road, is a city car Tomcat.
If I go to town in "off-road" stree I choosee the 4x4 otherwise if I am in a city I have to go with a city car because its use is easier.

Returning on the technical aspects ..

We assume that the platform Java EE consists of various and different technologies: JSP, Servlets, JMS, MDB, EJB, JPA etc etc. (See http://java.sun.com/javaee/technologies/)

Tomcat is able to support only a small part of Java EE, mainly relating to JSP and Servlet, which is why it is called a Tomcat Servlet Container.

note:
JSPs are also the servlet


An Application Server Java EE as Glassfish instead fully supports Java EE.
Glassfish (which in its commercial version with sun supports is called Sun Application Server) is the reference implementation for Java EE.

There are several alternatives to Glassfish:


The comparison Glassfish vs a list of servers has more sense than the title of the article!

An Application Server is able to do the same things that can make Tomcat, since it is a servlet container, so often there are comparisons of performance among the common features of Tomcat and Glassfish
(have a look
http://raibledesigns.com/rd/entry/glassfish_2_vs_tomcat_6.
or
http://www.pneumonoultramicroscopicsilicovolcanoconiosis.org/blog/glassfish-vs-tomcat
)

Conclusion

I personally prefer to apply the reasoning in the example of off-road car vs city car, in the sense that I take the car from the garage which is closest to the needs of the project.

It is also not excluded, in a complex architecture, the use of both types of servers, for example tomcat for front-end and Glassfish for the back-end.

Java EE - How to use EJB and WEB technologies

Java EE - An example on how to use EJB and web components
G.Morreale

Clicca qui per la versione in italiano
Introduction:

The purpose of this article is to create an enterprise application can use the following technologies

  • Entity Bean
  • Session Bean
  • Servlet
  • JSP 

Java EE platform is a very large and able to explain only small parts of them would require much more than a simple article.
Despite this, the attempt is to give an input to the programmer to stimulate the interest and cause him to deepen into a technology.

In order to speed up the approach to Java EE will be used Netbeans and consequently the whole series of wizards that the IDE provides.
Efforts will also include links to in-depth about the individual steps executed.

What will be able to make an example:

The design that you will be able to extract data from a table of a DBMS (mysql in this case) and print them via web page.

What should I install for example:


Note: The last two are not strictly necessary, it is possible to carry out similar operations with another DBMS or waive the graphical tool for the query.

The steps for implementing the example:

  1. The Database
    1. Create the schema
    2. Create a table
    3. People Table
  2. Enterprise Creation Project
  3. EJB
    1. Create a JDBC datasource
    2. Create a persistence unit
    3. Create the entity bean
    4. Create a session facade for the entity bean
  4. WEB Module
    1. Create a servlet
    2. Creare una jsp Create a jsp

1. The Database

Open Mysql query browser, logging on localhost, you create a new DB EsempioDB called with the following SQL:

CREATE DATABASE `EsempioDB`;

Create the table:

CREATE TABLE `esempiodb`.`EsempioTable` (
  `id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
  `testo` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`id`)
)
ENGINE = InnoDB;

Populate it:

INSERT INTO EsempioTable VALUES(1,'TESTO 1');
INSERT INTO EsempioTable VALUES(2,'TESTO 2');
INSERT INTO EsempioTable VALUES(3,'TESTO 3');


2. Creation Empty Project

Now create a new Enterprise selecting "New Project" in the file menu of NetBeans.

You choose a name, for example, "Example" and leave undisturbed all the required options until the end of the wizard.
This allows you to create a NetBeans EJB module project, a Web module project and a project EAR can include EJB and WEB in single file.

As you can see the list of projects will be the following 3 projects:

  • Example
  • Example-EJB
  • Example-war

note: 
Making a brief mention of the MVC design pattern the last two projects on hold model (EJB) and controller / view (war).

3. EJB

JDBC resource and PERSISTENCE UNIT

Now you need to create a JDBC server resource, a resource that is able to communicate with the DBMS and db created.

note:
This resource is usually created through the command its server (eg Glassfish asadmin add-resources-sun resources.xml) or through the administrative console of the server itself.
In the case of the Glassfish jdbc resource is created through an xml file in which a range of parameters such as username and password database, number of connections in the pool etc.

Xml file example:
<? xml version = "1.0" encoding = "UTF-8"?>
<! DOCTYPE resources PUBLIC "- / / Sun Microsystems, Inc. / / DTD Application Server 9.0 Resource Definitions / / EN" "http://www.sun.com/software/appserver/dtds/sun-resources_1_3.dtd">
<resources>
<jdbc-resource enabled="true" jndi-name="esempioJNDI" object-type="user" pool-name="mysqlPool"/>
<jdbc-connection-pool allow-no-component-callers = "false" associate-with-thread = "false" connection-creation-retry-attempts = "0" connection-creation-retry-interval-in-seconds = " 10 "connection-leak-reclaim =" false "connection-leak-timeout-in-seconds =" 0 "connection-validation-method =" auto-commit "datasource-classname =" com.mysql.jdbc.jdbc2.optional. MysqlDataSource fail-all-connections = "false" idle-timeout-in-seconds = "300" is-connection-validation-required = "false" is-isolation-level-guaranteed = "true" lazy-connection-association = "false" lazy-connection-enlistment = "false" match-connections = "false" max-connection-usage-count = "0" max-pool-size = "32" max-wait-time-in-Millis = " 60000 "name =" mysqlPool "non-transactional-connections =" false "pool-resize-quantity =" 2 "res-type =" javax.sql.DataSource "statement-timeout-in-seconds =" -1 "steady - pool-size = "8" validate-atmost-once-period-in-seconds = "0" wrap-jdbc-objects = "false">
<property name="serverName" value="localhost"/>
<property name="portNumber" value="3306"/>
<property name="databaseName" value="esempioDB"/>
<property name="User" value="root"/>
<property name="password" value="123456"/>
<property name="url" value="jdbc:mysql://localhost:3306/esempioDB"/>
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
</ jdbc-connection-pool>
</ resources>

Netbeans automatically generates the xml file and is responsible to communicate to the Glassfish in order to deploy this resource.

To do this you can go directly to create the persistence unit (would be the next step) and select from combobox DataSource "New Data Source"
(To obtain this window click the right button on the EJB project and choose within the category persistence: persistence unit.) 

Clicking on New Data Source abandons for a moment the creation of the persistence unit and move to the creation of a resource for communication with the db.
Initially you are asked a JNDI name and a URL jdbc.
On the first, you can choose an arbitrary name, eg. esempioJNDI

note:
The jndi name used to identify the resource inside the container, but this path will not be used directly in the code when using the dependency injection will be the same container to find the resource (using the path JNDI)

About the Database Connection, proceed by clicking the "New Database Connection", will appear in another window which must indicate the type of jdbc driver to use (mysql!) And the connection parameters.



Setting everything correctly in order to return to the "New Unit persistence."

On the "New persistence Unit must operate with the following options:

  • Persistence Unit Name is the name of the configuration of the persistence unit

  • Persistence Provider: Indicates which libraries use to manage the mapping between the database and its representation object
(default is proposed Toplink, but there are other viable alternatives, I personally prefer to hibernate, but for the example you give Toplink optional)

  • DataSource is the name of the newly created Datasource
  • Use Java Transaction API: Indicates whether to manage the JTA transaction or not. (leave checked)

  • Table generation Strategy: Tells the persistence provider whether or not to create the tables if there are the entity and not the card tables. (In this example, the tables have been created, but you could directly create the entity representing the tables and let that the persistence provider to automatically generate)

Ultimately chose the name of the persistence unit (for example - Example-ejbPU) you can continue clicking Finish leaving all options unchanged.

Netbeans has created two files automatically

  • sun-resources.xml - needed to create a resource on the server jdbc
  • persistence.xml - needed to indicate a range of options for the management of persistence (mapping O / R) etc.


Entity Bean

What is an entity bean? E 'POJO an object capable of representing the notation through an object table.
Correspondence between entity bean and tables is gestista the persistence provider (a number of libraries).
In the previous step has been chosen as provider Toplink (its libraries are installed by default).

note:
There are two types

BMP - entity Bean Managed Persistence
CMP - Container Managed Persistence entity

The first state that the programmer to deal with the logic of the mapping between the entity and the relational database, the latter supporting the persistence provider. In the entity will be created CMP.

These beans can be created automatically by another wizard of NetBeans.

Right click on the draft EJB Entity + Classes From Databases .. Choose the datasource "esempioJNDI" and choose the tables to be submitted to the wizard (only 1 in this case).

Click next, indicating a package that contains the entity, such entities, click on finish.

note:
The "Generated named query annotation ..." used to automatically generate the query within dell'entity, these queries have the advantage of being precompiled and therefore slightly more efficient. In this instance, however, is not used, so the option is left out.

Entities within the package you can find the entity bean through annotations (@ Table, @ Column etc.) Indicates the persistence provider how to make the mapping between data and nell'entity db.

Session Bean

What is a Session bean? It 'a component that manages the application logic, the classic example of the bank will look to carry out the transfer, etc list movements.

He has a particular life-cycle management by the container (through pooling) and usually are used to manage the request-response model.

note:
There are two types of session bean: Stateless and Stateful, the difference lies in the maintenance of information between clients and servers, only the latter are in fact able to retain such data.

The session bean is composed of its interface and its implementation

note:
The interface can be of two types, Local and Remote, the first is used when the EJB module and web module residing within the same enterprise application (EAR), are obviously more efficient. The latter are used when the EJB modules and the web form (or other forms EJB) reside on different applications or other container.

We use the wizard again NetBeans to automatically create a session bean can implement and expose local interface through the most common methods (insert, edit, deletions etc.) Interaction with the newly created entity.

Right click on the draft EJB - Session Bean Entity For Classes - to choose the entity - to choose a package (eg session) -> Finish!

Inside the package was created session the session bean and its interface.
The interface exposes the methods used from the outside (eg web form: servlet)

It gives a look to the implementation of the session bean


@Stateless
public class EsempiotableFacade implements EsempiotableFacadeLocal {

    @PersistenceContext
    private EntityManager em;

    public void create(Esempiotable esempiotable)
    {
        em.persist(esempiotable);
    }

    public void edit(Esempiotable esempiotable)
    {
        em.merge(esempiotable);
    }

    public void remove(Esempiotable esempiotable)
    {
        em.remove(em.merge(esempiotable));
    }

    public Esempiotable find(Object id)
    {
        return em.find(entities.Esempiotable.class, id);
    }

    public List<Esempiotable> findAll()
    {
        return em.createQuery("select object(o) from Esempiotable as o").getResultList();
    }

}

@Stateless merely indicates the type of bean.

@PersistenceContext
private EntityManager em;

Used to initialize the EntityManager, or that object which has been mapping between entity and tables.
The EntityManager class is a key provider of persistence.
the annotation @ PersistenceContext allows the container to initialize the variable em considering the information entered in the file persistence.xml (Remember the persistence unit!).
The initialization is done through the mechanism of dependency injection (see my previous article).

methods "em.find, em.remove, em.merge, em. persist"
belong to and serve dell'entity manager respectively for the following basic

  • em.find -> search through an entity id (corresponds to a SELECT ... WHERE id =: id)
  • em.remove -> elimination by id (equal to DELETE .. WHERE id =: id
  • em.merge -> insert or update (INSERT or UPDATE) (also serves to recover entity detached ...)
  • em. persist -> inclusion on dell'entity db (corresponds to INSERT)

To achieve the specific operations through ad hoc queries are used, as in method (findall ()), generating a query through the "createQuery" 

The query to be submitted all'entitymanager must be written in EJB-QL, or a specific language can make queries on the entity and not on tables. EJB-QL helps ensure the portability of the queries through various DBMS (the query written in fact exclude mysql).
For more on EJB-ql here.

Of course we must learn to write their own session bean but the example intends to give a fair view ..


WEB Module

We have built the business logic, the EJB is able to extract data from db and communicating through a data structure (List <Esempiotable>)

Now you can create a servlet to invoke the session bean. (According to the MVC pattern, the servlet will serve as a controller).

Right click on the form war -> New Servlet -> Servlet class name = test -> package = servlet -> Finish

It empties the ProcessRequest method so that it is equal to the portion of code following

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
{
    //clicca qui con il tasto dx.

Now you proceed with the initialization (once again made through dependency injection) of the EJB component to be recalled.

Where there is a comment click the right button -> Enterprise Resources -> Call Enterprise Bean -> Click-EJB Example -> EsempioTableFacade -> Finish 

In the latter case, the wizard is used to insert a single line of code:

@ EJB
Private EsempiotableFacadeLocal esempiotableFacade;

Or the one for the initialization of the session bean.
This variable does not need further initialization (thanks all'annotation has already thought of the container!), Is then ready for use.

Within ProcessRequest is then able to enter the following code in order to extract the contents of the table.

<Esempiotable> List esempiotableFacade.findAll list = ();
/ / (do not forget to fix the import!)

Well, have you suffered in the servlet that could print the contents of the List attarverso a PrintWriter or similar response from starting.
But wanting to respect the MVC paradigm and set the example for a more structured you decide to move the data to a view (a JSP page).

In order to move data between the servlet and jsp page using the technique of using a RequestDispatcher forward.

The dispatcher can be initialized as follows:

String arg = "/" + this.getServletName () + ". Jsp";
RequestDispatcher dispatcher = this.getServletContext (). GetRequestDispatcher (arg);

forwarding is done through education

dispatcher.forward (request, response);

This technique does not generate a redirect to the jsp page, but to tell the container that the flow is passed from servlet to jsp keeping intact the status of your request and response.
So it can then transmit the information contained in the "list" to jsp settandoli inside of the request and act in the following manner:

request.setAttribute ( "list", list);

then ultimately the code ProcessRequest will be the following:

protected void ProcessRequest (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException (
        
<Esempiotable> List esempiotableFacade.findAll list = ();
  
request.setAttribute ( "list", list);
            
String arg = "/" + this.getServletName () + ". Jsp";
RequestDispatcher dispatcher = this.getServletContext (). GetRequestDispatcher (arg);
dispatcher.forward (request, response);
            
)

Now create a jsp with the same name as the servlet (test.jsp) (According to MVC, we are creating a view)

The jsp code is as follows:

<% @ page contentType = "text / html"%>
<% @ page pageEncoding = "UTF-8"%>
<% @ page import = "entities.Esempiotable"%>
<% @ page import = "java.util.List"%>
<%
<Esempiotable> List list = (List <Esempiotable>) request.getAttribute ( "list");
%>
<! DOCTYPE HTML PUBLIC "- / / W3C / / DTD HTML 4.01 Transitional / / EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title> JSP Page </ title>
</ head>
<body>
<h1> Content Table EsempioTable </ h1>
<% If (list! = Null)
(For (Esempiotable e: list)
(Out.println (e.getId () + "" + e.getTesto () + "<br/>");)
)
%>
</ body>
</ html>

The code is trivial, is extracted from the request the attribute list and then in the html code is made for a course through the list to print the contents of the entity.

Clicking sull'Enterprise Application Example Run and typing in your browser
http://localhost/Esempio-war/test

The output obtained will be similar to the following image:




Conclusion:

This article is just an introduction to the Java EE world of things to explore and explain this is not really a lot .. This is just the beginning!