Tuesday, April 26, 2011

Client Server GUI Chating Application in Java


This is an fine example for Scoket Programmin in java. This application contains 2 java classes. One is for server and other is for client. Java Scoket is used to connect them together. Each line of the code are explained through comments. To run this application first run the server one and then client. Two Gui will be shown as in below screenshorts.

AppServer.java
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
/**
 * @author Tapas
 * @mail tapas.friends@gmail.com
 * @blog tapas4web.blogspot.com
 */
public class AppServer extends Frame implements ActionListener,Runnable
{
 //Declarations
 Button b1;
 TextField tf;
 TextArea ta;
 ServerSocket ss;
 Socket s;
 PrintWriter pw;
 BufferedReader br;
 Thread th;
 
 public AppServer()
 {
  Frame f=new Frame("Server Side Chatting");//Frame for Server
  f.setLayout(new FlowLayout());//set layout
  f.setBackground(Color.orange);//set background color of the Frame
  b1=new Button("Send");//Send Button
  b1.setBackground(Color.pink);
  b1.addActionListener(this);//Add action listener to send button.
  tf=new TextField(15);
  ta=new TextArea(12,20);
  ta.setBackground(Color.cyan);
  f.addWindowListener(new W1());//add Window Listener to the Frame
  f.add(tf);//Add TextField to the frame
  f.add(b1);//Add send Button to the frame
  f.add(ta);//Add TextArea to the frame
  try{
   ss=new ServerSocket(12000);//Socket for server
   s=ss.accept();//accepts request from client
   System.out.println(s);
   //below line reads input from InputStreamReader
   br=new BufferedReader(new InputStreamReader(s.getInputStream()));
   //below line writes output to OutPutStream
   pw=new PrintWriter(s.getOutputStream(),true);
  }catch(Exception e)
  {
  }
  th=new Thread(this);//start a new thread
  th.setDaemon(true);//set the thread as demon
  th.start();
  setFont(new Font("Arial",Font.BOLD,20));
  f.setSize(200,200);//set the size
  f.setLocation(300,300);//set the location
  f.setVisible(true);
  f.validate();
 }
 //method required to close the Frame on clicking "X" icon.
 private class W1 extends WindowAdapter
 {
  public void windowClosing(WindowEvent we) 
  {
   System.exit(0);
  }
 }
 //This method will called after clicking on Send button.
 public void actionPerformed(ActionEvent ae)
 {
  pw.println(tf.getText());//write the value of textfield into PrintWriter
  tf.setText("");//clean the textfield
 }
 //Thread running as a process in background
 public void run()
 {
  while(true)
  {
   try{
    String s=br.readLine();//reads the input from textfield
    ta.append(s+"\n");//Append to TextArea
   }catch(Exception e)
   {
   }
  } 
 }
 //Main method
 public static void main(String args[]) 
 {
  //Instantiate AppServer class
  AppServer server = new AppServer();
 }
} 

AppClient.java
import java.awt.*;
import java.awt.event.*;

import java.io.*;
import java.net.*;
/**
 * @author Tapas
 * @mail tapas.friends@gmail.com
 * @blog tapas4web.blogspot.com
 */
public class AppClient extends Frame implements ActionListener,Runnable
{
 //Declarations
 Button b;
 TextField tf;
 TextArea ta;
 Socket s;
 PrintWriter pw;
 BufferedReader br;
 Thread th;
 
 public AppClient()
 {
  Frame f=new Frame("Client Side Chatting");//Frame for Client
  f.setLayout(new FlowLayout());//set layout
  f.setBackground(Color.orange);//set background color of the Frame
  b=new Button("Send");//Send Button
  b.addActionListener(this);//Add action listener to send button.
  f.addWindowListener(new W1());//add Window Listener to the Frame
  tf=new TextField(15);
  ta=new TextArea(12,20);
  ta.setBackground(Color.cyan);
  f.add(tf);//Add TextField to the frame
  f.add(b);//Add send Button to the frame
  f.add(ta);//Add TextArea to the frame
  try{
   s=new Socket(InetAddress.getLocalHost(),12000);//Socket for client
   //below line reads input from InputStreamReader
   br=new BufferedReader(new InputStreamReader(s.getInputStream()));
   //below line writes output to OutPutStream
   pw=new PrintWriter(s.getOutputStream(),true);
  }catch(Exception e)  
  {
  }
  th=new Thread(this);//start a new thread
  th.setDaemon(true);//set the thread as demon
  th.start();
  setFont(new Font("Arial",Font.BOLD,20));
  f.setSize(200,200);//set the size
  f.setVisible(true);
  f.setLocation(100,300);//set the location
  f.validate();
 }
 //method required to close the Frame on clicking "X" icon.
 private class W1 extends WindowAdapter
 {
  public void windowClosing(WindowEvent we)
  {
   System.exit(0);
  }
 }
 //This method will called after clicking on Send button.
 public void actionPerformed(ActionEvent ae)
 {
  pw.println(tf.getText());//write the value of textfield into PrintWriter
  tf.setText("");//clean the textfield
 }
 //Thread running as a process in background
 public void run()
 {
  while(true)
  {
   try{
    ta.append(br.readLine()+"\n");//Append to TextArea
   }catch(Exception e) {}
  }
 }
 //Main method
 public static void main(String args[])
 {
  //Instantiate AppClient class
  AppClient client = new AppClient();
 }
}

