google Analytics

Wednesday, July 28, 2010

Ejb3 Stateful Bean Example

--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

@Stateful
@Remote(ShoppingCart.class)
public class ShoppingCartBean implements ShoppingCart, Serializable
{
private HashMap cart = new HashMap();

public void buy(String product, int quantity)
{
if (cart.containsKey(product))
{
int currq = cart.get(product);
currq += quantity;
cart.put(product, currq);
}
else
{
cart.put(product, quantity);
}
}

public HashMap getCartContents()
{
return cart;
}

@Remove
public void checkout()
{
System.out.println("To be implemented");
}
}



import java.util.HashMap;
import javax.ejb.Remove;

public interface ShoppingCart
{
void buy(String product, int quantity);

HashMap getCartContents();

@Remove void checkout();
}


public class Client
{
public static void main(String[] args) throws Exception
{
InitialContext ctx = new InitialContext();
ShoppingCart cart = (ShoppingCart) ctx.lookup("ShoppingCartBean/remote");

System.out.println("Buying 1 memory stick");
cart.buy("Memory stick", 1);
System.out.println("Buying another memory stick");
cart.buy("Memory stick", 1);

System.out.println("Buying a laptop");
cart.buy("Laptop", 1);

System.out.println("Print cart:");
HashMap fullCart = cart.getCartContents();
for (String product : fullCart.keySet())
{
System.out.println(fullCart.get(product) + " " + product);
}

System.out.println("Checkout");
cart.checkout();

System.out.println("Should throw an object not found exception by invoking on cart after @Remove method");
try
{
cart.getCartContents();
}
catch (javax.ejb.NoSuchEJBException e)
{
System.out.println("Successfully caught no such object exception.");
}


}
}

No comments:

Post a Comment