Tuesday, October 9, 2012

Java Random number generation of 4 digits

import java.util.Random;

System.out.println("***** Generating Random Number of 4 digit *****");
Random random = new Random();
for(int i=0;i<100;i++){
    long fraction = (long)(1000 * random.nextDouble());
    int PIN= (int)(fraction + 1000);
    System.out.println(PIN);
 }

Struts2 why more powerful than Struts1. Struts2 Vs Struts1 . Compare between Struts1 and Struts2

STRUTS2 = STRUTS1 + Interceptor (=XWork) + OGNL - FormBean

1. Easy web.xml

STRUTS1:

<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
   <param-name>config</param-name>
   <param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

STRUTS2:

<filter>
<filter-name>webwork</filter-name>
<filter-class>
   org.apache.struts.action2.dispatcher.FilterDispatcher
</filter-class>
</filter>

<filter-mapping>
<filter-name>webwork</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>


No struts-config.xml inside WEB-INF folder.

2. Easy Action Class.

STRUTS1:
public class MyAction extends Action {
    public ActionForward execute(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response)
            throws Exception {
        // do the work
        return (mapping.findForward("success"));
    }
}

All actions have to be thread-safe, as only a single action instance is created.
Struts 1 Actions are singletons and must be thread-safe since there will only be one instance of a class to handle all requests for that Action.
Because the actions have to be thread-safe, all the objects that may be needed in the processing of the action are passed in the method signature.

STRUTS2:
Struts 2 Action objects are instantiated for each request, so there are no thread-safety issues.
public class MyAction {
   public String execute() throws Exception {
        // do the work
        return "success";
   }
}

Here no need to extends other class and no need to pass every thing in execute method.

If you want to use any session or request ro response object then use xxxxAware, example:
public class MyAction implements ServletRequestAware {
   private HttpServletRequest request;
   public void setServletRequest(HttpServletRequest request) {
        this.request = request;
   }
   public String execute() throws Exception {
        // do the work using the request
        return Action.SUCCESS;
   }
}

3. No Action From

STRUTS1:
Struts 1 uses an ActionForm object to capture input. Like Actions, all ActionForms must extend a base class. Since  other JavaBeans cannot be used as ActionForms, developers often create redundant classes to capture input. DynaBeans can used as an alternative to creating conventional ActionForm classes, but, here too, developers may be redescribing existing JavaBeans.

STRUTS2:
All data of ActionForm will do here in action class, so need to create one more class.The Action properties can be accessed from the web page via the taglibs.

4. Advanced Expression Language:

STRUTS1:

Struts 1 integrates with JSTL, so it uses the JSTL EL. The EL has basic object graph traversal, but relatively weak collection and indexed property support.

STRUTS2:
Struts 2 can use JSTL, but the framework also supports a more powerful and flexible expression language called "Object Graph Notation Language" (OGNL).

5. Easy Validation

STRUTS1:
Struts 1 supports manual validation via a validate method on the ActionForm, or through an extension to the Commons Validator.

STRUTS2:
Struts 2 supports manual validation via the validate method and the XWork Validation framework. The Xwork Validation Framework supports chaining validation into sub-properties using the validations defined for the properties class type and the validation context.

First Example on Struts2, Struts2 Tutorial, Struts2 Easy Example

First Example on Struts2:

1. Create one Dynamic Project in Eclipse Say Struts2
2. Put all these below jar file inside WEB-INF\lib folder
struts2-core-2.0.6.jar
xwork-2.0.1.jar
commons-logging-1.1.jar
freemarker-2.3.8.jar
ognl-2.6.11.jar


3. Change your web.xml (WEB-INF\web.xml) file as below:
web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Struts2 First Example </display-name>
<filter>
   <filter-name>struts2</filter-name>
   <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>

<filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
</welcome-file-list>

</web-app>



4. In Struts2/src folder, put these two file:
ClientAction.java

import com.opensymphony.xwork2.ActionSupport;

public class ClientAction extends ActionSupport{

String name;

public String getName(){
return name;
}

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

public String execute() throws Exception{
if(getName().equals("")){
      return ERROR;
        }
else{
return SUCCESS;
}
}

}

struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
  <include file="struts-default.xml"/>
  <package name="default" extends="struts-default">

<action name="clientAction" class="ClientAction">
<result name="success">/client.jsp</result>
<result name="error">/error.jsp</result>
<result name="input">/error.jsp</result>
</action>
   </package>
</struts>


5. Write some jsp file inside Struts2\WebContent
index.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<body>
  <s:form action="clientAction" method="post">
      <s:textfield label="Name" name="name"/>
    <s:submit/>
  </s:form>

  </body>
</html>

client.jsp

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<body>
Thank you! <b><s:property value="name"/></b>.
<br><br>
</body>
</html>

error.jsp

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
  <title>Some Error</title>
  <link rel="stylesheet" href="mystyle.css" type="text/css" />
</head>
<body>
<h1>Error!</h1>
This error page is being shown because any of following reasons:
<ul class="boldred">
<li>Field(s) left blank.</li>
<li>Invalid Data Entered.(For example: String in place of Integer.)</li>
</ul>
</body>
</html>

That's it .........

Add any application Server inside the Eclipse and run .....
If you are getting some error that might be for update code.
So, In Eclipse bottom tab one Server tab is there -> locate your application server -> then right click on Struts1 (Project) -> click on "Clean Module Work Directory".

Now go to internet explorer and type URL:

http://localhost:8080/Struts2

and type your name in text box, you should suppose to get output like this

Thank you! Your Name.

Struts2 example with Annotation. Struts 2 with annotation. First Struts 2 with annotation.