The above prograam looks like below -



Sunday, April 24, 2011

Easy Ajax Development with jQuery


What’s Ajax?
AJAX is a short hand for Asynchronous JavaScript and XML. Ajax is a technique for handling external data through JavaScript asynchronously, without reloading the entire page. It means that instead of waiting for the whole page to load, you can load only what you need to. So if you only need to update one small text part of your site, you don’t have to worry about loading everything else on that page. Probably some of the best example of ajax handy applications are Google Suggest, Google Map, facebook and GMail e.t.c . XMLHttpRequest Object is the heart of the ajax. You can write your own plain javascript code to make an ajax call to the server using  XMLHttpRequest object. But In this article, we are going to discus how to get started with AJAX using the jQuery JavaScript framework?
What’s jQuery?
jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript.  jQuery’s methodology is simple: find things, do stuff. We select elements from the document (via the DOM) using the jQuery function, aliased as $(). This handy function acts just like document.getElementById(), except that instead of only supporting IDs, it supports CSS selectors and some XPath selectors; and, instead of returning one element, it can return an array of elements. XPath selectors are known as the XML Path Language, which is used for finding and manipulating elements in xml documents. Its similar to how you would select some elements in CSS.  You can find more details on jQuery at http://docs.jquery.com/Main_Page. The jQuery library has a full suite of AJAX capabilities. Let us have a look on them.

Getting Started :

jQuery provides some powerful set of  API’s to handle AJAX requests. The normal way of making AJAX calls using JavaScript is a bit odd as you have to first create an XMLHttpRequest object which is dependent on the browser and then make an AJAX call. Also sending a form data using AJAX is also bit difficult if we use normal JavaScript approach of calling AJAX. jQuery provides simple yet powerfull functions which have extended the JavaScript AJAX methods and provide more flexible way. Let us see different ways of doing AJAX things in jQuery.

Ajax request using GET  method:
Load a remote page using HTTP GET request method. This is an easy way to send a simple GET request to a server. It allows a single callback function to be specified that will be executed when the request is complete (and only if the response has a successful response code).

Syntax -

jQuery.get( url, [ data ], [ callback], [ dataType ] )
url: (String) The URL of the page to load.
data (Optional): (Map) Key/value pairs that will be sent to the server.
callback (Optional): (Function) A function to be executed whenever the data is loaded successfully.
type (Optional): (String) Type of data to be returned to callback function: “xml”, “html”, “script”, “json”, “jsonp”, or “text”.
Example -
//Gets the test.jsp page content, store it in a XMLHttpResponse object and show it in a alert box.
$.get(
     "test.jsp",
     "{key:value}",
     function(data){
          alert(data); 
     },
     "html"
);
Ajax request using POST  method:
Load data from the server using HTTP POST request method. This is an easy way to send a simple POST request to a server.

Syntax -

jQuery.post( url, [data], [callback], [type] )
url: (String) The URL of the page to load.
data (Optional): (Map) Key/value pairs that will be sent to the server.
callback (Optional): (Function) A function to be executed whenever the data is loaded successfully.
type (Optional): (String) Type of data to be returned to callback function: “xml”, “html”, “script”, “json”, “jsonp”, or “text”.

Example -
//Gets the test.php page content, store it in a XMLHttpResponse object and applies to the process() JavaScript function.
$.post(
     "test.jsp",
     { name: "John", time: "2pm" },
     function(data) {
           process(data);
     },
     "xml"
);

