Monday, October 13, 2014


Creating an Enterprise Application with EJB 3.1

https://netbeans.org/kb/docs/javaee/javaee-entapp-ejb.html



Netbeans 6.9
Galsss fish 3.1
Java EE 6


Coding EJB Module


1.Create Entity class models.



-----------------------------------------------------------------------------------------------------------------------
i.Create BookEntity

1. Right-click the EJB module in the Projects window and choose New > Other to open the New
File wizard.
2. From the Persistence category, select Entity Class and click Next.
3. Type "BookEntity" for the Class Name.
4. Type "ejb" for the Package.
5. Leave the Primary Key Type as "Long" in the New Entity Class wizard.
6. Select Create Persistence Unit. Click Next.
7. Keep the default Persistence Unit Name.
8. For the Persistence Provider, choose EclipseLink (JPA2.0)(default).
9. For the Data Source, choose a data source (for example, select jdbc/sample if you want to
use JavaDB).
10.Click Finish.

2.Create another Entity class "AutherEntity"
As according to the previous steps.

3.For book entity add folowing variables.

1. Add the following field declarations to the book class:

    private String title;
    private int ISBN;
    private String author;
    private int b_year;
    private String language;
    private double price;


2. Right-click in the Source Editor and choose Insert Code (Alt-Insert; Ctrl-I on Mac) and select
Getter and Setter to open the Generate Getters and Setters dialog box.

3. Select the body and title fields in the dialog box. Click Generate.
4.Save changes.

2. Add the following field declarations to the auther class:
  private String name;

Generte Getters and Setters.

-------------------------------------------------------------------------------------------------------------------------

2.Creating the Message-Driven Bean for each entity class


1. Right-click the EJB module in the Projects window and choose New > Other to open the New
File wizard.
2. From the Enterprise JavaBeans category, select the Message-Driven Bean file type.
Click Next.
Note. In NetBeans IDE 6.9, the Message-Driven Bean file type is in the Java EE category.
3. Type "NewBook" for the EJB Name.
4. Select ejb from the Package drop-down list.
5. Click the Add button next to the Project Destination field to open the Add Message Destination
dialog box.
6. In the Add Message Destination dialog box, type jms/1. Right-click the EJB module in the Projects window and choose New > Other to open the New
File wizard.
2. From the Enterprise JavaBeans category, select the Message-Driven Bean file type. Click Next.
Note. In NetBeans IDE 6.9, the Message-Driven Bean file type is in the Java EE category.
3. Type NewMessage for the EJB Name.
4. Select ejb from the Package drop-down list.
5. Click the Add button next to the Project Destination field to open the Add Message Destination
dialog box.
6. In the Add Message Destination dialog box, type jms/NewBook  and select Queue for the
destination type. Click OK.


Do same for the New auther and type the name as "jms/NewBook".

1. Inject the MessageDrivenContext resource into the class by adding the following annotated
field (in bold) to the class:

