EJB Tutorial from JBoss: Clustered Entity : Cluster « EJB3 « Java

Home
Java
1.2D Graphics GUI
2.3D
3.Advanced Graphics
4.Ant
5.Apache Common
6.Chart
7.Class
8.Collections Data Structure
9.Data Type
10.Database SQL JDBC
11.Design Pattern
12.Development Class
13.EJB3
14.Email
15.Event
16.File Input Output
17.Game
18.Generics
19.GWT
20.Hibernate
21.I18N
22.J2EE
23.J2ME
24.JavaFX
25.JDK 6
26.JDK 7
27.JNDI LDAP
28.JPA
29.JSP
30.JSTL
31.Language Basics
32.Network Protocol
33.PDF RTF
34.Reflection
35.Regular Expressions
36.Scripting
37.Security
38.Servlets
39.Spring
40.Swing Components
41.Swing JFC
42.SWT JFace Eclipse
43.Threads
44.Tiny Application
45.Velocity
46.Web Services SOA
47.XML
Java » EJB3 » Cluster 




EJB Tutorial from JBoss: Clustered Entity


File: Contact.java

/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2006, Red Hat Middleware LLC, and individual contributors
 * as indicated by the @author tags. See the copyright.txt file in the
 * distribution for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.jboss.tutorial.clusteredentity.bean;

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

import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;

/**
 *
 @author <a href="mailto:[email protected]">Kabir Khan</a>
 @version $Revision$
 */
@Entity
@Cache (usage=CacheConcurrencyStrategy.TRANSACTIONAL)
public class Contact implements Serializable
{
   Long id;
   String name;
   String tlf;
   Customer customer;
   
   public Contact()
   {
      
   }
   
   @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
   public Long getId()
   {
      return id;
   }

   public void setId(Long long1)
   {
      id = long1;
   }

   public String getName()
   {
      return name;
   }
   
   public void setName(String name)
   {
      this.name = name;
   }
   
   public String getTlf()
   {
      return tlf;
   }
   
   public void setTlf(String tlf)
   {
      this.tlf = tlf;
   }
   
   @ManyToOne
   @JoinColumn(name="CUST_ID")
   public Customer getCustomer()
   {
      return customer;
   }
   
   public void setCustomer(Customer customer)
   {
      this.customer = customer;
   }

}


File: Customer.java

/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2006, Red Hat Middleware LLC, and individual contributors
 * as indicated by the @author tags. See the copyright.txt file in the
 * distribution for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.jboss.tutorial.clusteredentity.bean;

import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue; import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;

import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;

/**
 * Company customer
 *
 @author Emmanuel Bernard
 @author Kabir Khan
 */
@Entity
@Cache (usage=CacheConcurrencyStrategy.TRANSACTIONAL)
public class Customer implements java.io.Serializable
{
   Long id;
   String name;
   private Set<Contact> contacts;

   public Customer()
   {
   }

   @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
   public Long getId()
   {
      return id;
   }

   public void setId(Long long1)
   {
      id = long1;
   }

   public String getName()
   {
      return name;
   }

   public void setName(String string)
   {
      name = string;
   }

   @Cache (usage=CacheConcurrencyStrategy.TRANSACTIONAL)
   @OneToMany(mappedBy="customer", fetch=FetchType.EAGER, cascade=CascadeType.ALL)
   public Set<Contact> getContacts()
   {
      return contacts;
   }

   public void setContacts(Set<Contact> contacts)
   {
      this.contacts = contacts;
   }
}



File: EntityTest.java

/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2006, Red Hat Middleware LLC, and individual contributors
 * as indicated by the @author tags. See the copyright.txt file in the
 * distribution for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.jboss.tutorial.clusteredentity.bean;

/**
 * Comment
 *
 @author <a href="mailto:[email protected]">Bill Burke</a>
 @version $Revision$
 */
public interface EntityTest
{
   Customer createCustomer();

   Customer findByCustomerId(Long id);
   
   boolean isCustomerInCache(Long id);
   boolean isContactInCache(Long id);
   boolean isCustomerContactsInCache(Long id);
}


File: EntityTestBean.java

/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2006, Red Hat Middleware LLC, and individual contributors
 * as indicated by the @author tags. See the copyright.txt file in the
 * distribution for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.jboss.tutorial.clusteredentity.bean;


import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.hibernate.cache.entry.CacheEntry;
import org.hibernate.cache.entry.CollectionCacheEntry;
import org.jboss.cache.CacheException;
import org.jboss.cache.Fqn;
import org.jboss.cache.Node;
import org.jboss.cache.TreeCache;
import org.jboss.cache.TreeCacheMBean;
import org.jboss.mx.util.MBeanProxyExt;
import org.jboss.mx.util.MBeanServerLocator;

/**
 * Comment
 *
 @author <a href="mailto:[email protected]">Bill Burke</a>
 @version $Revision$
 */
@Stateless
@Remote(EntityTest.class)
public class EntityTestBean implements EntityTest
{
   @PersistenceContext
   private EntityManager manager;

   public Customer createCustomer()
   {
      Customer customer = new Customer();
      customer.setName("JBoss");

      Set<Contact> contacts = new HashSet<Contact>();
      Contact kabir = new Contact();
      kabir.setCustomer(customer);
      kabir.setName("Kabir");
      kabir.setTlf("1111");
      contacts.add(kabir);

      Contact bill = new Contact();
      bill.setCustomer(customer);
      bill.setName("Bill");
      bill.setTlf("2222");
      contacts.add(bill);

      customer.setContacts(contacts);
      manager.persist(customer);
      return customer;
   }

   public Customer findByCustomerId(Long id)
   {
      return manager.find(Customer.class, id);
   }


