Monday, October 13, 2014

Hibernate Application  Full code One to Many



One person has many Hats
In hat table create personId column
Hat class implement getters and setters for personId,Generate hat mapping file including personID.
Person class create hat collection
In person mapping file add Hat collection property


Souce pakage

Config file-:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.DerbyDialect</property>
    <property name="hibernate.connection.driver_class">org.apache.derby.jdbc.ClientDriver</property>
    <property name="hibernate.connection.url">jdbc:derby://localhost:1527/demo</property>
    <property name="hibernate.connection.username">app</property>
    <property name="hibernate.connection.password">app</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.current_session_context_class">thread</property>
    <mapping resource="hibernatedemo/Person.xml"/>
    <mapping resource="hibernatedemo/Hat.xml"/>
  </session-factory>
</hibernate-configuration>
--------------------------------------------------------------------------------------------------------------------------Current package
Hat.java

package hibernatedemo;

/**
 *
 * @author MANISHA
 */
public class Hat {

    private int hatid;
    private String color;
    private String size;
    private int personid;

// Getters and Setters
    public int getHatid() {
        return hatid;
    }

    public void setHatid(int hatid) {
        this.hatid = hatid;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public String getSize() {
        return size;
    }

    public void setSize(String size) {
        this.size = size;
    }

    public int getPersonid() {
        return personid;
    }

    public void setPersonid(int personid) {
        this.personid = personid;
    }

    public String toString() {
        return "Hat: " + getHatid()
                + " Color: " + getColor()
                + " Size: " + getSize();
    }
}
-------------------------------------------------------------------------------------------------------------------
Hat mapping file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="hibernatedemo.Hat" table="HAT">
        <id column="HATID" name="hatid">
            <generator class="increment"/>
        </id>
        <property column="PERSONID" name="personid"/>
        <property column="COLOR" name="color"/>
        <property column="SIZE" name="size"/>
  
    </class>
</hibernate-mapping>
----------------------------------------------------------------------------------------------------------------------
Project name use as Main file

Hibenatedemo.java

package hibernatedemo;

import java.util.Iterator;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author MANISHA
 */
public class HibernateDemo {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
//        Person p1 = new Person();
//        p1.setName("Saman");
//        p1.setAge(22);
//        createPerson(p1);
//        Person p3 = new Person();
//        p3.setName("Mani");
//        p3.setAge(31);
//        createPerson(p3);
//        listPerson();
//         p1.setAge(50);
//         updatePerson(p1);
//         listPerson();

        //select peaple above 45
     //   listPersonabove(45);

        Person p2 = new Person();
        p2.setName("Kate With Hats");
        p2.setAge(30);
        
        Hat h1 = new Hat();
        h1.setColor("Black");
        h1.setSize("Small");
        
        Hat h2 = new Hat();
        h2.setColor("White");
        h2.setSize("Large");
        
        p2.addHat(h1);
        p2.addHat(h2);
        
        createPerson(p2);
        listPerson();

    }

    private static void createPerson(Person person) {
        Transaction tx = null;
        Session session = SessionFactryUtil.getCurrentSession();
        try {
            tx = session.beginTransaction();
            session.save(person);
            tx.commit();
        } catch (RuntimeException e) {
            if (tx != null && tx.isActive()) {
                try {
// Second try catch as the rollback could fail as well
                    tx.rollback();
                } catch (HibernateException e1) {
                    System.out.println("Error rolling back transaction");
                }
// throw again the first exception
                throw e;
            }
        }
    }

    private static void updatePerson(Person person) {
        Transaction tx = null;
        Session session = SessionFactryUtil.getCurrentSession();
        try {
            tx = session.beginTransaction();
            session.update(person);
            tx.commit();
        } catch (RuntimeException e) {
            if (tx != null && tx.isActive()) {
                try {
// Second try catch as the rollback could fail as well
                    tx.rollback();
                } catch (HibernateException e1) {
                    System.out.println("Error rolling back transaction");
                }
// throw again the first exception
                throw e;
            }
        }
    }

    private static void deletePerson(Person person) {
        Transaction tx = null;
        Session session = SessionFactryUtil.getCurrentSession();
        try {
            tx = session.beginTransaction();
            session.delete(person);
            tx.commit();
        } catch (RuntimeException e) {
            if (tx != null && tx.isActive()) {
                try {
// Second try catch as the rollback could fail as well
                    tx.rollback();
                } catch (HibernateException e1) {
                    System.out.println("Error rolling back transaction");
                }
// throw again the first exception
                throw e;
            }
        }
    }