2. public class NewMessage implements MessageListener {

4. @Resource
private MessageDrivenContext mdc;

5. Introduce the entity manager into the class by right-clicking in the code and choosing
 InsertCode (Alt-Insert) -> choosing Use Entity Manager from the pop-up menu.
Note. In NetBeans IDE 6.9, choose Persistence > Use Entity Manager.
The IDE adds the following @PersistenceContext annotation to your source code.

@PersistenceContext(unitName = "NewsApp-ejbPU")
private EntityManager em;

The IDE also generates the following persist method.

public void persist(Object object) {
em.persist(object);
}

6. Modify the persist method to change the name to save. The method should look like the
following:
7. public void save(Object object) {
8. em.persist(object);
}

Do Same for the auther.

-----------------------------------------------------------------------------------------------------------------------

3.Create Session Facade.

To create the session facade, perform the following steps:
1. Right-click the EJB module and choose New > Other.
2. From the Persistence category, select Session Beans for Entity Classes. Click Next.
3. Select ejb.autherEntity & ejb.bookEntity from the list of available entity classes and click Add to move the
class to the Selected Entity Classes pane. Click Next.
4. Check that the Package is set to ejb. Click Finish.

It will creates a AbstractFacde class and AutherFacde and BookFacade.

Abstract facade created because we add two classes

-----------------------------------------------------------------------------------------------------------------

Coding the Web Module

1.Creating the Singleton Session Bean

1. Right-click the Web module and choose New > Other to open the New File wizard.
2. Select Session Bean in the Enterprise JavaBeans category.
Note. In NetBeans IDE 6.9, Session Bean is in the Java EE category.
3. Type SessionManagerBean for the EJB Name.
4. Type ejb for the Package name.
5. Select Singleton. Click Finish.


@Singleton
@LocalBean
public class SessionManagerBean {
}
1. Annotate the class with @WebListener and implement HttpSessionListener.
2. @Singleton
3. @LocalBean

4. @WebListener

5. public class SessionManagerBean implements HttpSessionListener{

7. Click the warning badge in the left margin and choose "Implement all abstract methods".

9. @LocalBean
10. @WebListener
11. public class SessionManagerBean implements HttpSessionListener{
         private static int counter = 0;
}

public void sessionCreated(HttpSessionEvent se) {
                  counter++;
 }

public void sessionDestroyed(HttpSessionEvent se) {
           counter--;
}
Add the following method that returns the current value of counter.


 public int getActiveSessionsCount() {
           return counter;
}


----------------------------------------------------------------------------------------------------------------------

4. Creating the ListBooks Servlet

1. Right-click the web module project and choose New > Servlet.
2. Type ListNews for the Class Name.
3. Enter web for the Package name. Click Finish.


1. Right-click in the source editor and choose Insert Code (Alt-Insert) and select Call Enterprise
Bean.
2. In the Call Enterprise Bean dialog box, expand the BookApp-ejb node and select
NewsEntityFacade. Click OK.

The IDE adds the @EJB annotation to inject the enterprise bean

3. Use the Call Enterprise Bean dialog box again to inject the SessionManagerBean under the
NewsApp-war node.

In your code you will see the following annotations that inject the two enterprise beans.

@WebServlet(name = "ListBooks", urlPatterns = {"/ListBooks"})


public class ListBooks extends HttpServlet {
 
    @EJB
    private AuthorEntityFacade authorEntityFacade;
    @EJB
    private BookEntityFacade bookEntityFacade;

In the processRequest method, add the following code (in bold) to return the current
session or create a new one.

5.    protected void processRequest(HttpServletRequest request,
               HttpServletResponse response)
6.             throws ServletException, IOException {
7.                   request.getSession(true);
                 response.setContentType("text/html;charset=UTF-8"

In side body tag add what you want to dipalay (table )and links to other pages using href
           out.println("<head>");
            out.println("<title>ListBooks</title>");
            out.println("</head>");
           out.println("<body>");
            out.println("<center>");
            out.println("<h2>Books List</h2>");
            out.println("<br/>");
            out.println("<table border='1' width='800px'>");
            out.println("<th></th>");
            out.println("<th>ISBN</th>");
            out.println("<th>Title</th>");
            out.println("<th>Author Name</th>");
            out.println("<th>Price</th>");
            out.println("<th>Publish Date</th>");
            out.println("<th>Language</th>");
            List books = bookEntityFacade.findAll();
            for (Iterator it = books.iterator(); it.hasNext();) {
                out.println("<tr>");
                BookEntity elem = (BookEntity) it.next();
                out.println(" <td> <a href='UpdateBook?Id=" + elem.getId() + "'>Update</a></td>");
                out.println(" <td> <a href='ViewBook?Id=" + elem.getId() + "'> " + elem.getISBN()+ "                          </a></td>");
                out.println(" <td>" + elem.getTitle()+ " </td>");
                out.println(" <td>" + elem.getAuthor()+ "</td> ");
                out.println(" <td>" + elem.getPrice()+ " </td>");
                out.println(" <td>" + elem.getB_year()+ " </td>");
                out.println(" <td>" + elem.getLanguage()+ " </td>");
                out.println("</tr>");
            }
            out.println("</table>");
            out.println("<br/>");
            out.println("<a href='NewBook'>Add new Book</a>");
            out.println("<br/>");
            out.println("<a href='Main'>Home</a>");
            out.println("</center>");
            out.println("</body>");
            out.println("</html>");

----------------------Do same to List auther servlet.---------------------------------------------------------------


           out.println("<body>");
            out.println("<center>");
            out.println("<h2>Authors List</h2>");
            out.println("<br/>");
            out.println("<table border='1' width='800px'>");
            out.println("<th></th>");
            out.println("<th></th>");
            out.println("<th>Name</th>");

            List aut = authorEntityFacade.findAll();
            for (Iterator it = aut.iterator(); it.hasNext();) {
                out.println("<tr>");
                AuthorEntity elem = (AuthorEntity) it.next();
                out.println(" <td> <a href='UpdateAuthor?Id=" + elem.getId() + "'>Update</a></td>");
                out.println(" <td> <a href='?Id=" + elem.getId() + "'>Delete</a></td>");

                out.println(" <td>" + elem.getName() + " </td>");
                out.println("</tr>");
            }
            out.println("</table>");
            out.println("<br/>");
            out.println("<br/>");
            out.println("<a href='NewAuthor'>Add new Author</a>");
            out.println("<br/>");
            out.println("<a href='Main'>Home</a>");
            out.println("</center>");
            out.println("</body>");

---------------------------2.Insert a new book servlet.--------------------------------------------------------------

@WebServlet(name = "NewBook", urlPatterns = {"/NewBook"})
public class NewBook extends HttpServlet {

//    @Resource(mappedName = "jms/NewBookFactory")
//    private ConnectionFactory connectionFactory;
//    @Resource(mappedName = "jms/NewBook")
//    private Queue queue;

    BookEntity b = new BookEntity();
    int ISBN;
    double price;
    int year;
    Boolean exist = false;
 
    @EJB
    private AuthorEntityFacade authorEntityFacade;
    @EJB
    private BookEntityFacade bookEntityFacade;

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        if (request.getParameter("isbn") != null) {
            ISBN = Integer.parseInt(request.getParameter("isbn").toString());
        }
        if (request.getParameter("year") != null) {
            year = Integer.parseInt(request.getParameter("year").toString());
        }
        if (request.getParameter("price") != null) {
            price = Double.parseDouble(request.getParameter("price"));
        }

        String title = request.getParameter("title");
        String language = request.getParameter("lang");
        String author = request.getParameter("author");

        if ((ISBN != 0) && (year != 0) && (price != 0) && (title != null) && (language != null) && (author != null)) {
            try {

                /*Connection connection = connectionFactory.createConnection();
                 Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                 MessageProducer messageProducer = session.createProducer(queue);
                 ObjectMessage message = session.createObjectMessage();*/


                // here we create NewsEntity, that will be sent in JMS message 
               

 try {
                    
                        BookEntity b = new BookEntity();
                        b.setAuthor(author);
                        b.setISBN(ISBN);
                        b.setLanguage(language);
                        b.setPrice(price);
                        b.setTitle(title);
                        b.setB_year(year);
                        

                        bookEntityFacade.create(b);
                        response.sendRedirect("ListBooks");
         

                } catch (EJBException ex) {
                }



                //  response.sendRedirect("ListNews");
            } catch (EJBException ex) {
                ex.printStackTrace();
            }
        }


--------------------Create a form inside the body to add-------------------------------------------
            out.println("<head>");
            out.println("<title>Servlet AddNewBooks</title>");
            out.println("</head>");          
            out.println("<body>");
            out.println("<h2>Add New Book</h2>");
            out.println("<br/>");
            out.println("<form>");
            out.println("ISBN: <br/>");
            out.println("<input type='text' name='isbn' size='15'><br/>");
            out.println("Title: <br/>");
            out.println("<input type='text' name='title' size ='15'><br/>");
            out.println("Author Name: <br/>");
            out.println("<select name='author'>");
            out.println("<option></option>");
            List cus = authorEntityFacade.findAll();
            for (Iterator it = cus.iterator(); it.hasNext();) {
                AuthorEntity elem = (AuthorEntity) it.next();
                out.println("<option>" + elem.getName() + "</option>");
            }
            out.println("</select><br/>");
            out.println("Price: <br/>");
            out.println("<input type='text' name='price' size='15'><br/>");
            out.println("Year: <br/>");
            out.println("<input type='text' name='year' size ='15'><br/>");
            out.println("Language: <br/>");
            out.println("<input type='text' name='lang' size ='15'><br/>");
            out.println("<br/>");
            out.println("<input type='submit' value='Add Book'><br/>");
            out.println("</form>");
            out.println("<br/>");
            out.println("<a href='ListBooks'>Back</a>");
            out.println("</body>");

----------------------------Using a mapping file- in to add auther ------------------------------------------------


1. Right-click the web module project and choose New > Servlet.
2. Type PostMessage for the Class Name.
3. Enter web for the Package name and click Finish

adding the following field declarations (in bold):

WebServlet(name = "NewAuthor", urlPatterns = {"/NewAuthor"})
public class NewAuthor extends HttpServlet {
//    @EJB
//    private NewSessionBean newSessionBean;
//    @EJB
//    private AuthorEntityFacade authorEntityFacade;

    @Resource(mappedName = "jms/NewAuthorFactory")
    private ConnectionFactory connectionFactory;
    @Resource(mappedName = "jms/NewAuthor")


    private Queue queue;
    AuthorEntity e = new AuthorEntity();


 protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       response.setContentType("text/html;charset=UTF-8");


        String title = request.getParameter("title");
        if ((title != null)) {
            try {
                Connection connection = connectionFactory.createConnection();
                Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                MessageProducer messageProducer = session.createProducer(queue);
                ObjectMessage message = session.createObjectMessage();


                // here we create NewsEntity, that will be sent in JMS message 

                e.setName(title);

                message.setObject(e);
                messageProducer.send(message);
                messageProducer.close();


                connection.close();

                //  response.sendRedirect("ListAuthers");
            } catch (JMSException ex) {
                ex.printStackTrace();
            }
        }

------------------Update book-----------------------------------------------------------------------------------------
public class UpdateBook extends HttpServlet {

    @EJB
    private BookEntityFacade bookEntityFacade;
    BookEntity bo;
    Long Id;
    int ISBN, year;
    Double price;

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        if (request.getParameter("Id") != null) {

            Id = Long.parseLong(request.getParameter("Id").toString());

            try {
                bo = bookEntityFacade.find(Id);

            } catch (EJBException ex) {
            }
        } else {
            bo = new BookEntity();
            bo.setAuthor("");
            bo.setTitle("");
            bo.setLanguage("");
        }

        try {
            ISBN = Integer.parseInt(request.getParameter("isbn").toString());
            year = Integer.parseInt(request.getParameter("year").toString());
            price = Double.parseDouble(request.getParameter("price").toString());
        } catch (NullPointerException ex) {
        }
        String title = request.getParameter("title");
        String author = request.getParameter("author");
        String language = request.getParameter("language");

        if ((ISBN != 0) && (year != 0) && (price != 0) && (title != null) && (language != null) && (author != null)) {
            try {

                BookEntity b = new BookEntity();
                b.setAuthor(author);
                b.setISBN(ISBN);
                b.setLanguage(language);
                b.setPrice(price);
                b.setTitle(title);
                b.setB_year(year);

                bookEntityFacade.edit(b);
                response.sendRedirect("ListBooks");

            } catch (EJBException ex) {
                ex.printStackTrace();
            }
        }
-------------------------------------------------------------------------------------------------------------------
              out.println("<head>");
            out.println("<title>Servlet UpdateBooks</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h2>Update Books</h2>");
            out.println("<br/>");
            out.println("<form>");
            out.println("ISBN: <br/>");
            out.println("<input type='text'  name='isbn' readonly='readonly' value='" + bo.getISBN() + "'>              <br/>");
            out.println("Title: <br/>");
            out.println("<input type='text'  name='title' readonly='readonly' value='" + bo.getTitle() + "'>                      <br/>");
            out.println("Author: <br/>");
            out.println("<input type='text'  name='author' value='" + bo.getAuthor() + "'><br/>");
            out.println("Price: <br/>");
            out.println("<input type='text'  name='price' value='" + bo.getPrice() + "'><br/>");
            out.println("Year: <br/>");
            out.println("<input type='text'  name='year' value='" + bo.getB_year() + "'><br/>");
            out.println("Language: <br/>");
            out.println("<input type='text'  name='language' value='" + bo.getLanguage() + "'><br/>");
            out.println("<input type='submit' value='Update Books'> <br/>");
            out.println("</form>");
            out.println("<br/>");
            out.println("<a href='ListBooks'>Back</a>");
            out.println("</body>");

---------------------------------------------Update auther-------------------------------------------------------
@WebServlet(name = "UpdateAuthor", urlPatterns = {"/UpdateAuthor"})
public class UpdateAuthor extends HttpServlet {

    @EJB
    private AuthorEntityFacade authorEntityFacade;
 
    AuthorEntity e;
    Long Id;

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        if (request.getParameter("Id") != null) {

            Id = Long.parseLong(request.getParameter("Id").toString());

            try {
                e = authorEntityFacade.find(Id);
            } catch (EJBException ex) {
             
            }
        } else {
            e = new AuthorEntity();
            //ce.setCusID("");
            e.setName("");
        }
     
        //Long id = Long.parseLong(request.getParameter("id").toString());
        String name = request.getParameter("name");


        if ((name != null) ) {
            try {
             
                AuthorEntity c = new AuthorEntity();
                c.setId(Id);
                c.setName(name);


                authorEntityFacade.edit(c);
                response.sendRedirect("ListAuthor");

            } catch (EJBException ex) {
                ex.printStackTrace();
            }
        }

--------------------------------------------------------------------------------------------------------------------
            out.println("<head>");
            out.println("<title>Servlet UpdateAuthor</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h2>Update Author</h2>");
            out.println("<br/>");
            out.println("<form>");
         
            out.println("Author Name: <br/>");
            out.println("<input type='text' name='name' size='40' value='" + e.getName() + "'><br/>");

            out.println("<br/>");
            out.println("<input type='submit' value='Update Author'> <br/>");
            out.println("</form>");
            out.println("<br/>");
            out.println("<a href='ListAuthor'>Back</a>");
            out.println("</body>");

------------------------------Search book by ID--------------------------------------------------------------------
@WebServlet(name = "ViewBook", urlPatterns = {"/ViewBook"})
public class ViewBook extends HttpServlet {

    @EJB
    private AuthorEntityFacade authorEntityFacade;
    @EJB
    private BookEntityFacade bookEntityFacade;
    BookEntity bo;
    Long id;

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        if (request.getParameter("Id") != null) {

            id = Long.parseLong(request.getParameter("Id").toString());

            try {
                bo = bookEntityFacade.find(id);
            } catch (EJBException ex) {
             
            }
        }

------------------------------------------------------------------------------------------------------------------------
out.println("<head>");
            out.println("<title>Servlet ViewBook</title>");          
            out.println("</head>");
            out.println("<body>");
            out.println("<h2>View Book Details</h2>");
            out.println("<br/>");
            out.println("<form>");
            out.println("ISBN: <br/>");
            out.println("<input type='text' size='10' value='"+ bo.getISBN() +"'><br/>");
            out.println("Title: <br/>");
            out.println("<input type='text' size='15' value='"+ bo.getTitle() +"'><br/>");
            out.println("Author Name: <br/>");
            out.println("<input type='text' size='15' value='"+ bo.getAuthor()+"'><br/>");
            out.println("Price: <br/>");
            out.println("<input type='text' size='15' value='"+ bo.getPrice() +"'><br/>");
            out.println("Year: <br/>");
            out.println("<input type='text' size='15' value='"+ bo.getB_year() +"'><br/>");
            out.println("Language: <br/>");
            out.println("<input type='text' size='15' value='"+ bo.getLanguage() +"'><br/>");
            out.println("<a href='ListBooks'>Back</a>");
            out.println("</body>");

---------------------------------Main------------------------------------------------------------------------
Name "Main" as start up servlet and link  other forms using href.

             out.println("<title>Online BookStore</title>");          
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Online BookStore</h1>");
            out.println("<a href='ListBooks'>Book Details</a>");
            out.println("<br/>");
            out.println("<a href='ListAuthor'>Author Details</a>");
            out.println("</body>")

---------------------------------------------------------------------------------------------------------------
1. In the Projects window, right-click the NewsApp enterprise application node and select
Properties in the pop-up menu.
2. Select Run in the Categories pane.
3. In the Relative URL textfield, type /Main.
4. Click OK.
5. In the Projects window, right-click the NewsApp enterprise application node and choose Run.

























No comments:

Post a Comment