1. Create one Dynamic Project in Eclipse Say StrutsAnno
2. Put all these below jar file inside WEB-INF\lib folder
struts2-core-2.1.6.jar
xwork-2.1.2.jar
commons-logging-1.1.jar
freemarker-2.3.8.jar
ognl-2.6.11.jar
struts2-convention-plugin-2.1.6.jar


3. Change your web.xml (WEB-INF\web.xml) file as below:

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Struts2 First Example </display-name>
<filter>
   <filter-name>struts2</filter-name>
   <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>

<filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
</welcome-file-list>

</web-app>


There is no use of struts.xml if you use Annotation. :)

4. Create one package inside src folder say binod.suman
UserAction.java (StrutsAnno\src\binod\suman\UserAction.java)

package binod.suman;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

public class WelcomeUserAction {
private String userName;
private String message;

@Action(value="/welcome",results={@Result(name="success",location="/successPage.jsp"),@Result(name="error",location="/error.jsp")})
public String execute() {
message = "Welcome " + userName + " !";
System.out.println("Message : "+message);
if(userName.equals("Binod")){
 return "success";
}else{return "error";}
}

public void setUserName(String userName) {
this.userName = userName;
}

public void setMessage(String message) {
this.message = message;
}

public String getUserName() {
return userName;
}

public String getMessage() {
return message;
}
}


5. These below JSP page inside the WebContent
index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="/struts-tags" prefix="s" %>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Hello World</title>
    </head>
    <body>
        <s:form action="welcome" >
            <s:textfield name="userName" label="User Name" />
            <s:submit />
        </s:form>
    </body>
</html>


error.jsp

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
  <title>Some Error</title>
  <link rel="stylesheet" href="mystyle.css" type="text/css" />
</head>
<body>
<h1>Error!</h1>
This error page is being shown because any of following reasons:
<ul class="boldred">
<li>Field(s) left blank.</li>
<li>Invalid Data Entered.(For example: String in place of Integer.)</li>
</ul>

<h1> You have entered <font color="red"> <b><s:property value="userName"/></b> </font> but you should suppose to enter <b>Binod</b> </h1>
</body>
</html>


successPage.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome User</title>
</head>
<body>
<b><s:property value="message"/></b>.
</body>
</html>


Only one web.xml, one java class and some jsp pages.

http://localhost:8080/StrutsAnno/

Put UserName Balaram
Output:
Welcome Balaram !.

Simple Ajax with JQuery

 First I will write code with native Ajax then will write same code using Ajax.

The code below for add two number. There will be two text box on jps page and user has to enter first number and click on Add button then it will add first text box and second box number and will be showed to second text box. One clear button is also there to clear both text boxes.

Back side (Server side) will be came in both ways.

Pure (Native) Ajax:

var request;

function getRequest(){
      if(window.ActiveXObject){
        request = new ActiveXObject("Microsoft.XMLHTTP");
       }else if(window.XMLHttpRequest){
        request = new XMLHttpRequest();
      }
    }

function addAction(){
 var first = document.getElementById("firstNumber").value;
 if(first==null||first==""){
alert("Please enter first number");
return null;
 }
 var second = document.getElementById("secondNumber").value;
 if(second==null||second==""){
second = 0;
 }
 calculation(first, second, "add");
}

function calculation(first, second, operation){
 getRequest();
 var url = "http://localhost:8080/Calculator/Calculator?first="+first+"&second="+second+"&operation="+operation;
 request.open("POST",url,false);
 request.onreadystatechange = showResult;
 request.send();
}

function calculation2(first, second, operation){
getRequest();
var url = "http://localhost:8080/Calculator/Calculator";
     request.open("POST",url,false);
request.onreadystatechange = showResult;
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.send("first="+first+"&second="+second+"&operation="+operation); // Why Null
 }

function showResult(){

if(request.readyState == 4){
        var result = request.responseText;
        document.getElementById("secondNumber").value = result;
   }

}
function clearInput(){
document.getElementById("firstNumber").value="";
document.getElementById("secondNumber").value="";
}

JQuery Ajax code:

$(document).ready(function(){
$('#clearButton').click(function(){
$('#firstNumber').val('');
$('#secondNumber').val('');
});

$('#addButton').click(function(){
var first = $('#firstNumber').val();
var second = $('#secondNumber').val();
if(first==""){
alert("Pleae enter first number");
return;
}
if(second==""){second=0;}

$.ajax({
   type: 'POST',
   url: 'http://localhost:8080/Calculator/Calculator',
   async: false,
   data: {
   first: first,
   second: second,
   operation: 'add'
    },
    success: getAjaxData
  
});

});

function getAjaxData(data){
 $('#secondNumber').val(data);
}

});


JSP Page Code:

<body>
It is simple Calculator
<br>
<input type="text" id="firstNumber"/>
<input type="button" id="addButton" value="Add" onclick="addAction()"/>
<input type="text" id="secondNumber" readonly="readonly"/>
<input type="button" id="clearButton" value="Clear" onclick="clearInput()"/>
</body>

Server side Code:


String first = request.getParameter("first");
String second = request.getParameter("second");
String operation = request.getParameter("operation");
logger.info("First Number :"+first);
logger.info("Second Number :"+second);
int result =  Integer.parseInt(first)+Integer.parseInt(second);
response.setContentType("text/html");
response.getWriter().write(result+"");

For Ajax using DOJO

AJAX Using DOJO Tutorial

It is very simple to develope Ajax application with DOJO. There is no any need to use
ActiveXObject or XMLHttpRequest. Here I am going to show a very simple application.