    private static void listPerson() {
        Transaction tx = null;
        Session session = SessionFactryUtil.getCurrentSession();
        try {
            tx = session.beginTransaction();
            List persons = session.createQuery(
                    "select p from Person as p").list();
            System.out.println("*** Content of the Person Table ***");
            System.out.println("*** Start ***");
            for (Iterator iter = persons.iterator(); iter.hasNext();) {
                Person element = (Person) iter.next();
                System.out.println(element);
            }
            System.out.println("*** End ***");
            tx.commit();
        } catch (RuntimeException e) {
            if (tx != null && tx.isActive()) {
                try {
// Second try catch as the rollback could fail as well
                    tx.rollback();
                } catch (HibernateException e1) {
                    System.out.println("Error rolling back transaction");
                }
                throw e;
            }
        }
    }

    private static void listPersonabove(int age) {
        Transaction tx = null;
        Session session = SessionFactryUtil.getCurrentSession();
        try {
            tx = session.beginTransaction();

            Query q = session.createQuery("select p from Person as p where p.age >:age");
            Person fooPerson = new Person();

            //using set propety in dummy person
            fooPerson.setAge(age);
            q.setProperties(fooPerson);
            List persons = q.list();

            System.out.println("*** Content of the Person Table ***");
            System.out.println("*** Start ***");
            for (Iterator iter = persons.iterator(); iter.hasNext();) {
                Person element = (Person) iter.next();
                System.out.println(element);
            }
            System.out.println("*** End ***");

            tx.commit();
        } catch (RuntimeException e) {
            if (tx != null && tx.isActive()) {
                try {
// Second try catch as the rollback could fail as well
                    tx.rollback();
                } catch (HibernateException e1) {
                    System.out.println("Error rolling back transaction");
                }
                throw e;
            }
        }
    }

}

------------------------------------------------------------------------------------------------------------------------
Person.java

package hibernatedemo;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 *
 * @author MANISHA
 */
public class Person {

    private int personid;
    private String name;
    private int age;

    public Set getHats() {
        return hats;
    }

    public void setHats(Set hats) {
        this.hats = hats;
    }

    //hat collection
    private Set hats;

    //default constructor with no argument
//
//    public Person() {
//    }
    public Person() {
        hats = new HashSet();
    }

    // Getters and Setters
    public void addHat(Hat hat) {
        this.hats.add(hat);
    }

    public void removeHat(Hat hat) {
        this.hats.remove(hat);
    }

    public String toString() {
        String personString = "Person: " + getPersonid()
                             + " Name: " + getName()
                             + " Age: " + getAge();
        String hatString = "";
        for (Iterator iter = hats.iterator(); iter.hasNext();) {
            Hat hat = (Hat) iter.next();
            hatString = hatString + "\t\t" + hat.toString() + "\n";
        }
        return personString + "\n" + hatString;
    }

    public int getPersonid() {
        return personid;
    }

    public void setPersonid(int personid) {
        this.personid = personid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

//    @Override
//    public String toString() {
//        return "Person: " + getPersonid()
//                + " Name: " + getName()
//                + " Age: " + getAge();
//    }
}

----------------------------------------------------------------------------------------------------------------------
Person.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="hibernatedemo.Person" table="PERSON">
        <id column="PERSONID" name="personid">
            <generator class="increment"/>
        </id>
        <property column="NAME" name="name"/>
        <property column="AGE" name="age"/>
        <set cascade="all" name="hats" table="HAT">
            <key column="PERSONID"/>
            <one-to-many class="hibernatedemo.Hat"/>
        </set>
    </class>
</hibernate-mapping>
-----------------------------------------------------------------------------------------------------------------------
package hibernatedemo;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

/**
 * Hibernate Utility class with a convenient method to get Session Factory
 * object.
 *
 * @author MANISHA
 */
public class SessionFactryUtil {

    private static final SessionFactory sessionFactory;

    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml) 
            // config file.
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Log the exception. 
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    /**
     * Opens a session and will not bind it to a session context
     *
     * @return the session
     */
    public static Session openSession() {
        return sessionFactory.openSession();
    }

    /**
     * Returns a session from the session context. If there is no session in the
     * context it opens a session, stores it in the context and returns it. This
     * factory is intended to be used with a hibernate.cfg.xml including the
     * following property <property
     * name="current_session_context_class">thread</property>
     * This would return the current open session or if this does not exist,
     * will create a new session
     *     
* @return the session
     */
    public static Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }

    /**
     * closes the session factory
     */
    public static void close() {
        if (sessionFactory != null) {
            sessionFactory.close();
        }
    }

}

--------------------------------------------------------------------------------------------------------------------------
run
















EJB+Hibernate

1.Create table inside sevice->java DB->new Database->name "myDB"->app->app

create table"Person"

id-int-PK
name-varchar(20),
age-int
ok->connct 

2.Create Java EE application
ejb->give a name->java 6.9.1->glasfish 3.1

