May 31, 2011

Java threads yield() method

The yield() method is a static method on the Thread class that causes the currently executing thread to go to the runnable state, yielding to a higher priority thread to become the current executing thread. Whether execution of the yield() method will produce the desired result is the prerogative of the Thread Scheduler.


package info.icontraining.threads;

public class MyRunnable implements Runnable {
 
   public static void main(String[] args) {
      Thread t = new Thread(new MyRunnable());
      t.start();
  
      for(int i=0; i<50; i++) {
         System.out.println("Inside main");
      }
   }
 
   public void run() {
      for(int i=0; i<50; i++) {
         System.out.println("Inside run");
         Thread.yield();
      }
   }
}

EJB3 Stateful Session Bean - Hello World Example

0) To setup an EJB3 project within an Enterprise Application (EAR) and deploy it to the JBoss Application Server, visit this link

1) In the MyEJBProject, create two classes - Account.java and AccountBean.java - within the ejbModule folder

Account.java


package info.icontraining.session;


import javax.ejb.*;


@Remote
public interface Account {


  public float deposit(float amount);
  public float withdraw(float amount);
  
  @Remove 
  public void remove();


}


AccountBean.java


package info.icontraining.session;


import javax.ejb.*;


@Stateful(name="AccountBean")
@Remote(Account.class)  
public class AccountBean implements Account {
   
    float balance = 0;


    public float deposit(float amount){
        balance += amount;
        return balance;
    }
 
    public float withdraw(float amount){
        balance -= amount;
        return balance;
    }

    @Remove  
    public void remove() {
        balance = 0;
    }
}


2) Within the web application, create two JSPs - accountForm.jsp and accountDetails.jsp - within the WebContent folder

accountForm.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1" %>


<html>
<body>


<h1><p align="center">Bank Transaction Form</p></h1>
<hr/><br/>

<form action="accountDetails.jsp" method="post">
  <table align="center"> 
   <tr><td>Enter the amount: <input type="text" name="amt" size="10"></td></tr>
   <tr><td><b>Select your choice:</b></td></tr>
   <tr><td><input type="radio" name="operation" value ="dep">Deposit</td></tr>
   <tr><td><input type="radio" name="operation" value ="with">Withdraw<br/></td></tr>
   <tr><td><input type="radio" name="operation" value ="balance">Check Balance<br/></td></tr>
   <tr><td><input type="submit" value="Submit"><input type="reset" value="Reset"></td></tr>
  </table>
</form>


</body>
</html>



accountDetails.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1" %>
<%@ page import="info.icontraining.session.*, javax.naming.*"%>


 <%!
     public Account account = null;
     float bal=0;


     public void jspInit() {
         try {
            InitialContext ic = new InitialContext();
            account = (Account) ic.lookup("MyEarApp/AccountBean/remote");
            System.out.println("Loaded Account Bean");
         } catch (Exception ex) {
            System.out.println("Error: "+ ex.getMessage());
         }
     }
    
     public void jspDestroy() {
        account = null;
     }
%>


   <%
    try {
       String s1 = request.getParameter("amt");
       String s2 = request.getParameter("operation");


       if (s1.equals("")) s1=null;
       
       if ( s1 != null) {
           Float amt  = new Float(s1);
                
           if(s2.equals("dep")) {
               bal=account.deposit(amt.floatValue());
               out.println("Balance is: " + bal);
               out.println("<br/><a href=accountForm.jsp>Go back</a>");


           } else if(s2.equals("with")) {
               bal=account.withdraw(amt.floatValue());
               out.println("Balance is: " + bal);
               out.println("<br/><a href=accountForm.jsp>Go back</a>");
           
           } else {        
   %>
             <p>Please select your choice</p>
                
   <%
           }
    } else {
   
           if (account != null) {  
   %>
           <p><b>Your Current Balance is:</b> <%= bal%><br/>
           <% out.println("<br/><a href=accountForm.jsp>Go back</a>"); %>
           <p>
   <%     
           }
     }
  } catch (Exception e) {
       e.printStackTrace();
  }