1. Create one dynamic web project using your Eclipse IDE. (Say Project Name : Ajax_Dojo)
2. Write one servlet in that project (Say AdmissionEnquiry.java)
3. Write one jsp page inside WebContent (Say example1.jsp)
4. Copy dojo.js inside WebContent
5. Add any server like Apache or Jboss to your project
6. Run the application http://localhost:8080/Ajax_Dojo/example1.jsp

AdmissionEnquiry.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AdmissionEnquiry extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
static final long serialVersionUID = 1L;
public AdmissionEnquiry() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String roll = request.getParameter("roll");
System.out.println("Entered Roll Number :: "+roll);
PrintWriter out = response.getWriter();
if(roll.equalsIgnoreCase("110")){
out.print("Binod Suman");
}
else if(roll.equalsIgnoreCase("120")){
out.print("Pramod Kumar");
}
else{
out.print("Roll Number not found");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}

example1.jsp

<html><body onLoad="onLoad();"
><head>
<title>Ajax Dojo Example</title>
<script language="javascript" src="dojo.js"></script>
<script language="javascript">
dojo.require("dojo.io.*");
dojo.require("dojo.event.*");
function onLoad() {
var buttonObj = document.getElementById("myButton");
dojo.event.connect(buttonObj, "onclick", this, "onclick_myButton");
}
function onclick_myButton() {
var url2 = "http://localhost:8080/Ajax_Dojo/AdmissionEnquiry";
var bindArgs = {
url: url2,
error: function(type, data, evt){
alert(data); },
load: function(type, data, evt){
alert(data); },
mimetype: "text/plain",
formNode: document.getElementById("myForm") };
dojo.io.bind(bindArgs); }
</script>
</head>
<body>

<form id="myForm">
<h1>Find Student Name</h1>
<p> Enter Roll Number <input type="text" name="roll">
<input type="button" id="myButton" value="Submit"/>
</p>
</form>
</body>
</html>

During run the application, you will give roll number as input and you will get student Name.
Very simple ................ :)
Please give your comment to enhance this tutorial. ............ :)

Easy explanation for Strategy design pattern using simple arithmetic calcuation

Strategy Design Pattern:

Detail :
http://en.wikipedia.org/wiki/Strategy_pattern


Use strategy when you need to define a family of algorithms, encapsulate each one, and make them
interchangeable. Strategy lets the algorithm vary independently from clients that use it.

Strategy pattern are algorithms inside a class which can be interchanged depending on the class used.
This pattern is useful when you want to decide on run time which algorithm to be used.

Calculation.java

public interface Calculation {
int execute(int a, int b);
}

AddCalc.java
public class AddCalc implements Calculation{
@Override
public int execute(int a, int b) {
return a+b;
}
}

SubCalc.java
public class SubCalc implements Calculation{
@Override
public int execute(int a, int b) {
return a-b;
}
}


MultiCalc.java
public class MultiCalc implements Calculation{
@Override
public int execute(int a, int b) {
return a*b;
}
}

DivideCalc.java
public class DivideCalc implements Calculation{
@Override
public int execute(int a, int b) {
if(b==0) {return 0;}
return a/b;
}
}

MainStrategy.java
public class MainStrategy {
private Calculation calculation;
public MainStrategy(Calculation calculation){
this.calculation = calculation;
}

public int cal(int a,int b){
return calculation.execute(a, b);
}
}

Test.java
public int calculation(int first,int second,String operation){
MainStrategy mainStrategy = null;
if(operation.equals("add")){mainStrategy = new MainStrategy(new AddCalc());}
if(operation.equals("sub")){mainStrategy = new MainStrategy(new SubCalc());}
if(operation.equals("multi")){mainStrategy = new MainStrategy(new MultiCalc());}
if(operation.equals("div")){mainStrategy = new MainStrategy(new DivideCalc());}
return mainStrategy.cal(first, second);
}

Command Design Pattern using simple example

Command Design Pattern:

Detail : http://en.wikipedia.org/wiki/Command_pattern


Use strategy when you need to define a family of algorithms, encapsulate each one, and make them
interchangeable. Strategy lets the algorithm vary independently from clients that use it.


Strategy pattern are algorithms inside a class which can be interchanged depending on the class used.
This pattern is useful when you want to decide on run time which algorithm to be used.

Calculation.java

public interface Calculation {
int execute(int a, int b);
}

AddCalc.java
public class AddCalc implements Calculation{
@Override
public int execute(int a, int b) {
return a+b;
}
}

SubCalc.java
public class SubCalc implements Calculation{
@Override
public int execute(int a, int b) {
return a-b;
}
}

MultiCalc.java
public class MultiCalc implements Calculation{
@Override
public int execute(int a, int b) {
return a*b;
}
}

DivideCalc.java
public class DivideCalc implements Calculation{
@Override
public int execute(int a, int b) {
if(b==0) {return 0;}
return a/b;
}
}


Test.java
Map commands = new HashMap();
public Test(){
        commands.put("add", new AddCalc());
        commands.put("sub", new SubCalc());
        commands.put("multi", new MultiCalc());
        commands.put("div", new DivideCalc());
}

public int calc(int first,int second,String operation){
  Calcuation cal = commands.get(operation);
 return cal.execute(first,second);
}

Simple RMI and RMI with Spring

RMI (=Remote Method Invocation)

The basic structure of an RMI-based method call involves a client, a server and a registry. To make a call to a remote object, the client first looks up the object it wishes to invoke a method on in the registry. The registry returns a reference to the object (assuming it exists) on the server, which the client can use to invoke any methods that the remote object implements.

Step1 : HelloInterface.java

 
import java.rmi.Remote;
import java.rmi.RemoteException;

public interface HelloInterface extends Remote {
  public String say() throws RemoteException;
}