3.ejb->new->newpkge->give name->other->entity class from databse->select table->if not new datasouce->select database->
jindi/dbname->ok->select pkg->finish.

4.delete all rather than attributes/getters/setters/only to string.
-----------------------------------------------------------------------------------------------------------------------
package er;

import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;


public class Person implements Serializable {
    private static final long serialVersionUID = 1L;
  
    private Integer id;
    private String name; 
    private Integer age;

    public Person() {
    }

    public Person(Integer id) {
        this.id = id;
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    
    @Override
    public String toString() {
        return "er.Person[ id=" + id + " ]";
    }
    
}

-----------------------------------------------------------------------------------------------------------------
2.Go to war file souce pakage to create hibernate packages 

3.Create Configuration file

souce pakge->new->other->hibernate->hibernate config wizard->give create db name->table.

Configurations->show.sql->true
Misalinius->thread.






4.Create Mapping file
sose pakge->new->other->hibernate->mapping wizard->type class name 1st later->p->select the class name with the pakage name "Person(pakge)"->ok->Select table->finish



go in side the 

<hibernate-mapping>
  <class name="er.Person" table="PERSON">
  <id column="ID" name="id">
            <generator class="increment"/>
        </id>
        <property column="NAME" name="name"/>
        <property column="AGE" name="age"/>
      
    </class>
  
  </class>
</hibernate-mapping>




Check class name,table name,columns,class attributes correct.

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


5.Go config->souce-------now mapping propety should there.

<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.DerbyDialect</property>
    <property name="hibernate.connection.driver_class">org.apache.derby.jdbc.ClientDriver</property>
    <property name="hibernate.connection.url">jdbc:derby://localhost:1527/myDB</property>
    <property name="hibernate.connection.username">app</property>
    <property name="hibernate.connection.password">app</property>
    <property name="hibernate.current_session_context_class">thread</property>
    <property name="hibernate.show_sql">true</property>
    <mapping resource="hibernate.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

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

5.Create Hibernate Util class

war->souce pakage->other->newhibernateutil->ok

need add relevent methods if not there.

import org.hibernate.Session;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;

public class NewHibernateUtil {

    private static final SessionFactory sessionFactory;
    
    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml) 
            // config file.
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Log the exception. 
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
    
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    
    public static Session openSession() {
        return sessionFactory.openSession();
    }
    
    public static Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }

    /**
     * closes the session factory
     */
    public static void close() {
        if (sessionFactory != null) {
            sessionFactory.close();
        }
    }
}

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

6.In side the jar add Hibernate 4.x libries

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

7.Drag and drop config and mapping file inside the ejb->souce pakage 

----------------------------------------------------------------------------------------------------------------------
8.add the util file inside current pakage which contains the classes.

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

9.Add java class

Name it as Personmanger


package er;

import javax.ejb.Stateless;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author MANISHA
 */

@Stateless

public class PersonManager {


    public  void createPerson(Person person) {
        Transaction tx = null;
//util class name has method getCurrentSession.

        Session session = NewHibernateUtil.getCurrentSession();

        try {
            tx = session.beginTransaction();
            session.save(person);
            tx.commit();
        } catch (RuntimeException e) {
            if (tx != null && tx.isActive()) {

                try {
// Second try catch as the rollback could fail as well
                 //   tx.rollback();
                } 

catch (HibernateException e1) {
                    System.out.println("Error rolling back transaction");
                }

// throw again the first exception
                throw e;
            }
        }

    }

}
------------------------------------------------------------------------------------------------------------------------

10.Go to war 

New other new pakage-> Servelet->Main

Go inside the main servelet


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

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet Main</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<a href='Show'>Book Details</a>");
            out.println("</body>");
            out.println("</html>");
        }
    }


-----------------------------------------------------------------------------------------------------------------
Click on the project->propeties->run->Set path-> /Main
-----------------------------------------------------------------------------------------------------------------

Create another Servlet->Name it as Show


Inside the Show class r8 Click ->Insert code->Call entprisebean->ejb->Select the class


package er;

import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author MANISHA
 */
@WebServlet(name = "Show", urlPatterns = {"/Show"})
public class Show extends HttpServlet {
    int Id=0;
    int Age=0.0;
    String name=null;
    int state=0;
    
    
    @EJB
    private PersonManager personManager;

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

        if (request.getParameter("id") != null) {
           Id = Integer.parseInt(request.getParameter("id").toString());
        }
        if (request.getParameter("age") != null) {
            Age = Integer.parseInt(request.getParameter("age").toString());
        }
      
