Sunday, 25 March 2018

Message Driven Demonstration

An EJB application that demonstrates MDB (with appropriate business logic)

package mybeans;


Step 1: Project Application Creation
                New -> New Folder -> Java EE -> Enterprise Application -> Name the application as you wish -> set Java EE Version as Java EE 5 -> Finish

Step 2: Creating connection factory and destination.
                Select  services window -> Start Glassfish Server -> right click on glassfishserver -> View admin console module -> JMS Resources -> Connection Factories -> New -> Set Pool name as jms/Queue and Resouce type as QueueConnectionFactory.Destination Resources -> New -> Set JNDI name as jms/dest and Resource type as queue -> rest can be anything

Step 3: Message Driven Bean Creation
                Right click on ejb module -> New -> Message Driven Bean -> Name the program ->Select destination as Server Destination (with the destination created by   you in admin console) -> Finish     Type the following code under onMeassage method
        TextMessage tmsg=null;
tmsg=(TextMessage)message;
System.out.println(tmsg.getText());
                Left Click the error icon on first line and select “Add import for javax.jms.TextMessage;
                Left click the error icon on third line and select “Surround the statement with try-catch”

Step 4: Servlet file creation
                Right click source Packages under war module -> New -> Servlet ->  Name the servlet -> next -> finish   Right click on the first line inside the class definition -> Insert code ->Send JMS message -> Select Message Driven bean -> set Connection Factory as
        “jms/queue”
                Type the following code in process request method
        String msg=request.getParameter("msg");
sendJMSMessageToDest(msg);
                Left click the error icon on third line and select “Surround the statement  with try-catch”

Step 5: JSP file Creation
                Create a jsp file with one label and one text box.
Step 6: Running the project
                Clean and Bulid the Application module -> Deploy the ejb module -> Right click Application module select run
                You can see the message displayed on server which is sent by you. 


//Lab12a.java in ejb module:

package lab12;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
@MessageDriven(mappedName = "jms/dest2", activationConfig = {
@ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),  @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue")
})
public class Lab12a implements MessageListener {   
public Lab12a() {
    }

    @Override
public void onMessage(Message message) {
        TextMessage tmsg=null;
tmsg=(TextMessage)message;
try {
System.out.println(tmsg.getText());
        } catch (JMSException ex) {
Logger.getLogger(Lab12a.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

//index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Lab 12 Message Driven Bean </title>
</head>
<body>
<form action="mdbServlet" >
<h1> Message Driven Bean </h1>
            Enter the Message: <input type="textbox" name="message" size="80"/><br/>
<input type="submit" name="Send"/>
<input type="reset" name="clear" value="clear">
</form>
</body>
</html>

//mdbServlet.java
package lab12;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class mdbServlet extends HttpServlet {
@Resource(mappedName = "jms/dest2")
private Queue dest2;
@Resource(mappedName = "jms/qe2")
private ConnectionFactory qe2;    
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 mdbServlet</title>"); 
out.println("</head>");
out.println("<body>");
             String msg=request.getParameter("message");
try {
sendJMSMessageToDest2(msg);
            } catch (JMSException ex) {
Logger.getLogger(mdbServlet.class.getName()).log(Level.SEVERE, null, ex);
            }
out.println("</body>");
out.println("</html>");            
        } finally {           
out.close();
        }
    }


    @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
    }    
    @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
    }    
    @Override
public String getServletInfo() {
return "Short description";
    }
private Message createJMSMessageForjmsDest2(Session session, Object messageData) throws JMSException {        
        TextMessage tm = session.createTextMessage();
tm.setText(messageData.toString());
return tm;
    }
private void sendJMSMessageToDest2(Object messageData) throws JMSException {
        Connection connection = null;
        Session session = null;
try {
connection = qe2.createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            MessageProducer messageProducer = session.createProducer(dest2);
messageProducer.send(createJMSMessageForjmsDest2(session, messageData));
        } finally {
if (session != null) {
try {
session.close();
                } catch (JMSException e) {
Logger.getLogger(this.getClass().getName()).log(Level.WARNING, "Cannot close session", e);
                }
            }
if (connection != null) {
connection.close();
            }
        }
    }
}


