Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

"Online Tweeter Enterprise Application" : Creating a Singleton Session Bean in NetBeans EJB module - Part 7


Lets continue building "Online Tweeter Enterprise Application" in NetBeans. In this section of tutorial, you will create a Singleton Session Bean by name "ActiveFollowersOnline.java". A Singleton Session Bean is a enterprise bean which are instantiated once per application and has lifecycle till application is alive.

Step 1: Open "Tweeter-war" project and right click Source Packages and then select New and than Other as shown in fig below:







Step 2: On clicking Other a dialog box appears by name New File. In the Categories: list select Enterprise JavaBeans and in the File Types: select Session Bean as shown in fig below.







Step 3: Click

.
New Session Bean dialog box gets open. It prompts us to enter EJB Name: , Project: , Location: , Package: , Session Type: and Create Interface: etc. Enter the values as shown in the fig below.



Step 4: Click




 

A new Singleton Session Bean gets created by name "ActiveFollowersOnline.java" in the "Tweeter-war" module in the package provided at the time of creating the bean. It has most of the source code already generated by NetBeans. Kindly add or remove additional code provided below.


package com.hubberspot.ejb;

import javax.ejb.Singleton;
import javax.ejb.LocalBean;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

// @Singleton annotation informs container that
// treat this bean as a Singleton bean.

// @LocalBean annotation informs container that
// this session bean exposes a no-interface view.

// @WebListener annotation informs container that
// this class is a web listener which will listen to 
// various events happening during lifecyle of application
// Here this class listens to Http Session when a session
// is created or destroyed.

// We make class implements HttpSessionListener which has two
// methods sessionCreated() and sessionDestroyed() , which 
// are called by the container whenever a session is created 
// or destroyed

@Singleton
@LocalBean
@WebListener
public class ActiveFollowersOnline implements HttpSessionListener {

    private static int followersOnline = 0;

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        
        System.out.print("Session Created : ");
        followersOnline++;
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        followersOnline--;
    }

    public int getFollowersOnline() {
        return followersOnline;
    }   
    
}




In the next section of this blog (part 8) you will learn how to create a Servlet in NetBeans for this application in the Web module.



"Online Tweeter Enterprise Application" : Creating a JSP page in NetBeans Web module - Part 6

Lets continue building "Online Tweeter Enterprise Application" in NetBeans. In this section of tutorial, you will create a Java Server Pages (JSP) by name "tweets.jsp". A JSP page is like a User Interface for Web Application. Its like a dynamic web page having html with java embedded into it.

Step 1:
Open "Tweeter-war" project and right click Web Pages and then select New and than Other as shown in fig below.





Step 2: On clicking Other a dialog box appears by name New File. In the Categories: list select Web and in the File Types: select JSP as shown in fig below.




Step 3: Click

.
New JSP dialog box gets open. It prompts us to enter values for the File Name: , Project: , Location: , Folder: , Created File: and Options: .Enter the required values as per fig shown below.




Step 4: Click




 

A new jsp page gets created by the name tweets.jsp in the "Tweeter-war" module.Kindly add or remove additional code provided below. 

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!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>Tweeter</title>
    </head>
    <body>
        <table border="0" bgcolor="aquagreen" cellpadding="0" cellspacing="0" width="60%">
            <tr>
                <td>
                    <table border="0" align="center" cellpadding="0" cellspacing="0" width="100%">
                        <tr>
                            <td valign="middle" align="center" style="padding-right:0px; padding-left:0px; padding-bottom:0px; font:24px/30px Georgia; width:228px; color:#FFFFFF; padding-top:0px; height:37px;">
                                What's happening ?. !!!
                            </td>
                        </tr>
                    </table>                    
                </td>
            </tr>
            <tr align="left" valign="top">
                <td height="20">
                    <hr />
                </td>
            </tr>
            <tr>
                <td>
                    <form name="tweetsForm" action="TweetsSubmit" method="post">
                        <table border="0" cellpadding="0" cellspacing="0" width="100%">
                            <tr>
                                <td align="right" valign="top">
                                    UserName:
                                </td>
                                <td>
                                    <input type="text" name="txtUsername" size="50" maxlength="75"/>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <br/>
                                </td>
                            </tr>
                            <tr>
                                <td align="right" valign="top">
                                    Your Tweet:
                                </td>
                                <td>
                                    <textarea name="txtTweet" cols="38" rows="6"></textarea> 
                                </td>                                    
                            </tr>
                            <tr align="left">
                                <td height="20">
                                    <hr />
                                </td>
                                <td height="20">
                                    <hr />
                                </td>
                            </tr>
                            <tr>
                                <td colspan="2" align="left">
                                    <input type="submit" value="Tweet" />
                                </td>
                            </tr>
                        </table>
                    </form>
                </td>
            </tr>            
        </table>
    </body>