%>


3) Deploy the Enterprise Application comprising of the EJB Project and the Web Application.
Type the following URL in the browser and test the stateful session bean:

http://localhost:8080/MyEarApp/accountForm.jsp

EJB3 Stateless Session Bean - Hello World Example

1) Open Eclipse. Go to File > New > Project ...
Select EJB > EJB Project
Name the Project as MyEJBProject. Click Next.
Ensure that "EJB Module" with "3.0" as the version & "Java" with "5.0" as the version, checkboxes are ticked. Click Next. Click Finish.

2) In the MyEJBProject, create the following pieces of code within the ejbModule folder

HelloUser.java interface


package info.icontraining.session;


import javax.ejb.Local;


@Local  
public interface HelloUser {
      public String sayHello(String name);
}


HelloUserBean.java class



package info.icontraining.session;


import javax.ejb.Stateless;


@Stateless
public class HelloUserBean implements HelloUser {

      public String sayHello(String name) {
           return "Hello " + name + "! Welcome to EJB 3!";
      }
}


3) In your web application project (this is a different project compared to the EJB project just created above), add the following servlet code and configure it in the web.xml file

HelloUserClient.java servlet class


package info.icontraining.ejb.client;


import javax.naming.*;
import info.icontraining.session.*;
import java.io.*;
import java.util.Hashtable;
import javax.servlet.ServletException;
import javax.servlet.http.*;


public class HelloUserClient extends HttpServlet {


   public void doGet(HttpServletRequest req, HttpServletResponse res) 
                   throws ServletException, IOException {

       Hashtable env = new Hashtable(); 
       env.put("java.naming.factory.initial", 
                       "org.jnp.interfaces.NamingContextFactory");
       env.put("java.naming.factory.url.pkgs", 
                       "org.jboss.naming:org.jnp.interfaces"); 
       env.put("java.naming.provider.url","localhost:1099"); 


       PrintWriter out = res.getWriter();

       Context context;
       try {
           context = new InitialContext(env);

           HelloUser helloUser = (HelloUser) context.lookup("MyEarApp/" 
+ HelloUserBean.class.getSimpleName() + "/local");

           out.println(helloUser.sayHello("Dinesh"));

       } catch (NamingException e) {
           e.printStackTrace();
       }
   }      
}


web.xml configuration


<servlet>
    <servlet-name>HelloUserClient</servlet-name>
    <servlet-class>info.icontraining.ejb.client.HelloUserClient</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>HelloUserClient</servlet-name>
    <url-pattern>/helloUserClient</url-pattern>
</servlet-mapping>


4) Right-click on the Web Application Project and select the "Properties" menu item.
Select "Java Build Path" from the options on the left.
Click on the "Projects" Tab.
Click the "Add..." button; Tick the "MyEJBProject" checkbox. Click OK. Again, click OK.
Any build errors in the Web Application project / servlet class will get removed.

5) Click on the "File" menu item at the top.
Select New > Project ...
Choose "J2EE" and then "Enterprise Application Project". Click Next.
Name the project as "MyEarApp". Click Next.
Check the "MyEJBProject" and the Web Application Project as the 2 modules to be added within the Enterprise Application Project. Also, check the "Generate Deployment Descriptor" option.
Click Finish.

Note: In Eclipse Helios, after creating the Enterprise Application Project, right click on the project, select Properties. In the pop-up window, select "Deployment Assembly" on the left. Then click on the "Add..." button and select choose Project and click Next. Select the 2 projects - the EJB Project (MyEJBProject) and the web application project together (by pressing down the CTRL key). Click Finish.

6) Open the application.xml file within the new created EAR project - MyEarApp - within the EarContent/META-INF folder.
Modify the <context-root> element of the web application to /MyEarApp

7) Deploy the MyEarApp project to the JBoss Application Server and test the EJB by typing the following URL in the browser:

http://localhost:8080/MyEarApp/helloUserClient

Ajax with JSON response and Java JSON library on server-side

0) Add the org.json.jar file to the WebContent/lib folder of the web application - download the jar file from here