Ajax equest using JSON  format:
JavaScript Object Notation (JSON) is a popular light weight format that can be used to get data from server. JSON has became very popular since that web pages have became interactive using AJAX. JSON format is easy to create from the server and easy to parse at client as it is the basic object representation in JavaScript.
JQuery provides a function that can be used to make an AJAX call and get the data in JSON format. Normally the data that we get from AJAX is converted in JSON by calling eval () method of JavaScript. But the function provided by JQuery handles this internally and provides direct JSON object as output.
Syntax -
jQuery.getJSON( url, [data], [callback] ) 

Example -
//Loads the four most recent cat pictures from the Flickr JSONP API
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
  {
    tags: "cat",
    tagmode: "any",
    format: "json"
  },
  function(data) {
     $.each(data.items, function(i,item){
          $("").attr("src", item.media.m).appendTo("#images");
          if ( i == 3 ) return false;
  });
});

ajaxStart() and ajaxComplete() methods:
While you make an AJAX call and get some data from server, it is good to show a progress bar or image to user so that (s)he knows that something is going on. Hence Loading… text is common in AJAX enabled application.
What if you web application is making many AJAX calls like gmail. You may want to display a Loading… text while any of AJAX call is proceeding. To achieve this ajaxStart() and ajaxComplete() methods of jQuery can be used.
ajaxStart() method registers a function handler that will be called by jQuery internally whenever an AJAX call is made. If already a request is active than the handler is not called. We can use this method to register a handler function that will display our progress bar.

$.ajaxStart(function() {
     $("div#loading").text("Loading...");
});

In above code snippet, we used ajaxStart() method to register a function that set the innerHTML of div to Loading…
Similarly ajaxComplete() method can be used to register a handler function which gets called by jQuery when an AJAX request get completed and any other active request are not in progress.

$.ajaxComplete(function() {
     $("div#loading").text("");
});

serialize() and serializeArray()  methods:
While submitting a form using AJAX, one has to create a input string that contains the value of all the input elements on the screen. It is very difficult to create this string if your form is very big. Hence we can use jQuery’s serialize() and serializeArray() method to do so.

Serialize() Serializes a set of input elements into a string of data. Serialize is typically used to prepare user input data to be posted to a server. The serialized data is in a standard format that is compatible with almost all server side programming languages and frameworks. In order to work properly serialize requires that form fields have a name attribute. Having only an id will not work.


var str = $("form").serialize();
$("#results").text(str);

In above code snippet, we created a serialize output of the form. This value can be sent to server by an AJAX call.

SerializeArray() serializeArray() does the similar job. Except it creates JSON output.

[
     {name: 'firstname', value: 'Hello'},
     {name: 'lastname', value: 'World'},
     {name: 'alias'}, // this one was empty
]

ajaxSuccess() and ajaxError() methods-
Whenever an Ajax request completes successfully, jQuery triggers the ajaxSuccess event. Any and all handlers that have been registered with the .ajaxSuccess() method are executed at this time.
$('div.log').ajaxSuccess(function() {
      $(this).text('Triggered ajaxSuccess handler.');
});

In the above code, when Ajax request completes successfully, the log message is displayed.
Similarly whenever an Ajax request completes with an error, jQuery triggers the ajaxError event. Any and all handlers that have been registered with the .ajaxError() method are executed at this time.
$("#msg").ajaxError(function(event, request, settings){
         $(this).append("Error requesting page " + settings.url + "");
});

When the  Ajax request fails, the error message is displayed. 


Friday, April 15, 2011

Struts 2 Architecture at a Glance with API Internal Flows



Introduction
Apache Struts 2 is an elegant, extensible framework for creating enterprise-ready Java web applications.
It is a second-generation web application framework that implements the Model-View-Controller (MVC) design pattern and it introduces several new architectural features that make the framework cleaner and more flexible. These new features includes-
  • Interceptors for layering cross-cutting concerns away from action logic.
  • Annotation-based configuration to reduce or eliminate XML configuration.
  • A powerful expression language, Object-Graph Navigation Language(OGNL), that transverses the entire framework.
  • A mini-MVC–based tag API that supports modifiable and reusable UI components.
  • Pluggable architecture which supports framework extension.
  • Better support for Validation, File Upload, Internationalization (I18N) through Interceptors.
Apache Struts2 was originally known as WebWork 2. After working independently for several years, the WebWork and Struts communities joined forces to create Struts2. This new version of Struts is simpler to use and closer to how Struts was always meant to be.

