Java/EJB3/JBoss

Материал из Java эксперт
Версия от 06:50, 1 июня 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

EJB Tutorial from JBoss: Deployment descriptor

File: jboss.xml
<?xml version="1.0"?>
<jboss
        xmlns="http://java.sun.ru/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.ru/xml/ns/javaee
                            http://www.jboss.org/j2ee/schema/jboss_5_0.xsd"
        version="3.0">
  <enterprise-beans>
    <consumer>
          <ejb-name>ExampleConsumer</ejb-name>
           <ejb-class>org.jboss.tutorial.consumer_deployment_descriptor.bean.ExampleConsumerBean</ejb-class>
           <message-destination>queue/tutorial/example</message-destination>
         <message-destination-type>javax.jms.Queue</message-destination-type>
           <producer>
              <class>org.jboss.tutorial.consumer_deployment_descriptor.bean.ExampleProducerRemote</class>
           </producer>
           <local-producer>
              <class>org.jboss.tutorial.consumer_deployment_descriptor.bean.ExampleProducerXA</class>
              <connection-factory>java:/JmsXA</connection-factory>
           </local-producer>
           <local-producer>
        <class>org.jboss.tutorial.consumer_deployment_descriptor.bean.ExampleProducerLocal</class>
           </local-producer>
           <current-message>
        <method>
                   <method-name>currentMessage</method-name>
              </method>
           </current-message>
           <message-properties>
        <method>
             <method-name>method2</method-name>
            </method>
        <delivery>NonPersistent</delivery>
           </message-properties>
         </consumer>
  </enterprise-beans>
</jboss>





EJB Tutorial from JBoss: JBoss deployment descriptor

File: ejb-jar.xml
<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar
        xmlns="http://java.sun.ru/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.ru/xml/ns/javaee
                            http://java.sun.ru/xml/ns/javaee/ejb-jar_3_0.xsd"
        version="3.0">
   <description>JBoss Stateful Session Bean Tutorial</description>
   <display-name>JBoss Stateful Session Bean Tutorial</display-name>
   <enterprise-beans>
      <session>
         <ejb-name>ShoppingCart</ejb-name>
         <remote>org.jboss.tutorial.jboss_deployment_descriptor.bean.ShoppingCart</remote>
         <ejb-class>org.jboss.tutorial.jboss_deployment_descriptor.bean.ShoppingCartBean</ejb-class>
         <session-type>Stateful</session-type>
         <remove-method>
            <bean-method>
               <method-name>checkout</method-name>
            </bean-method>
            <retain-if-exception>false</retain-if-exception>
         </remove-method>
         <transaction-type>Container</transaction-type>
      </session>
   </enterprise-beans>
   <assembly-descriptor>
        <method-permission>
            <role-name>shopper</role-name>
            <method>
                <ejb-name>ShoppingCart</ejb-name>
                <method-name>buy</method-name>
            </method>
        </method-permission>
        <method-permission>
            <role-name>clerk</role-name>
            <method>
                <ejb-name>ShoppingCart</ejb-name>
                <method-name>priceCheck</method-name>
            </method>
        </method-permission>
   </assembly-descriptor>
</ejb-jar>

File: jaas-test-config.xml
<?xml version="1.0"?>
<!DOCTYPE policy PUBLIC
      "-//JBoss//DTD JBOSS Security Config 3.0//EN"
      "http://www.jboss.org/j2ee/dtd/security_config.dtd">
<policy>
    <application-policy name = "tutorial-test">
       <authentication>
          <login-module code = "org.jboss.security.auth.spi.UsersRolesLoginModule"
             flag = "required">
             <module-option name="usersProperties">security/users1.properties</module-option>
             <module-option name="rolesProperties">security/roles1.properties</module-option>
          </login-module>
       </authentication>
    </application-policy>
   <application-policy name = "tutorial-default">
      <authentication>
         <login-module code = "org.jboss.security.auth.spi.UsersRolesLoginModule"
            flag = "required">
            <module-option name="usersProperties">security/users2.properties</module-option>
            <module-option name="rolesProperties">security/roles2.properties</module-option>
         </login-module>
      </authentication>
   </application-policy>
</policy>

File: jboss.xml
<?xml version="1.0"?>
<jboss
        xmlns="http://java.sun.ru/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.ru/xml/ns/javaee
                            http://www.jboss.org/j2ee/schema/jboss_5_0.xsd"
        version="3.0">
    <security-domain>tutorial-default</security-domain>
  <enterprise-beans>
      <session>
           <ejb-name>ShoppingCart</ejb-name>
           <jndi-name>ShoppingCart</jndi-name>
           <clustered>true</clustered>
          <cluster-config>
              <partition-name>DefaultPartition</partition-name>
              <load-balance-policy>org.jboss.ha.framework.interfaces.RandomRobin</load-balance-policy>
           </cluster-config>
           <security-domain>tutorial-test</security-domain>
        </session>
        <session>
           <ejb-name>StatelessTest</ejb-name>
           <jndi-name>StatelessTest</jndi-name>
        </session>
     </enterprise-beans>