</html>



Output of the jsp on browser window : 


tweets.jsp is a simple web page having few html components which prompts user to enter UserName , Tweet he/she wants to publish and than click on Submit button.  

In the next section of this blog (part 7) you will learn how to create a Singleton Session Bean in NetBeans for this application in the Web module. 

"Online Tweeter Enterprise Application" : Creating a Stateless Session Bean in NetBeans EJB module - Part 5


Lets continue building "Online Tweeter Enterprise Application" in NetBeans. In this section of tutorial, you will create a Stateless Session Bean by name "TweetsFinder.java". A Stateless Session Bean is a enterprise bean that is short - lived object which fulfill single client request and remember nothing about the client in subsequent requests.

Step 1: Open "tweeter-ejb" project and right click Source Packages and then select New and than Other as shown in fig below:










Step 2: On clicking Other a dialog box appears by name New File. In the Categories: list select Enterprise JavaBeans and in the File Types: select Session Bean as shown in fig below.































Step 3: Click

.
New Session Bean dialog box gets open. It prompts us to enter EJB Name: , Project: , Location: , Package: , Session Type: and Create Interface: etc. Enter the values as shown in the fig below.

Step 4: Click




 

A new Stateless Session Bean gets created by name "TweetsFinder.java" in the "tweeter-ejb" module in the package provided at the time of creating the bean. It has most of the source code already generated by NetBeans. Kindly add or remove additional code provided below.


package com.hubberspot.ejb;

import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;

// @Stateless annotation provides container information to
// treat this Java class as a Stateless Session Bean.
@Stateless
public class TweetsFinder {

    // @PersistenceContext injects dependency for the EntityManager
    // by loading persistence.xml
    // EntityManager provides an interface for database persistence
    // such as to persist, merge , load and query objects.
    @PersistenceContext(name = "Tweeter-ejbPU")
    EntityManager tweetsManager;

    // This Stateless Session Bean has only one method
    // findAllTweets(). 
    public List< Tweet > findAllTweets() {

        // Here, it creates CriteriaQuery object
        // from EntityManager by calling its 
        // getCriteriaBuilder().createQuery() which returns 
        // back instance of CriteriaQuery.
        CriteriaQuery criteriaQuery = tweetsManager.getCriteriaBuilder().createQuery();

        // CriteriaQuery has two methods by name select()
        // and from which fetches data from database as 
        // normal SQL select query.        
        criteriaQuery.select(criteriaQuery.from(Tweet.class));

        // Creates a Query instance using criteriaQuery object
        // and EntityManager's createQuery() method.    
        Query query = tweetsManager.createQuery(criteriaQuery);

        // Finally it returns back list of tweets stored in 
        // database.    
        return query.getResultList();

    }
}





Video tutorial to demonstrate How to create a Java EE Stateless Session Bean (EJB) in an Enterprise Application using NetBeans.








In the next section of this blog (part 6) you will learn how to create a JSP page in NetBeans for this application in the Web module.



"Online Tweeter Enterprise Application" : Creating a Message-Driven Bean in NetBeans EJB module - Part 4


Lets continue building "Online Tweeter Enterprise Application" in NetBeans. In this section of tutorial, you will create a Message-Driven Bean by name "ReceiveTweets.java". A Message-Driven Bean is a enterprise bean that acts as a JMS message listener which process message coming on the queue or topic over which it is bound to listen.
In our "Online Tweeter Enterprise Application" it basically processes and stores the tweets sent by user from the servlet to the queue in database.

Step 1: Open "tweeter-ejb" project and right click Source Packages and then select New and than Other as shown in fig below:








Step 2: On clicking Other a dialog box appears by name New File. In the Categories: list select Enterprise JavaBeans and in the File Types: select Message-Driven Bean as shown in fig below.





Step 3: Click

.
New Message-Driven Bean dialog box gets open. It prompts us to enter values for EJB Name: , Project: , Location: , Package: , Project: , Destinations:. Enter the values as per fig below or enter what suits you.






Step 4: Click Add button to add a valid message destination. Add Message Destination dialog box gets open. Enter values for Destination Name: and Destination Type: as shown in fig below.





Step 5: Click



Previously opened New Message-Driven Bean dialog box gets open with the values entered for the Project Destinations: as shown in fig below.