   public boolean isCustomerInCache(Long id)
   {
      try
      {
         TreeCache cache = getCache();
         String key = "/org/jboss/tutorial/clusteredentity/bean/Customer/org.jboss.tutorial.clusteredentity.bean.Customer#" + id;
         return isInCache(cache, key);
      }
      catch (Exception e)
      {
         throw new RuntimeException(e);
      }
   }

   public boolean isContactInCache(Long id)
   {
      try
      {
         TreeCache cache = getCache();
         String key = "/org/jboss/tutorial/clusteredentity/bean/Contact/org.jboss.tutorial.clusteredentity.bean.Contact#" + id;

         return isInCache(cache, key);
      }
      catch (Exception e)
      {
         throw new RuntimeException(e);
      }
   }

   public boolean isCustomerContactsInCache(Long id)
   {
      try
      {
         TreeCache cache = getCache();
         String key = "/org/jboss/tutorial/clusteredentity/bean/Customer/contacts/org.jboss.tutorial.clusteredentity.bean.Customer.contacts#" + id;

         return isInCache(cache, key);
      }
      catch (Exception e)
      {
         throw new RuntimeException(e);
      }
   }

   private TreeCache getCache() throws Exception
   {
      MBeanServer server = MBeanServerLocator.locateJBoss();
      TreeCacheMBean proxy = (TreeCacheMBean)MBeanProxyExt.create(TreeCacheMBean.class, new ObjectName("jboss.cache:service=EJB3EntityTreeCache"), server);
      return proxy.getInstance();
   }

   private boolean isInCache(TreeCache cache, String key)throws CacheException
   {
      return isInCache(cache, null, key);
   }

   private boolean isInCache(TreeCache cache, Node node, String keythrows CacheException
   {
      //Not the best way to look up the cache entry, but how hibernate creates the cache entry
      //and fqn seems to be buried deep deep down inside hibernate...

      if (node == null)
      {
         node = cache.get("/");
      }

      Map map = node.getChildren();
      for(Object child : map.values())
      {
         Node childNode = (Node)child;

         Fqn fqn = childNode.getFqn();
         if (fqn.toString().equals(key))
         {
            Object entry = childNode.getData().get("item");
            return (entry != null&& (entry instanceof CacheEntry || entry instanceof CollectionCacheEntry);
         }

         Map children = childNode.getChildren();
         if (children != null && children.size() 0)
         {
            if (isInCache(cache, childNode, key))
            {
               return true;
            }
         }
      }

      return false;
   }
}

File: CachedEntityRun.java

/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2006, Red Hat Middleware LLC, and individual contributors
 * as indicated by the @author tags. See the copyright.txt file in the
 * distribution for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.jboss.tutorial.clusteredentity.client;

import java.util.Properties;
import java.util.Set;

import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.jboss.tutorial.clusteredentity.bean.Contact;
import org.jboss.tutorial.clusteredentity.bean.Customer;
import org.jboss.tutorial.clusteredentity.bean.EntityTest;

/**
 *
 @author <a href="mailto:[email protected]">Kabir Khan</a>
 @version $Revision$
 */
public class CachedEntityRun
{
   public static void main(String[] args)throws NamingException
   {
      if (args.length != 2)
      {
         throw new RuntimeException("You need to pass in two parameters of the type ipaddress:port");
      }

      Properties prop1 = new Properties();
      prop1.put("java.naming.factory.initial""org.jnp.interfaces.NamingContextFactory");
      prop1.put("java.naming.factory.url.pkgs""org.jboss.naming:org.jnp.interfaces");
      prop1.put("java.naming.provider.url""jnp://" + args[0]);

      Properties prop2 = new Properties();
      prop2.put("java.naming.factory.initial""org.jnp.interfaces.NamingContextFactory");
      prop2.put("java.naming.factory.url.pkgs""org.jboss.naming:org.jnp.interfaces");
      prop2.put("java.naming.provider.url""jnp://" + args[1]);

      System.out.println("Saving customer to node 1");
      InitialContext ctx1 = new InitialContext(prop1);

      EntityTest tester1 = (EntityTest)ctx1.lookup("EntityTestBean/remote");
      Customer customer = tester1.createCustomer();
      customer = tester1.findByCustomerId(customer.getId());

      System.out.println("Looking for customer in node 2's cache");
      InitialContext ctx2 = new InitialContext(prop2);

      EntityTest tester2 = (EntityTest)ctx1.lookup("EntityTestBean/remote");

      if(!tester2.isCustomerInCache(customer.getId()))
      {
         throw new RuntimeException("Could not find Customer in node2's cache");
      }
      System.out.println("Found customer " + customer.getId() " in node2 cache");

      if (!tester2.isCustomerContactsInCache(customer.getId()))
      {
         throw new RuntimeException("Could not find Customer contacts in node2's cache");
      }
      System.out.println("Found contacts collection for " + customer.getId() " in node2 cache");

      Set<Contact> contacts = customer.getContacts();

      for (Contact contact : contacts)
      {
         if (!tester2.isContactInCache(contact.getId()))
         {
            throw new RuntimeException("Could not find Contact in node2's cache");
         }
         System.out.println("Found contact " + contact.getId() " collection in node2 cache");
      }

      customer = tester2.findByCustomerId(customer.getId());
      if (customer == null)
      {
         throw new RuntimeException("Customer was not found in node 2");
      }
      System.out.println("Lookup of customer from node2 worked (via cache)");
      System.out.println("Customer: id=" + customer.getId() "; name=" + customer.getName());

      for (Contact contact : contacts)
      {
        System.out.println("\tContact: id=" + contact.getId() "; name=" + contact.getName());
    }

   }
}




           
       














jboss-EJB-3.0_RC9_Patch_1.zip( 10,289 k)
Related examples in the same category
1.EJB Tutorial from JBoss: clustering
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.