            name = request.getParameter("name");
        
        
          if ((Id != 0) && (Age != 0) && (name != null) ) {
          
                 try {
              
                try {
                        Person b = new Person();
                        b.setId(Id);
                        b.setName(name);
                        b.setAge(Age);
                        
                        personManager.createPerson(b);
                        state=0;

                        } catch (Exception e) {
                        //catch (EJBException ex) {
                           state=1;
                           }
                
               //Give a servelet name if add move this servelet
                     response.sendRedirect("ListNews");
           
            } catch (Exception e) {
              //catch (EJBException ex) {
                            ex.printStackTrace();
            }
        }

---------------------------------------------------------------------------------------------------------------------
        PrintWriter out = response.getWriter();
        
        try  {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet Show</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h2>Add New person</h2>");
            out.println("<br/>");

            out.println("<form>");
            out.println("Id: <br/>");
            out.println("<input type='text' name='id'  id='id'><br/>");
            out.println("<br/>");
            out.println("Name: <br/>");
            out.println("<input type='text' name='name' id='name'><br/>");
            out.println("Age: <br/>");
            out.println("<input type='text' name='age' id='age' ><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>");
            out.println("</html>");
     } finally {
            out.close();
        }
    }
------------------------------------------------------------------------------------------------------------------
Run the application
http://localhost:8080/hiperEJB-war/Main




























Creating Web service in Java EE


Server 

ejb <- add new package-> name it.--->clicl on package->new Session bean->statelss->local->finish.

In side the page Right clik->add business method->

Method name:Converter
Add-Parameter1-value,,Select data type fom drop down (double)
Return type : double

public class Convert implements ConvertLocal {

    @Override
    public double CelciusConvrtr(double value) {
        return ((value*9/5)+35);
    }

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

war<-Add new package->other->webservices->webservice->give a name->select create webservice from existing session bean->brows->select creates session bean->finish->Deploy
----------------------------------------------------------------------------------------------------------------
war->webservices->new webservice->Test service

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

Client in Visual studio console

Get URL of generated WSDL

Cretae  console application->References->Add Service reference->Paste the URL->Click Go->OK

-------------------------------------------------------------------------------------------------------------------------
Main call the functions include in WSDL

WebserviceAppname-which dispay inside the references
ServicenameClient- .war pagename+Client

Main{
Webserviceappname.ServicenameClient dd=new Webserviceappname.Servicename();
       Console.writeline( dd.methodname(pass argument));
       Console.ReadLine();
}


Display on form(get the value from text box,Diplay Label)
private void button1_Click(object sender, EventArgs e)
        {
            ServiceReference1.tempConverterClient cc = new           ServiceReference1.tempConverterClient();
            label1.Text = cc.CtoF(Convert.ToDouble(textBox1.Text.ToString())).ToString();

        }
---------------------------------------------------------------------------------------------------------

Client in Net-beans console

Java application->add->webservices->webserviceclient->select WSDL url->Paste the URL
->finish

Go main page Click add new method by
Right click->Insert code->Call webservice method->Select the method you want

Call the method inside the main method(If there are parameters pass the relevent values)

----------------------------------------------------------------------------------------------------------
Reading a WSDL file


























Decrypt cypher text 


bcprov-ext-jdk15on-151-jar

Add this jar to library folder.

Start a java application.
Get a jframe and name it as main.java,


Add three text fields

type-To type the value
encypt-To display encyted code.
decrypt-To display decrypted cod.


public class Main extends javax.swing.JFrame {
    /**
     * encryption and decryption
     */
 
    byte[] input;
    byte[] keyBytes = "12345678".getBytes(); // our own key
    byte[] ivBytes = "input123".getBytes();
 
    SecretKeySpec key = new SecretKeySpec(keyBytes, "DES");
    IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
    Cipher cipher;
    byte[] chiperText;
    int ctLenght;
    /**
     * Creates new form Main
     */
    public Main() {
        initComponents();
    }


--------------------------------Encryption-----------------------------------------------------------------------------

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        try {
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); //type of security
            input = type.getText().getBytes();
            SecretKeySpec key = new SecretKeySpec(keyBytes, "DES");
            IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
            
            cipher = Cipher.getInstance("DES/CTR/NoPadding", "BC"); //CTR of encryption
            cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
            chiperText = new byte[cipher.getOutputSize(input.length)];
            ctLenght = cipher.update(input, 0, input.length, chiperText, 0);
            
            ctLenght += cipher.doFinal(chiperText, ctLenght);
            encrypt.setText(new String(chiperText));
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);
        }
    }             

------------------------------------------------------------Decription------------------------------------

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        try {
            cipher.init(Cipher.DECRYPT_MODE, key,ivSpec);
            byte[] plainText = new byte[cipher.getOutputSize(ctLenght)];
            int ptLength = cipher.update(chiperText, 0,ctLenght,plainText,0);
            
            ptLength += cipher.doFinal(plainText, ptLength);
            decrypt.setText(new String(plainText));
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);
        }
    }                                        
-------------------------------------------------------------------------------------------------------------------





















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.