Step 6:  After providing Project Destinations: click




 

A new Message-Driven Bean gets created by name "ReceiveTweets.java" in the "tweeter-ejb" module in the package provided at the time of creating the bean. It has most of the source code already generated by NetBeans. Kindly add or remove additional code provided below.


package com.hubberspot.ejb;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.ejb.MessageDrivenContext;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

// @MessageDriven annotation provides information to the container
// that this java class is a Message-Driven Bean. It has few 
// additional info about JNDI name of the destination to which
// this bean is listening.

// @ActivationConfigProperty annotation informs container about 
// the type of destination it is listening and the acknowledge
// mode.

// Message-Driven Bean must implement MessageListener which has a
// method onMessage() which gets triggered as soon as any message
// arrives over the queue.

@MessageDriven(mappedName = "jms/tweets", activationConfig = {
    @ActivationConfigProperty(propertyName = "acknowledgeMode", 
        propertyValue = "Auto-acknowledge"),
    @ActivationConfigProperty(propertyName = "destinationType", 
        propertyValue = "javax.jms.Queue")
})
public class ReceiveTweets implements MessageListener {
    
    // @Resource annotation injects the dependency for the resource
    // we intent to use. 
    
    @Resource
    MessageDrivenContext receiveTweetsContext;
    
    // @PersistenceContext injects dependency for the EntityManager
    // by loading persistence.xml
    // EntityManager provides an interface for database persistence
    // such as to persist, merge , load and query objects.
    
    @PersistenceContext(name="Tweeter-ejbPU")
    EntityManager tweetsManager;
    
    public ReceiveTweets() {
    }
    
    // The Object Message in the form of tweet entered
    // by the user in a Servlet is been persisted to 
    // database by EntityManager's persist() method.
    
    @Override
    public void onMessage(Message message) {
        
        ObjectMessage tweetMessage = null;
        
        if(message instanceof ObjectMessage) {
           
            try {
            
                tweetMessage = (ObjectMessage) message;
                
                Tweet tweet = (Tweet) tweetMessage.getObject();
                
                tweetsManager.persist(tweet);
            
            } catch (JMSException ex) {
           
                Logger.getLogger(ReceiveTweets.class.getName())
                        .log(Level.SEVERE, null, ex);
                receiveTweetsContext.setRollbackOnly();
            }
            
        }
        
    }
}




In the next section of this blog (part 5) you will learn how to create a Stateless Session Bean in NetBeans for this application.



"Online Tweeter Enterprise Application" : Creating an Entity Class in NetBeans EJB module - Part 3


Lets continue building "Online Tweeter Enterprise Application" in NetBeans. In this section of tutorial, you will create an Entity Class by name "Tweet.java". An Entity class is a simple POJO with annotations. It uses annotations like @Entity, @Id ... etc, which makes it persist in database as tables.

Step 1: Open "tweeter-ejb" project and right click Source Packages and then select New and than Other as shown in fig below:





Step 2: On clicking Other a dialog box appears by name New File. In the Categories: list select Persistence and in the File Types: select Entity Class as shown in fig below.




Step 3: Click

.
New Entity Class dialog box gets open. It prompts us to enter values for Class Name: , Project: , Location: , Package: , Created File: , Primary Key Type:. Enter the values as per fig below or enter what suits you.





and than just click
.

In the package provided at the time of creating Entity Class in the tweeter-ejb module Tweet.java gets created. It has most of the source code already generated by NetBeans. Kindly add or remove additional code provided below.

package com.hubberspot.ejb;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

// @Entity annotation is used to make a 
// Java class an Entity

@Entity
public class Tweet implements Serializable {

    private static final long serialVersionUID = 1L;

    // @Id annotation is used over the field which is
    // to be marked as primary key. Each entity class
    // needs to have this primary key.
    
    // @GeneratedValue annotation provides information
    // to the persistence provider to generate a way to
    // uniquely identify each instance of this entity class.
    // In order to do that it uses strategies for creating
    // new and unique id based on the strategy type.
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    
    private String username;
    private String tweet;

    public String getTweet() {
        return tweet;
    }

    public void setTweet(String tweet) {
        this.tweet = tweet;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }    

    public Long getId() {
        return id;
    }

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

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