</jboss>

File: jboss-service.xml
<?xml version="1.0" encoding="UTF-8"?>
<server>
   <!-- The custom JAAS login configuration service that installs 
       a Configuration capable of dynamically updating the
       config settings
   -->
   <mbean code="org.jboss.security.auth.login.DynamicLoginConfig"
         name="jboss.tutorial:service=DynamicLoginConfig">
      <attribute name="AuthConfig">META-INF/jaas-test-config.xml</attribute>
      <depends optional-attribute-name="LoginConfigService">
         jboss.security:service=XMLLoginConfig
      </depends>
      <depends optional-attribute-name="SecurityManagerService">
         jboss.security:service=JaasSecurityManager
      </depends>
   </mbean>
</server>

File: application.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE application PUBLIC
   "-//Sun Microsystems, Inc.//DTD J2EE Application 1.3//EN"
   "http://java.sun.ru/dtd/application_1_3.dtd">
<application>
   <display-name>Tutorial</display-name>
   <module>
      <ejb>tutorial.jar</ejb>
   </module>
</application>





EJB Tutorial from JBoss: service deployment descriptor

File: jboss.xml
<?xml version="1.0"?>
<jboss
        xmlns="http://java.sun.ru/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.ru/xml/ns/javaee
                            http://www.jboss.org/j2ee/schema/jboss_5_0.xsd"
        version="3.0">
   <enterprise-beans>
      <service>
       <ejb-name>ServiceOne</ejb-name>
         <ejb-class>org.jboss.tutorial.service_deployment_descriptor.bean.ServiceOne</ejb-class>
         <local>org.jboss.tutorial.service_deployment_descriptor.bean.ServiceOneLocal</local>
         <remote>org.jboss.tutorial.service_deployment_descriptor.bean.ServiceOneRemote</remote>
         <management>org.jboss.tutorial.service_deployment_descriptor.bean.ServiceOneManagement</management>
         <jndi-name>serviceOne/remote</jndi-name>
         <local-jndi-name>serviceOne/local</local-jndi-name>
      </service>
      <service>
     <ejb-name>ServiceTwo</ejb-name>
         <ejb-class>org.jboss.tutorial.service_deployment_descriptor.bean.ServiceTwo</ejb-class>
       <object-name>tutorial:service=serviceTwo</object-name>
         <management>org.jboss.tutorial.service_deployment_descriptor.bean.ServiceTwoManagement</management>
      </service>
      <service>
     <ejb-name>ServiceThree</ejb-name>
         <ejb-class>org.jboss.tutorial.service_deployment_descriptor.bean.ServiceThree</ejb-class>
         <management>org.jboss.tutorial.service_deployment_descriptor.bean.ServiceThreeManagement</management>
      </service>
   </enterprise-beans>
</jboss>

File: jboss-service.xml
<?xml version="1.0" encoding="UTF-8"?>
<server>
   <mbean code="org.jboss.ejb3.test.service.Tester" name="jboss.ejb3:service=Tester,test=service"/>
</server>





Entry Point In ejb-jar.xml

File: EmployeeService.java

import java.sql.Connection;
import java.sql.PreparedStatement;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.sql.DataSource;
@Stateless
public class EmployeeService implements EmployeeServiceLocal, EmployeeServiceRemote {
  @PersistenceContext(unitName="EmployeeService")
  EntityManager em;
  
  @Resource(name="min") int minCheckNumber = 100;
  public EmployeeService() {
  }
  public void doAction(){
/*    Employee employee = new Employee();
    employee.setFirstName("E");
    employee.setLastName("E");
    em.persist(employee);
    employee.setLastName("New");
    em.merge(employee);
    
    em.remove(employee);
    
    em.flush();
    System.out.println("saved");
    
    
    List list = em.createQuery("FROM Employee p").getResultList();
    */
 
  }
}
    

File: EmployeeServiceLocal.java

import java.util.Collection;
import javax.ejb.Local;
@Local
public interface EmployeeServiceLocal {
    public void doAction();
}

File: EmployeeServiceRemote.java


import java.util.Collection;
import javax.ejb.Remote;
@Remote
public interface EmployeeServiceRemote{
  public void doAction();  
}

File: EntityListener.java