Step 2: Hello.java

import java.rmi.*;
import java.rmi.server.*;

public class Hello extends UnicastRemoteObject
 implements HelloInterface {
  private String message;
  public Hello (String msg) throws RemoteException {
  message = msg;
  }
  public String say() throws RemoteException {
  return message;
  }
}


Step3.Compile the above two Source file named HelloInterface.java and Hello.java.

Step4.After compiling the above two classes type the following command i.e-  "rmic Hello" in console
> rmic Hello


By running the "rmic Hello" command a new class will be created i.e "Hello_Stub.class" in the directory.

Step5.Create Server application named HelloServer.java

HelloServer.java
import java.rmi.Naming;

public class HelloServer
{
  public static void main (String[] argv)
  {
  try {
  Naming.rebind("Hello", new Hello ("Hello,From Roseindia.net pvt ltd!"));
  System.out.println ("Server is connected and ready for operation.");
  }
  catch (Exception e) {
  System.out.println ("Server not connected: " + e);
  }
  }
}


Step6.Create Client application named HelloClient.java

HelloClient.java

import java.rmi.Naming;

public class HelloClient
{
  public static void main (String[] argv) {
  try {
HelloInterface hello =(HelloInterface)
 Naming.lookup ("//192.168.10.201/Hello");
  System.out.println (hello.say());
  }
  catch (Exception e){
  System.out.println ("HelloClient exception: " + e);}
  }
}

Step6.Compile both of the files.

Step7.Type "rmicregistry" on commandprompt and press ENTER.


Step8.Type java HelloServer in commandprompt and press ENTER.The following message will be displayed on console.

Console output will come
Server is connected and ready for operation.

Step9.Now,open another separate command terminal,and run the client application like shown in the figure given below:-

javac HelloClient.java
java  HelloClient

Hello, From RoseIndia.net pvt ltd.

Step10. If the message similar to the above appears in figure comes means that you have implemented your RMI application.


In short:
Write the service implementation class with methods that throw java.rmi
.RemoteException.
2 Create the service interface to extend java.rmi.Remote.
3 Run the RMI compiler (rmic) to produce client stub and server skeleton classes.
4 Start an RMI registry to host the services.
5 Register the service in the RMI registry.


RMI using SPRING:

Fortunately, Spring provides an easier way to publish RMI services. Instead of writing RMI-specific classes with methods that throw RemoteException, you simply write a POJO that performs the functionality of your service. Spring handles the rest.

For a typical Spring Application we need the following files:

1. An interface that defines the functions.
2. An Implementation that contains properties, its setter and getter methods, functions etc.
3. A XML file called Spring configuration file.
4. Client program that uses the function

Instead of generating a server skeleton and client stub using rmic and manually adding it to the RMI registry (as you would in conventional RMI), we’ll use Spring’s RmiServiceExporter.

RmiServiceExporter exports any Spring-managed bean as an RMI service. RmiServiceExporter works by wrapping the bean in an adapter class. The adapter class is then bound to the RMI registry and proxies requests to the service class.

<bean class="org.springframework.remoting.rmi.RmiServiceExporter">
        <property name="serviceName" value="employee-service"/>
        <property name="service" ref="employeeService"/>
        <property name="serviceInterface" value="rmi.common.EmployeeI"/>
        <property name="registryPort" value="1234"/>
</bean>

<bean id="employeeService" class="rmi.server.EmployeeImpl">
</bean>

public class Employee implements Serializable {
 private String name;
 private String address;

 public Employee(String name,String address){
  this.name = name;
  this.address = address;
 }

 // getters and setters
}


public interface EmployeeI {

 public void addEmployee(Employee employee);
 public void removeEmployee(Employee employee);
 public List<Employee> getEmployees();
  
}

public class EmployeeImpl implements EmployeeI{

    private List<Employee> employees = new ArrayList<Employee>();

    public void addEmployee(Employee employee) {
     employees.add(employee);
    }
  
    public void removeEmployee(Employee employee){
     employees.remove(employee);
    }

    public List<Employee> getEmployees() {
        return employees;
    }
}


Now to run the server side service you need Spring context initialization.


public class EmpServerDemo {
 public static void main(String[] args) {
  ApplicationContext ctx = new ClassPathXmlApplicationContext("rmi/server/rmi-server-context.xml");
 }
}

CLIENT SIDE

Now let us have a look at client side.

To link in the service on the client, we'll create a separate Spring container, containing the simple object and the service
linking configuration bits:


<beans>
    <bean id="employeeService" class="org.springframework.remoting.rmi.RmiProxyFactoryBean">
        <property name="serviceUrl" value="rmi://localhost:1234/employee-service"/>
        <property name="serviceInterface" value="rmi.common.EmployeeI"/>
    </bean>
</beans>

You can make client calls through the below code...

public class EmpClientDemo {
 public static void main(String[] args) {
  ApplicationContext ctx = new ClassPathXmlApplicationContext("rmi/client/rmi-client-context.xml");
  EmployeeI employee = (EmployeeI) ctx.getBean("employeeService");
  employee.addEmployee(new Employee("Prashant", "address1"));
  employee.addEmployee(new Employee("Sneha", "address2"));
  List<Employee> employees = employee.getEmployees();
  System.out.println("Total number of employees: " + employees.size());
  Iterator<Employee> it = employees.iterator();
  while (it.hasNext()) {
   Employee emp = (Employee) it.next();
   System.out.println(" " + emp);
  }
 }
}

 UnicastRemoteObject : This is the simplest way to ensure that objects of a class can be used as remote objects.

JSON Object With Servlet

ProjectStructure:

  

 JarFiles:

 

 package com.candidjava;