    @Override
    public boolean equals(Object object) {
        
        if (!(object instanceof Tweet)) {
            return false;
        }
        Tweet other = (Tweet) object;
        if ((this.id == null && other.id != null) || 
                (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.hubberspot.ejb.Tweet[ id=" + id + " ]";
    }
    
}



Tweet.java has few properties such as tweet and username, which will be persisted in the database through getters and setters.

In the next section of this blog (part 4) you will learn how to create a Message Driven Bean in NetBeans for this application.

"Online Tweeter Enterprise Application" : Creating a Persistence Unit in NetBeans - Part 2

Lets continue building "Online Tweeter Enterprise Application" in NetBeans. In this section of tutorial, you will create a Persistence Unit which will group set of related entity beans. Persistence Unit is necessary to create a database connection and it allows our entity objects to get stored in database as tables.


Creating a Persistence Unit in NetBeans - Follow steps mentioned below :

Step 1: Before creating a Persistence Unit in NetBeans, create a database named "tweeter" into MySQL.

Step 2: Install and Open MySQL Command Line Client as shown in fig below:

 
















Step 3: MySQL Command Line Client window pops up. It asks for the password, just provide the password provided by you at the time of installation of MySQL.


Step 4: Run the following query also shown in fig below:

Create database tweeter;
 






















Step 5: After creating a database into MySQL lets move further by creating a Persistence Unit in NetBeans.
Open "tweeter-ejb" project and right click Source Packages and then select New and than Other as shown in fig below:







Step 6: On clicking Other a dialog box appears by name New File. In the Categories: list select Persistence and in the File Types: select Persistence Unit as shown in fig below.






























Step 7: Click


New Persistence Unit dialog box gets open. It prompts us to provide or create or enter "Persistence Unit Name: ", "Persistence provider: ", "Data Source: ", use of Java Transaction API and Table Generation Strategy etc... provide values to it according to the fig below.









 














Step 8: Don't click Finish. Lets create New Data Source. Select New Data Source from the list as shown in fig below:

























Step 9:  On clicking New Data Source, Create Data Source dialog box gets open as shown in the fig below. Just enter JNDI name for the Data Source and select New Database Connection from the list Database Connection:




Step 10: On clicking New Database Connection, New Connection Wizard dialog box gets open. It prompts us to enter information about the Driver and Driver File. Since for this application MySQL is the database choose from the drivers list MySQL (Connector/J driver). In the Driver File just click on Add button and add the required JDBC jar for MySQL as shown in fig below.






Step 11: Click


New Connection Wizard dialog box gets open which prompts us to enter information about Driver Name, Host, Port, Database, User Name, Password. Just provide information as shown in fig. For User Name and Password enter the information you provided at the time of installing MySQL Database Server.





























Step 12: Click


and than just click 



Step 13: Previous Create Data Source dialog box gets open having information about the newly created Data Source as shown in fig.



Step 14: Click



Previous New Persistence Unit dialog box gets open with the information about the Data Source as shown in fig below.



Step 15: Click



and Persistence Unit gets created having the necessary information in the persistence.xml file created by NetBeans (shown below) and placed in the Configuration Files folder in the Tweeter-ejb module.







    
  
    org.eclipse.persistence.jpa.PersistenceProvider
    jndi/tweeter
    false
    
      
    
  





In the next section of this blog (part 3) you will learn how to create an Entity Bean class in NetBeans for this application.

"Online Tweeter Enterprise Application" : Creating an Enterprise Application Project in NetBeans - Part 1

Lets start building "Online Tweeter Enterprise Application" in NetBeans from scratch.

Creating an Enterprise Application Project in NetBeans - Follow steps mentioned below :


Step 1: Open NetBeans 7.0 or above version.





Step 2: Go to File Menu and Select New Project 






























Step 3: On clicking New Project menu item, a New Project dialog box appears which prompts us to Choose Project. Select Java EE from the Categories: panel and Select Enterprise Application from Projects: panel as shown in below fig.



























Step 4: Click


New Enterprise Application dialog box gets open. It prompts us to provide Name and Location of the project.

a) Project Name: provide as shown in fig below

b) Project Location: provide as shown in fig below or you can provide as per your convenience.
c) Select the checkbox for "Use Dedicated Folder for Storing Libraries" and "Set as Main Project".  


   


Step 5: Click


A new dialog box opens for New Enterprise Application prompting us to provide Server and Settings details. Choose details as mentioned in the fig below.




Step 6: Click



Tweeter Project has been created in NetBeans IDE. As per diagram below NetBeans IDE creates three modules ie.

1. Tweeter 
2. Tweeter-ejb
3. Tweeter-war



In part 2 you will be able to Create a persistence Unit for application.

 
© 2021 Learn Java by Examples Template by Hubberspot