import javax.persistence.PostLoad;
import javax.persistence.PostPersist;
import javax.persistence.PostRemove;
import javax.persistence.PostUpdate;
public class EntityListener
{
   @PostUpdate
   public void update(Object entity)
   {
      System.out.println("@PostUpdate: " + entity.getClass().getName());
   }
   @PostPersist
   public void persist(Object entity)
   {
      System.out.println("@PostPersist: " + entity.getClass().getName());
   }
   @PostLoad
   public void load(Object entity)
   {
      System.out.println("@PostLoad: " + entity.getClass().getName());
   }
      
   @PostRemove
   public void remove(Object entity)
   {
      System.out.println("@PostRemove: " + entity.getClass().getName());
   }
  
}

File: Employee.java
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.PostRemove;
@Entity
@EntityListeners(EntityListener.class)
public class Employee implements java.io.Serializable {
  private int id;
  private String firstName;
  private String lastName;
  @Id
  @GeneratedValue
  public int getId() {
    return id;
  }

  @PostRemove
  public void postRemove()
  {
     System.out.println("@PostRemove");
  }
  public void setId(int id) {
    this.id = id;
  }
  public String getFirstName() {
    return firstName;
  }
  public void setFirstName(String first) {
    this.firstName = first;
  }
  public String getLastName() {
    return lastName;
  }
  public void setLastName(String last) {
    this.lastName = last;
  }
}

File: Main.java
import java.util.Collection;
import javax.naming.InitialContext;

public class Main {
  public static void main(String[] a) throws Exception {
    EmployeeServiceRemote service = null;
    // Context compEnv = (Context) new InitialContext().lookup("java:comp/env");
    // service = (HelloService)new InitialContext().lookup("java:comp/env/ejb/HelloService");
    service = (EmployeeServiceRemote) new InitialContext().lookup("EmployeeService/remote");
    
    
    
    
    service.doAction();
  }
}

File: jndi.properties
java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
java.naming.provider.url=localhost:1099





Use JBoss Enterprise Beans Session Config

File: Employee.java
import static javax.persistence.FetchType.LAZY;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
@Entity
//@Table(name="EMP", schema="HR")
@Table(name="EMP")
public class Employee implements Serializable {
  @Id
  @Column(name = "EMP_ID")
  private int id;
  @Column(name = "COMM")
  private String name;
  @Column(name = "SAL")
  private long salary;
  @Basic(fetch=LAZY)
  @Lob @Column(name="PIC")
  private byte[] picture;
  
  public Employee() {
  }
  public Employee(int id) {
    this.id = id;
  }
  public int getId() {
    return id;
  }
  public void setId(int id) {
    this.id = id;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public long getSalary() {
    return salary;
  }
  public void setSalary(long salary) {
    this.salary = salary;
  }
  public byte[] getPicture() {
    return picture;
  }
  public void setPicture(byte[] picture) {
    this.picture = picture;
  }
  public String toString() {
    return "Employee id: " + getId() + " name: " + getName() + " salary: " + getSalary();
  }
}

File: EmployeeService.java

import java.util.Collection;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
@Stateless
public class EmployeeService implements EmployeeServiceLocal, EmployeeServiceRemote {
  @PersistenceContext(unitName="EmployeeService")
  EntityManager em;
  
  public EmployeeService() {
  }
  public Employee createEmployee(int id, String name, long salary, byte[] pic) {
    Employee emp = new Employee(id);
    emp.setName(name);
    emp.setSalary(salary);
    emp.setPicture(pic);
    
    em.persist(emp);
    
    
    emp = findEmployee(id);
    System.out.println(emp);
    
    return emp;
  }
  public void removeEmployee(int id) {
    Employee emp = findEmployee(id);
    if (emp != null) {
      em.remove(emp);
    }
  }
  public Employee raiseEmployeeSalary(int id, long raise) {
    Employee emp = em.find(Employee.class, id);
    if (emp != null) {
      emp.setSalary(emp.getSalary() + raise);
    }
    return emp;
  }
  public Employee findEmployee(int id) {
    return em.find(Employee.class, id);
  }
  public Collection<Employee> findAllEmployees() {
    Query query = em.createQuery("SELECT e FROM Employee e");
    return (Collection<Employee>) query.getResultList();
  }
  
  public void doAction(){
    Employee emp = new Employee(1);
    emp.setName("name");
    emp.setSalary(100);
    emp.setPicture("pic".getBytes());
    
    em.persist(emp);
    
    
    emp = findEmployee(1);
    System.out.println(emp);
  }
}
    

File: EmployeeServiceLocal.java

import javax.ejb.Local;
@Local
public interface EmployeeServiceLocal {
    public void doAction();
  public Employee createEmployee(int id, String name, long salary, byte[] pic) ;
}

File: EmployeeServiceRemote.java


import javax.ejb.Remote;
@Remote
public interface EmployeeServiceRemote{
  public Employee createEmployee(int id, String name, long salary, byte[] pic) ;
  