import java.io.IOException;
 import java.io.PrintWriter;
 import java.util.Iterator;
import javax.servlet.ServletException;
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
import org.json.JSONException;
 import org.json.JSONObject;
public class JObject extends HttpServlet {
 int length;
 String opt;
 boolean data;
 String getMark;
 String getCity;
 boolean mail;
protected void doGet(HttpServletRequest request,
 HttpServletResponse response) throws ServletException, IOException {
 JSONObject object = new JSONObject();
try {
 object.put("name", "Deepa");
 object.put("Reg No", new Integer(12345));
 object.put("Mark", new Double(99));
 object.put("mail", "deepa@ebullitent.com");
 object.put("City", "Chennai");
 length = object.length();
 opt = object.optString("name");
 data = object.isNull("name");
 getMark = object.getString("Mark");
 getCity = (String) object.get("City");
 mail = object.has("mail");
 // object.append("mark1","98");
 } catch (JSONException e) {
e.printStackTrace();
 }
 PrintWriter out = response.getWriter();
out.println("<html>");
 out.println(object);
 out.println("<head></head>");
 out.println("<body bgcolor='pink'>");
 out.println("<br/>");
 out.println("Name: " + opt);
 out.println("<br/>");
 out.println("Is Null: " + data);
 out.println("<br/>");
 out.println("city: " + getCity);
 out.println("<br/>");
 out.println("has mail: " + mail);
 out.println("<br/>");
 out.println("Mark:" + getMark);
 out.println("<br/>");
 out.println("List of keys:");
 out.println("<br/>");
 out.println("--------------");
 out.println("<br/>");
out.println("length: " + length + "\n");
 out.println("</body></html>");
 out.println();
 Iterator i = object.keys();
 while (i.hasNext()) {
 out.println(i.next());
 }
 object.toString();
}
}

OUTPUT:

 

 

 

 DOWNLOAD+ SOURCECODE

Ajax and JSON example, How to use JSON with Ajax

In my previous post, I had explained easy example of JSON. In this post I am explaining how to use JSON with Ajax.
No need to require any other software, just create one dynamic web project and paste below code.

1. StudentInfo.java (This is a Servlet)

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class StudentInfo extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String roll = request.getParameter("roll");
PrintWriter out = response.getWriter();
out.println(getResult(roll));
}

public String getResult(String roll){
String name = "";
String hostel = "";
String contact = "";
String[] subjects = new String[]{};
if(roll.equalsIgnoreCase("110")){
name = "Binod Kumar Suman"; hostel = "Ganga"; contact = "999999999";
subjects= new String[]{"C++","JAVA","DataBase"};
} else if(roll.equalsIgnoreCase("120")){
name = "Pramod Kumar Modi"; hostel = "Godawari"; contact = "111111111111";
subjects= new String[]{"C++","QT","Linux"}; }
else{ name = "Roll Number not found"; }

String result = "var student={"; result += "name:'" + name + "', ";
result += "hostel:'" + hostel + "', ";
result += "contact:'" +contact +"',";
result += "subject:[";
for(int i=0;i<subjects.length;i++){
if(i == subjects.length - 1){
result += "'"+subjects[i] + "']";
}
else{
result += "'"+subjects[i] +"',";
}
}
result += "};";
return result;

}
}

2. ShowStudentInfo.jsp

<html><head><
title>Binod Java Solution AJAX </title>
<script type="text/javascript">
var request; f
unction getName(){
var roll = document.getElementById("roll").value;
var url = "http://localhost:8080/Ajax_JSON/StudentInfo?roll="+roll;
if(window.ActiveXObject){ request = new ActiveXObject("Microsoft.XMLHTTP"); }
else if(window.XMLHttpRequest){ request = new XMLHttpRequest(); } request.onreadystatechange = showResult;
request.open("POST",url,true);
request.send();
}

function showResult(){
if(request.readyState == 4){
var response = request.responseText;
eval(response);
document.getElementById("NamelH1").innerHTML = student.name; document.getElementById("HostelH1").innerHTML = student.hostel; document.getElementById("ContactH1").innerHTML = student.contact; document.getElementById("SubjectH1").innerHTML = student.subject; } }

</script>
</head><body>
<h2> GET STUDENT INFO </h2>
<br> Enter Roll Number <input type="text" id="roll">
<input type="button" value="Get Name" onclick="getName();"/> <br>
<table border=2>
<tr><td>Name</td><td><span id="NamelH1">
</span></td></tr> <tr><td>Hostel</td>
<td><span id="HostelH1"></span></td></tr> <tr><td>Contact</td><td><span id="ContactH1">
</span></td></tr> <tr><td>Subject</td>
<td><span id="SubjectH1"></span></td></tr>
</table>
</body>
</html>

After compile and start the server, open internet explorer and put URL (like http://localhost:8080/Ajax_JSON/ShowStudentInfo.jsp) and put roll no. 110

This is very basic and fundamental tutorial, you can build a good project on Ajax and JSON with the help of this easy example.


Easy Example:

JSON : JavaScript Ojbect Notation.
It contains name/value pairs, array and other object for passing aroung ojbect in java script. It is subset of JavaScript and can be used as object in javascript.

You can use JSON to store name/value pair and array of ojbect.

It has eval() method to assign value to variable.
In below example, I have put all things together.
Just make one html file and you can start your practice on it.

How to use this tutorial:
1. Make one file JSONDemo.html
2. And paste below code
<html>
<head>
<body>
<script language="javascript">
eval("var amount =10;");
alert("Value of amount :: "+amount);

var student = {
name : "Binod",
roll : 110,
subject : ["Java","Database","Networking"]

}
alert("Student Name :: "+student.name);
alert("Student All Subject :: "+student.subject);
alert("Student First Subject :: "+student.subject[0]);
alert("Student No. of Subject :: "+student.subject.length);

for(var i=0;i<student.subject.length;i++){
var value = student.subject[i];
alert(value);
}

var person = {
name : "Ambani",
books : [
{
title : "Java Programming",
author : "Binod Suman"
},
{
title : "XML",
author : "Don Box"
}
]

}

alert("Book Title :: "+person.books[0].title);
alert("Book Author :: "+person.books[0].author);


</script>

Please put your comment on this post for enhance this blog or this tutorial.

Thanks and have a nice day ............ :) 