Struts 2 Architecture
Mainly the MVC pattern provides a separation of concerns that applies well to web applications. Separation of concerns means managing the complexity of large software systems by dividing them into high-level components. The MVC design pattern identifies three distinct concerns: model, view, and controller. In Struts 2, these are implemented by the action, result, and FilterDispatcher respectively.

The Big Picture of Struts2-



Struts 2 Framework Components
Now let us see some of the Backend Hero’s (API Classes) of Struts2 framework-

1. FilterDispatcher –
This is the controller of Struts 2 framework and the first component to act in the request processing cycle. Basically it is a servlet filter. Its main and important job is to inspecting each incoming request to determine which Struts 2 action should handle the request.

2. ActionMapper-
This class is used by FilterDispatcher to determine whether the request should invoke an action or not.
When given an HttpServletRequest, the ActionMapper may return null if no action invocation request matches, or it may return an ActionMapping that describes an action invocation for the framework to try.
ActionMapping is the class that holds the action mapping information used to invoke a Struts action

3. ActionProxy-
If the ActionMapper determines that an Action should be invoked for that request, the FilterDispatcher delegates control to the ActionProxy. The ActionProxy consults with ConfigurationManager and then creates an ActionInvocation.

4. ConfigurationManager-
This is the java object representation for the struts.xml file which is loaded at the application startup and contains all the information regarding framework configuration. The ConfigurationProvider interface describes the framework's configuration. By default, the framework loads its configurations via an xml document by using the StrutsXmlConfigurationProvider.

5. Struts.xml-
This the core configuration files of struts 2 framework. It contains user defined mappings for each actions, Interceptors and results etc.

6. ActionInvocation-
It is responsible for the command pattern implementation. This includes invoking any Interceptors in advance of invoking the Action itself. Once the Action returns, the ActionInvocation is responsible for looking up the proper result associated with the Action result code mapped in struts.xml. The result is then executed, which involves a template written in JSP or FreeMarker to be rendered.

7. Interceptor-
Interceptors are invoked both before and after the action has executed. Interceptors don’t necessarily have to do something both times they fire, but they do have the opportunity. Some interceptors only do work
before the action has been executed, and others only do work afterward. The important thing is that the interceptor allows common, cross-cutting tasks to be defined in clean, reusable components that you can keep separate from your action code (e.g. validation, file upload, logging etc). You can use a stack of interceptors for a single action as well.

8. Action-
MVC model concern is implemented by the Struts 2 action component. In an application for a specific task, there should be a respective action to handle that particular task.  Let’s take a user login scenario where there must be an action which is responsible for validating the user credentials with Database values. In a single line- An action is an encapsulation of the calls to business logic into a single unit of work.

9. Result-
Result translates the state of the application into a visual presentation with which the user can interact. The action is responsible for choosing which result will render the response for a specific request. Different Results types are like Jsp, Velocity, Freemaker etc.

10. Template-
It is the view pages which actually renders the response to the user.

11. ObjectFactory-
Although ObjectFactory is not shown in above diagram, still this is one of the core important class of the framework. All objects created by the framework are instantiated by the ObjectFactory. The ObjectFactory provides the means of integrating the framework with IoC containers like Spring.

Request Processing Lifecycle
  1. The normal lifecycle of struts2 begins when the request is sent from client’s browser. This results invoke the servlet container which in turn is passed through standard filter chain. The chain includes the (optional) ActionContextCleanUp filter, which is useful when integrating technologies such as SiteMesh Plugin.
  2. The FilterDispatcher filter is called which consults the ActionMapper to determine whether an Action should be invoked.
  3. If ActionMapper finds an Action needs to be invoked, the FilterDispatcher delegates control to ActionProxy. 
  4. ActionProxy reads the configuration file such as struts.xml. ActionProxy creates an instance of ActionInvocation class and delegates the control.
  5. ActionInvocation is responsible for command pattern implementation. It invokes the Interceptors one by one (if required) and then invoke the Action.
  6. Once the Action returns, the ActionInvocation is responsible for looking up the proper result associated with the Action result code mapped in struts.xml.
  7. The Interceptors are executed again in reverse order and the response is returned to the FilterDispatcher. And the result is then sent to the servlet container which in turns sends it back to client.