  public void doAction();
}

File: jndi.properties
java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
java.naming.provider.url=localhost:1099

File: Main.java
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;
public class Main {
  public static void main(String[] a) throws Exception {

    // Context compEnv = (Context) new InitialContext().lookup("java:comp/env");
    // service = (HelloService)new InitialContext().lookup("java:comp/env/ejb/HelloService");
    Object obj = new InitialContext().lookup("EmployeeServiceRemote");
    
    EmployeeServiceRemote service = (EmployeeServiceRemote)PortableRemoteObject.narrow(obj,EmployeeServiceRemote.class);
    
    service.createEmployee(158, "AAA", 45000, "asdf".getBytes());
    service.doAction();
  }
}





Use JBoss Remote Binding

File: EmployeeService.java

import java.util.Collection;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.jboss.annotation.ejb.RemoteBinding;
@Stateless
@RemoteBinding(jndiBinding="EmployeeServiceRemote")
public class EmployeeService implements EmployeeServiceLocal, EmployeeServiceRemote {
  @PersistenceContext(unitName="EmployeeService")
  EntityManager em;
  
  public EmployeeService() {
  }
  public Employee createEmployee(int id, String name, long salary, byte[] pic) {
    Employee emp = new Employee(id);
    emp.setName(name);
    emp.setSalary(salary);
    emp.setPicture(pic);
    
    em.persist(emp);
    
    
    emp = findEmployee(id);
    System.out.println(emp);
    
    return emp;
  }
  public void removeEmployee(int id) {
    Employee emp = findEmployee(id);
    if (emp != null) {
      em.remove(emp);
    }
  }
  public Employee raiseEmployeeSalary(int id, long raise) {
    Employee emp = em.find(Employee.class, id);
    if (emp != null) {
      emp.setSalary(emp.getSalary() + raise);
    }
    return emp;
  }
  public Employee findEmployee(int id) {
    return em.find(Employee.class, id);
  }
  public Collection<Employee> findAllEmployees() {
    Query query = em.createQuery("SELECT e FROM Employee e");
    return (Collection<Employee>) query.getResultList();
  }
  
  public void doAction(){
    Employee emp = new Employee(1);
    emp.setName("name");
    emp.setSalary(100);
    emp.setPicture("pic".getBytes());
    
    em.persist(emp);
    
    
    emp = findEmployee(1);
    System.out.println(emp);
  }
}
    

File: EmployeeServiceLocal.java

import javax.ejb.Local;
@Local
public interface EmployeeServiceLocal {
    public void doAction();
  public Employee createEmployee(int id, String name, long salary, byte[] pic) ;
}

File: EmployeeServiceRemote.java


import javax.ejb.Remote;
@Remote
public interface EmployeeServiceRemote{
  public Employee createEmployee(int id, String name, long salary, byte[] pic) ;
  
  public void doAction();
}

File: Employee.java
import static javax.persistence.FetchType.LAZY;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
@Entity
//@Table(name="EMP", schema="HR")
@Table(name="EMP")
public class Employee implements Serializable {
  @Id
  @Column(name = "EMP_ID")
  private int id;
  @Column(name = "COMM")
  private String name;
  @Column(name = "SAL")
  private long salary;
  @Basic(fetch=LAZY)
  @Lob @Column(name="PIC")
  private byte[] picture;
  
  public Employee() {
  }
  public Employee(int id) {
    this.id = id;
  }
  public int getId() {
    return id;
  }
  public void setId(int id) {
    this.id = id;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public long getSalary() {
    return salary;
  }
  public void setSalary(long salary) {
    this.salary = salary;
  }
  public byte[] getPicture() {
    return picture;
  }
  public void setPicture(byte[] picture) {
    this.picture = picture;
  }
  public String toString() {
    return "Employee id: " + getId() + " name: " + getName() + " salary: " + getSalary();
  }
}

File: jndi.properties
java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
java.naming.provider.url=localhost:1099

File: Main.java
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;
public class Main {
  public static void main(String[] a) throws Exception {

    // Context compEnv = (Context) new InitialContext().lookup("java:comp/env");
    // service = (HelloService)new InitialContext().lookup("java:comp/env/ejb/HelloService");
    Object obj = new InitialContext().lookup("EmployeeServiceRemote");
    
    EmployeeServiceRemote service = (EmployeeServiceRemote)PortableRemoteObject.narrow(obj,EmployeeServiceRemote.class);
    
    service.createEmployee(158, "AAA", 45000, "asdf".getBytes());
    service.doAction();
  }
}