Monday, October 8, 2012

Chat application in java

This is my 3rd year project which is the initial state of any perfect chat application. It has also few bugs, but it can help any novice student to complete their java assignment.
This application is developed in NetBeans IDE. There is two projects one is server and another is Client. To download this two projects click the link bellow.

Download Chat Application


How to run This application :

After downloading two projects open this two projects in NetBeans IDE. At First run Server project then run Client project. Client project should be run two or more times because one client can not chat alone. The Client project runs two times means that two user is connected to the server and they can chat with each other.

Overview Of This Project:

I have attached some screen shots which can help you to understand easily. The attachments are given bellow :

Server Monitor :

This is the Server Monitor window. When you run the Server project this window will be shown. This window contains four portion :
  1. Monitor Clients : display the User information like name of user, from which IP address and which port number.
  2. Online Clients : list out the users who are connected to this server.
  3. Server Status : Shows which port number is used by this server.
  4. Controll Panel : it contains two buttons one is Start and second one is Stop. Start button run this server on specific port number and Stop button just shut down the server.

Sign-in Window:

When you run Client Project the first window will be shown. Client project has another two window which i will discuss in bellow. This window contain one input field and button. Input field just take the name of user and sign in button take the user to the next window. User name can be any String but there is a little bug if username contain space character then it behave not well. Single word user name is better for this for example “jodu” , “modhu”.

Buddy List :

This window is showed after sign in with user name. if any other user is already sign in list of those users will be showed and also those who are currently signed in will be showed in the list. if any user want to chat with any other user then user just double click on the user name from the online user list as like as yahoo messenger.


Chat Window :

here is the chat window of two user. I just present a little conversion between two users . Any user can also send any file by this window.

Emailtemplate

Download Source Code


This application developed by using freemarker and java

struts 1x i18n internationalization tutorial with example program(Using Link)

This struts tutorial explains how to archive internationalization(i18n) without using or modifying any browser setting, Here we have loaded four different languages English, France, Germany and  Italy, by clicking a link in the webpage languages can be changed.
Controller class will load the language for the  application based on their user request
Project Structure:
JAR Files: 
TLD Files:

Following is the list of required JAR files to be added in Java Class Path of your project. Download displaytag JAR files from

JAR FILES + TLD FILES

Model class which handles data from view page
Form.java:



package com.candid;

public class Form extends org.apache.struts.action.ActionForm {

 private static final long serialVersionUID = 1L;

 private String name;

 public String getName() {
  return name;
 }

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

}
Controller class which loads language based on user action

Inter_WebPage.java:

package com.candid;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession; //import org.apache.struts.actions.DispatchAction;
import org.apache.struts.actions.LookupDispatchAction;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;

/**
 *
 * @author balamurugan@candidjava.com
 */
/*
 * our program is Loopup Dispatch Action so class must extends
 * LookupDispatchAction
 */
public class Inter_WebPage extends LookupDispatchAction {

 /* forward name="success" path="" */
 private final static String SUCCESS = "success";

 protected Map getKeyMethodMap() {
  Map map = new HashMap();
  map.put("label.submit", "submit");
  map.put("label.language.english", "english");
  map.put("label.language.italian", "italian");
  map.put("label.language.german", "german");
  map.put("label.language.french", "french");

  return map;
 }

 public ActionForward english(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response)
   throws Exception {
  HttpSession session = request.getSession();
  session.setAttribute("org.apache.struts.action.LOCALE", Locale.ENGLISH);
  return mapping.findForward(SUCCESS);
 }

 public ActionForward french(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response)
   throws Exception {
  HttpSession session = request.getSession();
  session.setAttribute("org.apache.struts.action.LOCALE", Locale.FRENCH);
  return mapping.findForward(SUCCESS);
 }

 public ActionForward german(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response)
   throws Exception {
  HttpSession session = request.getSession();
  session.setAttribute("org.apache.struts.action.LOCALE", Locale.GERMAN);
  return mapping.findForward(SUCCESS);
 }

 public ActionForward italian(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response)
   throws Exception {
  HttpSession session = request.getSession();
  session.setAttribute("org.apache.struts.action.LOCALE", Locale.ITALIAN);
  return mapping.findForward(SUCCESS);
 }

 public ActionForward submit(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response)
   throws Exception {

  return mapping.findForward("output");
 }

}

ApplicationResource_de.properties:



# To change this template, choose Tools | Templates
# and open the template in the editor.

label.string1 = Geben ihren Namen.
label.string2=Willkommen.
label.language.english=english
label.language.italian=italiano
label.language.german=deutsch
label.language.french=francaise

label.submit=Einreichen.

ApplicationResource_fr.properties:



# To change this template, choose Tools | Templates
# and open the template in the editor.

label.string1 = Entrez votre nom.
label.string2=Bienvenue.
label.language.english=english
label.language.italian=italiano
label.language.german=deutsch
label.language.french=francaise

label.submit=Soumettre des.

ApplicationResource_it.properties:



# To change this template, choose Tools | Templates
# and open the template in the editor.