1) Create a JSP - getOrderInfoJson.jsp - within the WebContent folder of your web application. The JSP contains the Javascript code to retrieve the response payload in JSON format and convert it into a Javascript object and extract the response data to modify the HTML DOM.

<html>
<head>
<title>Get Customer Orders - JSON Example</title>
<script type="text/javascript">

var request = null;
function createRequest() {

   try {
      request = new XMLHttpRequest();
   } catch (trymicrosoft) {
      try {
         request = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (othermicrosoft) {
         try {
            request = new ActiveXObject("Microsoft.XMLHTTP");
         } catch (failed) {
            request = null;
         }
      }
   }
   if (request == null) {  
      alert("Error creating request object");   
   }
}

function checkOrder() {
   createRequest();
   request.open("POST", "jsonServlet", true);
   request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
   request.onreadystatechange = updatePage;
   request.send("customerId="+document.forms[0].elements[0].value);
}

var updatePage = function() {
   if (request.readyState == 4) {
      if (request.status == 200) {
         alert(request.responseText);
         var jsonCustomerObject = eval( "(" + request.responseText + ")");
    
         var toDisplay;
    
         toDisplay = "<span style='font-weight:bold;'> Customer Name:</span> " 
                  + jsonCustomerObject.realname + "<br/><br/>";

         toDisplay = toDisplay 
                  + "<span style='font-weight:bold;'>Order ID:</span> " 
                  + jsonCustomerObject.orders[0].id + "<br/>";
    
         toDisplay = toDisplay 
                  + "<span style='font-weight:bold;'>Date of Order:</span> " 
                  + jsonCustomerObject.orders[0].date + "<br/>";
    
         toDisplay = toDisplay 
                  + "<span style='font-weight:bold;'>Total Order Cost:</span> "  
                  + jsonCustomerObject.orders[0].cost + "<br/><br/>";
        
         toDisplay = toDisplay 
                  + "<span style='font-weight:bold;'>Details of Order</span> "  
                  + "<br/><br/>";
    
         for(var i=0; i<jsonCustomerObject.orders[0].items.length; i++) {

            toDisplay = toDisplay 
                  + "<span style='font-weight:bold;'>Item Id:</span> " 
                  + jsonCustomerObject.orders[0].items[i].id + "<br/>";
   
            toDisplay = toDisplay 
                  + "<span style='font-weight:bold;'>Item Name:</span> " 
                  + jsonCustomerObject.orders[0].items[i].name + "<br/>";
   
            toDisplay = toDisplay 
                  + "<span style='font-weight:bold;'>Item Price:</span> " 
                  + jsonCustomerObject.orders[0].items[i].price + "<br/>";
   
            toDisplay = toDisplay 
                  + "<span style='font-weight:bold;'>Item Description:</span> " 
                  + jsonCustomerObject.orders[0].items[i].description 
                  + "<br/>";
   
            toDisplay = toDisplay + "<br/><br/>";
         }
        
         document.getElementById('message').innerHTML = toDisplay;
      }
   }
}
</script>
</head>
<body>
<h1>Check Customer Order Information</h1>

<form>
   <label>Customer Id</label>: <input type="text" name="customerId" />
   <br/><br/>
   <input type="button" value="Submit" onclick="javascript:checkOrder();"/>
</form>
<br/>

<div id="message"></div>

</body>
</html>


2) Create a servlet - JsonServlet.java - within the src folder of the web application

import java.io.*;
import java.util.*;
import javax.servlet.http.*;
import org.json.*;