Session Bean Demonstation



 An EJB application that demonstrates Session Bean (with appropriate business logic)

1.overview
2. create a javaEE web application
3. create session bean
4. create servlet
5. create jsp
6. deploy the web application


1.overview

It covers creating a Session Bean and accessing it in a Web Application using JSPand Servlet.Enterprise JavaBeans technology is the server-side component architecturefor developing and deploying business applications in Java EE. The latest release of the technology, JSR 318: Enterprise JavaBeans 3.1, which is available in the Java EE 6platform, further simplifies the technology and makes many improvements.
There are two types of EJB components: Session beans and  Message-driven beans.  you will create a JEE 6 Web Application and add the following components to it - Stateless Session Bean, a Servlet, and a JSP. The  JSP will contain a form allowing you to specify a name. The form will submit to a Servlet which will read the name entered as the form parameter. The Servlet will pass the name to a sayHello method that is in the Session bean that you will create.

2. create a javaEE web application
To create a Java EE  Web Application, perform the following steps in the NetBeans IDE.
Create a new Web Application.
Select File->New Project from the NetBeans menu.
Select the Java Web category and a project type of  Web Application.
Click Next.

3. create session bean
To create a stateless session bean that is accessed using the local client access mode, perform the following steps in NetBeans IDE.Right-click on the prg11 project and select New->Other.
In the New File window, select a category of Enterprise JavaBeans and a file type of Session Bean.
Click Next.
Specify the Session Bean information as follows:
EJB Name: hello

Package Name: p11
Ensure Stateless is selected as the Session Type
Select  Local as the option for Create Interface.
Click Finish.
Double-click helloLocal.java in the Source Packages node to open  in the code editor.
Add the following line of code to the helloLocal interface to declare the sayHello method.
       String sayHello(String name) ;
Double-click hello.java in the Source Packages node to open  in the code editor.
Implement  sayHello method in the hello(SessionBean.)
public String sayHello(String name) {
return "Hello  " + name;
    }
4.create servlet
To create a Servlet, perform the below steps in NetBeans IDE.
Right-click on the prg11  project and select New->Other.
In the New File window, select a category of Web and a file type of Servlet.
Click Next.-->Specify the Servlet  information as follows:
Class Name: helloServlet
Package Name: hs
Click Finish.-->
Perform the following changes to the helloServlet.
a.  Import the following package.
import javax.ejb.EJB;

b. Add a field of type helloLocal named hello
 @EJB
private helloLocal hello;                     
---->
In the ProcessRequest method of SayHelloServlet, make the following changes.
a.  Add the below lines of code
String str1=request.getParameter("name");
String str2=hello.sayHello(str1);
b.  Add the below line of code to modify the HTML response produced by the
SayHelloServlet.
out.println("<h1>" + str2 + "</h1>");
5. Create a jsp
-------------------
To modify index.jsp, perform the following steps in NetBeans IDE.Open the existing index.jsp file from the Web Pages portion of the prg11 project.
Modify the title and heading of the page to Say Hello.
Add a form to the body of the index.jsp page which contains one text box  named  name and a submit button named OK.
<form  method="post" action="helloServlet">
            Enter Your Name: <input type="text" name="name">
<input type="submit" value="OK">
</form>

6.Deploy the web application
-------------------------------
To deploy and run the application, perform the following steps in NetBeans IDE.Right-click prg11 project in the projects window and select  Build. In the Projects window, right-click prg11 and select Run.
---------------------------------------------------------------------------


//index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title> Say Hello</title>
</head>
<body bgcolor="orange">
<h1>Say Hello!</h1>
<form  method="post" action="helloServlet">
            Enter Your Name: <input type="text" name="name">