Comparison between Struts 1 and Struts 2
Let us see the basic difference between Struts 1 and 2 frameworks-
  1. Unlike Struts 1, Struts 2 does not need to extend Action class. The Action in Struts 2 is a POJO object. Thus making it easy to unit test the code.
  2. Struts 1 Actions are singletons and must be thread-safe since there will be only one instance of a class to handle all requests for that Action. Struts 2 Action objects are instantiated for each request, so there are no thread-safety issues.
  3. Struts 1 Actions have dependencies on the servlet API since the HttpServletRequest and HttpServletResponse is passed to the execute method when an Action is invoked. Struts 2 Actions are not coupled to a container. Most often the servlet contexts are represented as simple Maps, allowing Actions to be tested in isolation.
  4. 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. Struts 2 uses Action properties as input properties, eliminating the need for a second input object. Input properties may be rich object types which may have their own properties.
  5. 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. Struts 2 can use JSTL, but the framework also supports a more powerful and flexible expression language called “Object Graph Notation Language” (OGNL).
  6. Struts 1 uses the standard JSP mechanism for binding objects into the page context for access. Struts 2 uses a “ValueStack” technology so that the taglibs can access values without coupling your view to the object type it is rendering.
  7. Struts 1 supports separate Request Processors (lifecycles) for each module, but all the Actions in the module must share the same lifecycle. Struts 2 supports creating different lifecycles on a per Action basis via Interceptor Stacks. Custom stacks can be created and used with different Actions, as needed.
  8. AJAX is a well known term in web development. In Struts 1.x, developer had to write and maintain the code in javascript to add AJAX support. But now Struts 2 gives you Ajax ‘out of the box’. No writing of javascript, no debugging against various browsers; just configure and go. 
Strut 2 comes with highly configurable AJAX tag library which can be used directly without writing JavaScript code. Some best of them are Dojo library and Struts2-JQuery Library.

You can find the Strut2-jQuery plugin showcase at Here


Toad Connection Error on a Windows 64-bit Machine


Problem
Toad 8.6 installation on a 64-bit windows 7 machine gives error as below when trying to connect Database.

"ORA-12154: TNS:could not resolve the connect identifier specified"



Root Cause
64-bit Microsoft OS's install 32-bit applications into the following location
"C:\Program Files (x86)\..."
rather than the typical location of


"C:\Program Files\..."
This causes an existing networking bug to occur where the networking layer is unable to parse program locations that contain parenthesis() in the path to the executable which is attempting to connect to Oracle.


Solution
Uninstall Toad from the following location
C:\Program Files (x86)\Quest Software\Toad for Oracle\


and reinstall it in the following location
C:\Oracle\Quest\Toad 9.1
(Any other location having no parenthesis in the path)

Tuesday, April 12, 2011

Disable Back Button and Right Click using JavaScript

Now a day due to security purpose sometimes it is required that we disable the functionality of Back button of the Browser. Actually we can not disable Browser Back button but we can use JavaScript and find a workaround for this. We will cover below 3 tricks in this Article one by one -
  1. Open a Window without Back Button.
  2. Disable Back functionality using history.forward().
  3. Disable the right click on any webpage using JavaScript.
Open a window without Back Button
Although this is one of the ways to hide Back button from user but at the same time there is an Alternate workaround for the user to go back the previous page. Most of the modern browsers have options of Back in context menu. Hence even if you disable Back Button, user can still right click on the page and click Back to go to previous page.(You can disable right click also as described below in this Article)
The codes to open a webpage in a new window have no toolbar (Back/Next buttons) as follows-

<HTML>
<HEAD>
<SCRIPT type="text/javascript">
    
    function openWindow() {
        //Open a new window with no toolbar
        window.open("http://emuzix.net","mywindow","status=1, toolbar=0");

    }
</SCRIPT>
</HEAD>
<BODY>
<input type="button" value="Demo Here" onClick="openWindow()"/> 

</BODY>
</HTML>



Disable Back functionality using history.forward()
Another technique to disable the back functionality in any webpage is using history.forward() method. We need to add the following codes in the webpage where we want to avoid user to get back from previous page. But here the problem is that you have to add this code in all the pages where you want to avoid user to get back from previous page. For example user follows the navigation page1 -> page2. And you want to stop user from page2 to go back to page1. In this case add following code in page1

<HTML>
<HEAD>
<SCRIPT type="text/javascript">

    function stayHere() {
        window.history.forward();
    }
</SCRIPT>
</HEAD>
<BODY onload="stayHere();">

Your Content Goes Here!

</BODY>
</HTML>



Disable the right click on any webpage using JavaScript
Basically "oncontextmenu" is responsible for opening contextmenu in a page. Add the below code to Disable the right click (Context menu) on any webpage –

<HTML>
<BODY oncontextmenu="return false;">

Your Content Goes Here!

</BODY>
</HTML>