label.string1 = Inserisci il tuo nome.
label.string2=Benvenuto.
label.language.english=english
label.language.italian=italiano
label.language.german=deutsch
label.language.french=francaise

label.submit=presentare

ApplicationResource.properties:



# -- standard errors --
errors.header=<UL>
errors.prefix=<LI>
errors.suffix=</LI>
errors.footer=</UL>
# -- validator --
errors.invalid={0} is invalid.
errors.maxlength={0} can not be greater than {1} characters.
errors.minlength={0} can not be less than {1} characters.
errors.range={0} is not in the range {1} through {2}.
errors.required={0} is required.
errors.byte={0} must be an byte.
errors.date={0} is not a date.
errors.double={0} must be an double.
errors.float={0} must be an float.
errors.integer={0} must be an integer.
errors.long={0} must be an long.
errors.short={0} must be an short.
errors.creditcard={0} is not a valid credit card number.
errors.email={0} is an invalid e-mail address.
# -- other --
errors.cancel=Operation cancelled.
errors.detail={0}
errors.general=The process did not complete. Details should follow.
errors.token=Request could not be completed. Operation is not in sequence.
# -- welcome --
welcome.title=Struts Application
welcome.heading=Struts Applications in Netbeans!
welcome.message=It's easy to create Struts applications with NetBeans.

label.string1 = Enter your name
label.string2=  welcome
label.language.english=english
label.language.italian=italian
label.language.german=german
label.language.french=french

label.submit=submit

web.xml:



<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 <servlet>
  <servlet-name>action</servlet-name>
  <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
  <init-param>
   <param-name>config</param-name>
   <param-value>/WEB-INF/struts-config.xml</param-value>
  </init-param>
  <init-param>
   <param-name>debug</param-name>
   <param-value>2</param-value>
  </init-param>
  <init-param>
   <param-name>detail</param-name>
   <param-value>2</param-value>
  </init-param>
  <load-on-startup>2</load-on-startup>
 </servlet>
 <servlet-mapping>
  <servlet-name>action</servlet-name>
  <url-pattern>*.do</url-pattern>
 </servlet-mapping>
 <session-config>
  <session-timeout>30</session-timeout>
 </session-config>
 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
 <jsp-config>
  <taglib>
   <taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
   <taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
  </taglib>
  <taglib>
   <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
   <taglib-location>/WEB-INF/struts-html.tld</taglib-location>
  </taglib>
  <taglib>
   <taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri>
   <taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
  </taglib>
  <taglib>
   <taglib-uri>/WEB-INF/struts-nested.tld</taglib-uri>
   <taglib-location>/WEB-INF/struts-nested.tld</taglib-location>
  </taglib>
  <taglib>
   <taglib-uri>/WEB-INF/struts-tiles.tld</taglib-uri>
   <taglib-location>/WEB-INF/struts-tiles.tld</taglib-location>
  </taglib>
 </jsp-config>
</web-app>

struts-config.xml:



<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts-config PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
          "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">

<struts-config>
 <form-beans>
  <form-bean name="form1" type="com.candid.Form"></form-bean>
 </form-beans>

 <action-mappings>
  <action path="/changeLocale" name="form1" parameter="method"
   type="com.candid.Inter_WebPage">
   <forward name="success" path="/index.jsp" />
   <forward name="output" path="/output.jsp"></forward>
  </action>
  <action path="/Welcome" forward="/welcomeStruts.jsp" />
 </action-mappings>
 <message-resources parameter="com/candid/ApplicationResource" />

</struts-config> 
 
Index page Provides a link to change language

index.jsp:



<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>
<%@taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
<html>
<head>
<title>Struts - I18N</title>
</head>
<body>
<html:form action="changeLocale">
 <table>
  <tr>
   <td>Select your language : <a
    href="changeLocale.do?method=<bean:message key="label.language.english" />"><bean:message
    key="label.language.english" /></a> <a
    href="changeLocale.do?method=<bean:message key="label.language.french" />"><bean:message
    key="label.language.french" /></a> <a
    href="changeLocale.do?method=<bean:message key="label.language.german" />"><bean:message
    key="label.language.german" /></a> <a
    href="changeLocale.do?method=<bean:message key="label.language.italian" />"><bean:message
    key="label.language.italian" /></a></td>
  </tr>
  <tr>
   <td><bean:message key="label.string1" /></td>
   <td><html:text property="name"></html:text>
  </tr>
  <tr>
   <td><html:submit property="method">
    <bean:message key="label.submit" />
   </html:submit></td>
  </tr>
 </table>
</html:form>
</body>
</html>

output.jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>output</title>
</head>
<body>
<table>
 <tr>
  <td><bean:message key="label.string2" /></td>
  <TD><bean:write name="form1" property="name" /></TD>
 </tr>
</table>
</body>
</html> 
 




Screenshot for internationalization

OUTPUT:    

      

                                                                                                                
DOWNLOAD+SOURCE CODE

Connect facebook using java