<input type="submit" value="OK">
</form>
</body>
</html>


//helloServlet.java
package hs;
import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import p11.helloLocal;
@WebServlet(name = "helloServlet", urlPatterns = {"/helloServlet"})
public class helloServlet extends HttpServlet {   
    @EJB
private helloLocal hello;   
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String str1=request.getParameter("name");
String str2=hello.sayHello(str1);
response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
try {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet helloServlet</title>"); 
out.println("</head>");
out.println("<body>");
out.println("<h1>" + str2 + "</h1>");
out.println("</body>");
out.println("</html>");
                    } finally {           
out.close();
        }
    }

       @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
    }    
    @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
    }   
    @Override
public String getServletInfo() {
return "Short description";
    }


}
//hello.java
package p11;
import javax.ejb.Stateless;
@Stateless
public class hello implements helloLocal
{
    @Override
public String sayHello(String name)
    {
return "Hello  " + name;
    }
}


//helloLocal.java

package p11;
import javax.ejb.Local;
@Local
public interface helloLocal
{
    String sayHello(String name);     
}

Java and Mysql Connection


Write a JAVA Program to insert data into Student DATA BASE and retrieve info based on particular queries(For example update, delete, search etc…).

1.Analysis


construction of java program to which has to connect to mysql database by following the sequence of jdbc steps.

Import java.sql.* packages.

Load and register the JDBC driver

Open a connection to the database by creating a connection object.

Create a statement object to create a query.

Execute the statement object and return a query resultset.

Process the resultset.

Close the resultset and statement objects.

Close the connection.
               


2.Design


3.Implementation

package J2eeLabPrograms;

import java.sql.*;
import java.io.*;

class prg1
{
    public static void menu()  {
        System.out.println("Enter you Choice");
        System.out.println("1.Insert Student Details "+
                         "\n 2.Update Details" +
                         "\n 3.Delete Record"  +
                         "\n 4.Display Records"+
                         "\n 5.Exit ");
       System.out.println("--------------------");
    }

    public static void main(String args[])   {
    Connection con=null;
    Statement st=null;
    PreparedStatement pst=null;
    ResultSet rs=null;
    String str=null;
    String url="jdbc:mysql://localhost:3306/kumardb","root","";
   
     try{
             Class.forName("com.mysql.jdbc.Driver");
             con=DriverManager.getConnection(url,"","");
              DataInputStream in=new DataInputStream(System.in);
                        
             while(true) {
                  try{
                         menu();
                      int ch=Integer.parseInt(in.readLine());
                   switch(ch) {

    case 1:
                               System.out.println("Enter the name");
                          String name=in.readLine();
                               System.out.println("Enter the USN");
                          String usn=in.readLine();
                 System.out.println("Enter the Branch");
                          String branch=in.readLine();
                 System.out.println("Enter the Average marks");
                          int AvgMarks=Integer.parseInt(in.readLine());
               pst=con.prepareStatement("insert into student values(?,?,?,?)");
                         pst.setString(1,name);
                         pst.setString(2,usn);
                         pst.setString(3,branch);
                         pst.setInt(4,AvgMarks);
                         pst.executeUpdate();
                         break;
                         
                 case 2:
                         System.out.println("Enter the USN");
                         String u=in.readLine();
                         System.out.println("Enter the Name");
                         String n=in.readLine();
               String query = new String ("UPDATE student SET name = ? WHERE usn=?");
                           pst = con.prepareStatement(query);
                           pst.setString(1,n);
                         pst.setString(2,u);
                            int row=pst.executeUpdate();
                            if(row>0){ 
                              System.out.println("record updated successfully");
                             }
                         else{
                                System.out.println(" un successful");
                          }
                            break;
                
             case 3:
                          System.out.println("Enter the USN");
                          String u1=in.readLine();
              String q1 = new String ("delete from student  WHERE usn=?");
                          pst = con.prepareStatement(q1);
                        pst.setString(1,u1);
             int r=pst.executeUpdate();
                 if(r>0){ 
                 System.out.println("record updated successfully");
                  }
                 else{
                    System.out.println(" un successful");
}

                             break;

             case 4:
             System.out.println("Name \t USN \t Branch \t Avg Marks ");
             st=con.createStatement();
             rs=st.executeQuery("select * from student");
                         
             while(rs.next())
             {

                             System.out.println(rs.getString(1)+"\t"+
                                    rs.getString(2)+"\t "+
                                    rs.getString(3)+"\t\t"+
                                    rs.getInt(4)+"\t\t" );
             }
             System.out.println("--------------------------------------------");
             break;
                
             case 5:System.exit(0);
                 break;
             } // end of switch case
     } // end of inner try
             catch(SQLException e){
                         System.out.println(e.toString()+" Enter again");
             }
   } // end of while loop
} // end of outer try
            catch(ClassNotFoundException e){
                           System.out.println("Driver not found");
               }
   catch(SQLException e){
                           System.out.println(e);
               }
   catch(Exception e){
                           System.out.println(e);
               }
} // end of main
}