public class JsonServlet extends HttpServlet {
   public void doPost (HttpServletRequest req, HttpServletResponse res) 
      throws IOException {
      String custId = req.getParameter("customerId");
      Customer customer = getCustomer(custId);

      PrintWriter out = res.getWriter();
      res.setContentType("application/x-json");
      try {
         out.print(customer.toJSONObject());
         System.out.println(customer.toJSONObject());
      } catch (JSONException e) {
         e.printStackTrace();
      }
   }
   private Customer getCustomer(String id) {
      Item i1 = new Item();
      i1.setId("i-55768");
      i1.setDescription("512 Megabyte Type 1 CompactFlash card. Manufactured by Oolong Industries");
      i1.setName("Oolong 512MB CF Card");
      i1.setPrice(49.99);
      Item i2 = new Item();
      i2.setId("i-74491");
      i2.setDescription("7.2 Megapixel digital camera featuring six shooting modes and 3x optical zoom. Silver.");
      i2.setName("Fujak Superpix72 Camera");
      i2.setPrice(299.99);
      Item[] items = new Item[2];
      items[0] = i1;
      items[1] = i2;
      Order o1 = new Order();
      o1.setId("o-11123");
      o1.setCost(348.98);
      o1.setDate( new Date());
      o1.setItems(items);
      Order[] orders = new Order[1];
      orders[0] = o1;
      Customer c = new Customer();
      c.setRealname("Dinesh PC");
      c.setUsername("dinipc");
      c.setOrders(orders);

      return c;
   }
}

3) Configure the servlet in the web.xml file present within the WebContent/WEB-INF folder

<servlet>
    <servlet-name>jsonServlet</servlet-name>
    <servlet-class>JsonServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>jsonServlet</servlet-name>
    <url-pattern>/jsonServlet</url-pattern>
</servlet-mapping>


4) Add the classes - Customer.java,  Order.java and Item.java - within the src folder of the web application. These classes contain the toJSONObject() methods that use the org.json API methods to serialize the output response into the JSON format

import java.util.*;
import org.json.*;

public class Customer {
   private String username; 
   private String realname;
   private Order[] orders;
   public String getUsername() {
      return username;
   }
   public void setUsername(String username) {
      this.username = username;
   }

   public String getRealname() {
      return realname;
   }
   public void setRealname(String realname) {
      this.realname = realname;
   }

   public Order[] getOrders() {
      return orders;
   }

   public void setOrders(Order[] orders) {
      this.orders = orders;
   }

   public JSONObject toJSONObject() throws JSONException {

      JSONObject json = new JSONObject();
      json.put("realname", realname);
      json.put("username", username);
 
      JSONArray jsonItems = new JSONArray();
 
      for (int i=0; i<orders.length; i++ ) {
         jsonItems.put(orders[i].toJSONObject());
      }
 
      json.put("orders",jsonItems);

      return json;
   }

}


import java.util.*;
import org.json.*;

public class Order {
   private String id;
   private Date date;
   private double cost;
   private Item[] items;
   public String getId() {
      return id;
   }
   public void setId(String id) {
      this.id = id;
   }
   public Date getDate() {
      return date;
   }
   public void setDate(Date date) {
      this.date = date;
   }
   public double getCost() {
      return cost;
   }
   public void setCost(double cost) {
      this.cost = cost;
   }
   public Item[] getItems() {
      return items;
   }
   public void setItems(Item[] items) {
      this.items = items;
   }
   public JSONObject toJSONObject() throws JSONException {

      JSONObject json = new JSONObject();
      json.put("id", id);
      json.put("cost", cost);
      json.put("date", date.toString());

      JSONArray jsonItems = new JSONArray();
 
      for (int i=0; i<items.length; i++ ) {
         jsonItems.put(items[i].toJSONObject());
      }
      json.put("items",jsonItems);

      return json;
   }
}


import java.util.Iterator;
import org.json.*;

public class Item {
   private String id;
   private String name;
   private String description;
   private double price;
   public String getId() {
      return id;
   }
   public void setId(String id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getDescription() {
      return description;
   }
   public void setDescription(String description) {
      this.description = description;
   } 
   public double getPrice() {
      return price;
   }
   public void setPrice(double price) {
      this.price = price;
   }

public JSONObject toJSONObject() throws JSONException {

JSONObject json = new JSONObject();
json.put("id", id);
json.put("name", name);
json.put("description", description);
json.put("price", price);

return json;
}

}

5) Test the example with the following URL in the browser:

http://localhost:8080/WebAppName/jsonServlet