import javax.servlet.http.*;
import java.io.IOException;
import javax.servlet.*;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.PrintWriter;
import com.facebook.api.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class SocialJavaTutorial extends HttpServlet {
    int count;

    //Application API Key and application secret from creating app in FB
    String appapikey = new String("7623a6ab94a7cc519b1fb73627afdda0");
    String appsecret = new String("90e48- your secret here - df6d957e");

    //Facebook loginPage to this application.  Parameter canvas=true shows the result in Facebook canvas
    String loginPage = "http://www.facebook.com/login.php?api_key="+"00b0049fc7cf0d1e4a4ba2ea3e55b269"+"&v=1.0&canvas=true";
    String profilePage = "http://www.facebook.com/profile.php";

    FacebookJsonRestClient facebook;  // the facebook client, talks to REST Server
    PrintWriter servletOutput;  // output of servlet. HTML or FBML out

    public void doGet( HttpServletRequest req, HttpServletResponse res ) throws ServletException, IOException{
        servletOutput = res.getWriter(); // response is sent to ServletOutput
        res.setContentType( "text/html" );
        servletOutput.println("This is the doGet method");
    }

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

        servletOutput = res.getWriter(); // response is sent to ServletOutput
        res.setContentType( "text/html" );

        // do authentication 
        String user =null;
        String sessionKey=null;
        sessionKey = req.getParameter(FacebookParam.SESSION_KEY.toString());  // Session Key passed as request parameter
        if (sessionKey==null) { // If there is not session key, they user not logged in
            servletOutput.println("<fb:redirect url=" + loginPage + "/>");  // Facebook Redirect to login page
        }
        else{  // user is logged on

            //get MockFBMLText from Profile as a parameter. If it exists, send it to servlet & skip the rest

            String mockfbmltext = req.getParameter("mockfbmltext");
            if (mockfbmltext!=null){
                servletOutput.println(mockfbmltext);
            }else{        // if MockFBMLText is set, don't do anything else
                facebook = new FacebookJsonRestClient(appapikey, appsecret,sessionKey);  // create Facebook Json Rest Client
                try{
                    // Get user id as parameter
                    user = req.getParameter("fb_sig_user");  // get user as a string.  User info passed as request parameter
                    Long userLong = new Long(user); // need user as a long for  API calls

                    // get profiletext as parameter, if not null, then display on profile, redirect to profile page
                    String displayText = req.getParameter("profiletext");
                    if (displayText!=null){
                        facebook.profile_setFBML(displayText, userLong);
                        servletOutput.println("<fb:redirect url=" + profilePage + "/>");  // Facebook Redirect to login page
                    }else{
                        // render rest of page if displayText is not a parameter

                        // Display User ID
                        servletOutput.println("User is " + user +"<br>");  // displays numeric value

                        // use JDBC to store and update the count
                        Connection con;
                        Statement stmt;
                        try {
                            Class.forName("com.mysql.jdbc.Driver").newInstance();
                        } catch (Exception ex) {
                            // handle the error
                            servletOutput.println(ex +" error");
                        }
                        try {
                            con = DriverManager.getConnection("jdbc:mysql://HOST/DATABASE?" +
                            "user=USER_NAME&password=PASSWORD");
                            String query;
                            try {
                                stmt = con.createStatement();
                                query ="Select count from counter";  //counter is the table that contains count
                                ResultSet rs = stmt.executeQuery(query);
                                if (rs.next()) {
                                    int count = rs.getInt("count");
                                    count++;
                                    servletOutput.println("the count is " + count +" <br>");
                                    query ="UPDATE  counter SET count=" + count;  //update count in Database
                                    stmt.executeUpdate(query);

                                } else { // if it is the first time access
                                    stmt = con.createStatement();
                                    query ="INSERT INTO counter (count) VALUES (1)";
                                    stmt.executeUpdate(query);
                                    servletOutput.println("You are number 1");
                                }
                                con.close();
                            } catch(SQLException ex) {
                                servletOutput.println("SQLException: " + ex.getMessage());
                            }
                        } catch (SQLException ex) {
                            // handle any errors
                            servletOutput.println("SQLException: " + ex.getMessage());
                            servletOutput.println("SQLState: " + ex.getSQLState());
                            servletOutput.println("VendorError: " + ex.getErrorCode());
                        }

                        // Try FQL to get name
                        String query = "SELECT name FROM user WHERE uid=" + user;
                        org.json.JSONArray resultArray = (org.json.JSONArray)facebook.fql_query(query);
                        try{
                            JSONObject result = resultArray.getJSONObject(0);
                            servletOutput.println("User Name is " + result.getString("name"));
                            servletOutput.println("<br>");
                        } catch(JSONException jex){
                            servletOutput.println(">Error: JSON "  + jex );
                        }

                        // Set up input form on canvas page
                        servletOutput.println("</pre>");
                        servletOutput.println("<form action=\"\" method=\"post\">");
                        servletOutput.println("<input name=\"profiletext\" type=\"text\" size=\"30\" value=\"\"><br>");
                        servletOutput.println("<input name=\"submit\" type=\"submit\" value=\"Display text on profile\">");
                        servletOutput.println("</form>");

                        // Set up mockajax form on profile page
                        String appCallBackUrl = "http://www.socialjava.com/servlet/SocialJavaTutorial/";
                        String mockAjax;
                        mockAjax="<form>";
                        mockAjax+="<input name=\"mockfbmltext\" type=\"text\" size=\"30\">";
                        mockAjax+="<br />";
                        mockAjax+="<input type=\"submit\"";
                        mockAjax+="  clickrewriteurl=\""+ appCallBackUrl +"\"";
                        mockAjax+="  clickrewriteid=\"preview\" value=\"Draw text below\"";
                        mockAjax+="/>";
                        mockAjax+="<br />";
                        mockAjax+="<div id=\"preview\" style=\"border-style: solid; border-color: black;";
                        mockAjax+=" border-width: 1px; padding: 5px;\">";
                        mockAjax+="</div>";
                        mockAjax+="</form>";
                        facebook.profile_setFBML(mockAjax.toString(), userLong);
                    }           
                }//try
                catch( FacebookException ex )
                {
                    servletOutput.println(">Error: Couldn't talk to Facebook> "  + ex );
                }
            } //else user is logged in
        }//else mockajax

        servletOutput.close();
    }  // end doPost()
}