4.OUTPUT:

Enter you Choice
1.Insert Student Details
 2.Update Details
 3.Delete Record
 4.Display Records
 5.Exit
--------------------
1
Enter the name
syed
Enter the USN
1re13mca01
Enter the Branch
mca
Enter the Average marks
70
Enter you Choice
1.Insert Student Details
 2.Update Details
 3.Delete Record
 4.Display Records
 5.Exit
--------------------
4
Name    USN    Branch             Avg Marks
syed     1re13mca01     mca                 70                   
--------------------------------------------
Enter you Choice
1.Insert Student Details
 2.Update Details
 3.Delete Record
 4.Display Records
 5.Exit
--------------------
1
Enter the name
ravi D
Enter the USN
1re13mca02
Enter the Branch
mca
Enter the Average marks
75
Enter you Choice
1.Insert Student Details
 2.Update Details
 3.Delete Record
 4.Display Records
 5.Exit
--------------------
4
Name    USN    Branch             Avg Marks
syed     1re13mca01     mca                 70                   
ravi D  1re13mca02     mca                 75                   
--------------------------------------------
Enter you Choice
1.Insert Student Details
 2.Update Details
 3.Delete Record
 4.Display Records
 5.Exit
--------------------
2
Enter the USN
1re13mca01
Enter the Name
syed
record updated successfully
Enter you Choice
1.Insert Student Details
 2.Update Details
 3.Delete Record
 4.Display Records
 5.Exit
--------------------
2
Enter the USN
1re13mca01
Enter the Name
syed khutubuddin
record updated successfully
Enter you Choice
1.Insert Student Details
 2.Update Details
 3.Delete Record
 4.Display Records
 5.Exit
--------------------
4
Name    USN    Branch             Avg Marks
syed khutubuddin       1re13mca01     mca                 70                   
ravi D  1re13mca02     mca                 75                   
--------------------------------------------
Enter you Choice
1.Insert Student Details
 2.Update Details
 3.Delete Record
 4.Display Records
 5.Exit
--------------------
3
Enter the USN
1re13mca01
record updated successfully
Enter you Choice
1.Insert Student Details
 2.Update Details
 3.Delete Record
 4.Display Records
 5.Exit
--------------------
4
Name    USN    Branch             Avg Marks
ravi D  1re13mca02     mca                 75                   
--------------------------------------------
Enter you Choice
1.Insert Student Details
 2.Update Details
 3.Delete Record
 4.Display Records
 5.Exit
--------------------





PUBLISHER & SUBSCRIBER PATTERN

Using the UML Drawing Tool by implementing the code in Java demonstrate the Observer  Design Pattern. The Publisher-Subscriber desig...