Tuesday, December 18, 2007

Making an object without calling constructor?

Yes , thats possible in Java using the sun.reflect.ReflectionFactory
Just run this code and check out for yourself

import java.lang.reflect.*;
import java.io.Serializable;
import java.security.AccessController;
import sun.reflect.ReflectionFactory;

class Test2{
public Test2(){
System.out.println("Test 2");
}
}

class Test1 extends Test2{

int a;
public Test1(){
a=5;
System.out.println("Const Test1 "+a);
}
}

public class Test0 implements Serializable {

public Test0() {
System.out.println("Const Test0");
}

public static void main(String[] args) throws Exception {
Class c[]=new Class[0];
System.out.println(c==null);
System.out.println(Test1.class instanceof Class);
Constructor constr = reflectionFactory.newConstructorForSerialization(Test0.class, Test1.class.getConstructor(c));
Constructor constr1=Test1.class.getConstructor(new Class[0]);
System.out.println(constr.equals(constr1)+" "+constr.getName()+" "+constr1.getName() );
System.out.println(constr.getDeclaringClass().getName());
Test0 test=(Test0)constr.newInstance(new Object[0]);
System.out.println(constr.newInstance(new Object[0]).getClass());
}

private static final ReflectionFactory reflectionFactory = (ReflectionFactory)
AccessController.doPrivileged(
new ReflectionFactory.GetReflectionFactoryAction());

}

Tuesday, August 14, 2007

Deploying Web Application in Tomcat

Before discussing the organization of source code directories in Tomcat, it is useful to examine the runtime organization of a web application. A web application is defined as a hierarchy of directories and files in a standard layout. Such a hierarchy can be accessed in its "unpacked" form, where each directory and file exists in the file system separately, or in a "packed" form known as a Web ARchive, or WAR file. The former format is more useful during development, while the latter is used when you distribute your application to be installed.
The top-level directory of your web application hierarchy is also the document root of the context root of your application. Here, you will place the HTML files and JSP pages that comprise your application's user interface. Thus, if the context path is /catalog, then a request URL referring to /catalog/index.html will retrieve the index.html file.

Standard Directory Layout

To facilitate creation of a Web Application Archive file in the required format, it is convenient to arrange the "executable" files of your web application (that is, the files that Tomcat actually uses when executing your app) in the same organization as required by the WAR format itself. To do this, you will end up with the following contents in your application's "context root" directory:
*.html, *.jsp, etc. - The HTML and JSP pages, along with other files that must be visible to the client browser (such as JavaScript, style sheet files, and images). In larger applications one may choose to divide these files into a subdirectory hierarchy, but for smaller apps, it is generally much simpler to maintain only a single directory for these files.
/WEB-INF/web.xml - The Web Application Deployment Descriptor for the application. This is an XML file describing the servlets and other components that make up the application, along with any initialization parameters and container-managed security constraints that one wants the server to enforce
/WEB-INF/classes/ - This directory contains any Java class files (and associated resources) required for the application, including both servlet and non-servlet classes, that are not combined into JAR files. If the classes are organized into Java packages, they must be reflected in this directory hierarchy under /WEB-INF/classes/. For example, a Java class named com.mycompany.mypackage.MyServlet would need to be stored in a file named /WEB-INF/classes/com/mycompany/mypackage/MyServlet.class.
/WEB-INF/lib/ - This directory contains JAR files that contain Java class files (and associated resources) required for the application, such as third party class libraries or JDBC drivers.
When an application is installed into Tomcat, the classes in the WEB-INF/classes/ directory, as well as all classes in JAR files found in the WEB-INF/lib/ directory, are made visible to other classes within that particular web application. Thus, including all of the required library classes in one of these places will simplify the installation of the web application -- no adjustment to the system class path (or installation of global library files in your server) will be necessary.
Shared Library Files
Like most servlet containers, Tomcat also supports mechanisms to install library JAR files (or unpacked classes) once, and make them visible to all installed web applications (without having to be included inside the web application itself. There are two locations that are commonly used within a Tomcat installation for shared code:
$CATALINA_HOME/common/lib - JAR files placed here are visible both to web applications and internal Tomcat code. This is a good place to put JDBC drivers that are required for both your application and internal Tomcat use (such as for a JDBCRealm).
$CATALINA_HOME/shared/lib - JAR files placed here are visible to all web applications, but not to internal Tomcat code. This is the right place for shared libraries that are specific to the application.
A standard Tomcat 4 installation includes a variety of pre-installed shared library files, including:
The JavaMail 1.2 (and associated JavaBeans Activation Framework) APIs, so you can write mail-enabled web applications.
•The JDBC 2.0 Optional Package APIs, which define things like javax.sql.DataSource.
•The Servlet 2.3 and JSP 1.2 APIs that are fundamental to writing servlets and JavaServer Pages.
An XML Parser compliant with the JAXP (version 1.1) APIs, so that the application can perform DOM-based or SAX-based processing of XML documents.


Web Application Deployment Descriptor
As mentioned above, the /WEB-INF/web.xml file contains the Web Application Deployment Descriptor for your application. As the filename extension implies, this file is an XML document, and defines everything about your application that a server needs to know.

Deployment
In order to be executed, a web application must be deployed on a servlet container. This is true even during development. A web application can be deployed in Tomcat by one of the following approaches:
•Copy unpacked directory hierarchy into a subdirectory in directory $CATALINA_HOME/webapps/. Tomcat will assign a context path to the application based on the subdirectory name chosen. Be sure to restart Tomcat after installing or updating the application.
•Copy the web application archive file into directory $CATALINA_HOME/webapps/. When Tomcat is started, it will automatically expand the web application archive file into its unpacked form, and execute the application that way.
•Use the Tomcat 4 "Manager" web application to deploy and undeploy web applications. Tomcat includes a web application, deployed by default on context path /manager that allows you to deploy and undeploy applications on a running Tomcat server without restarting it.: hyperlink) for more information on using the Manager web application.
Courtsey: Tomcat Docs

Exploring AJAX

AJAX stands for Asynchronous JavaScript and XML. It is not a new programming language, but a new way to use existing standards. It is used create better, faster, and more user-friendly web applications. AJAX is based on JavaScript and HTTP requests. With AJAX, JavaScript communicates directly with the server, using the JavaScript XMLHttpRequest object. With this object, JavaScript can trade data with a web server, without reloading the page.

AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web server, allowing web pages to request small bits of information from the server instead of whole pages. It is a browser technology independent of web server software.

AJAX is based on the following web standards:

  • JavaScript
  • XML
  • HTML
  • CSS

The web standards used in AJAX are well defined, and supported by all major browsers. AJAX applications are browser and platform independent.

AJAX Uses HTTP Requests

In traditional JavaScript coding, if you want to get any information from a database or a file on the server, or send user information to a server, you will have to make an HTML form and GET or POST data to the server. The user will have to click the "Submit" button to send/get the information, wait for the server to respond, and then a new page will load with the results.

Because the server returns a new page each time the user submits input, traditional web applications can run slowly and tend to be less user-friendly.

With AJAX, JavaScript communicates directly with the server, through the JavaScript XMLHttpRequest object

With an HTTP request, a web page can make a request to, and get a response from a web server - without reloading the page. The user will stay on the same page, and he or she will not notice that scripts request pages, or send data to a server in the background.

AJAX - Browser Support

The keystone of AJAX is the XMLHttpRequest object. Different browsers use different methods to create the XMLHttpRequest object. Internet Explorer uses an ActiveXObject, while other browsers use the built-in JavaScript object called XMLHttpRequest.

The code above is compatible with all the popular browsers: Internet Explorer, Opera, Firefox, and Safari.

Sample AJAX Example

The entire source code can be downloaded my website.


input type="button" onClick="getTime()" value="Get Date"
div id="t2"

The above line shows the HTML for the “Get Date” button. On clicking this button the “getTime” method gets called as is evident from the “onClick” attribute. Below is the “getTime” method that actually makes the AJAX calls and hits the “Get Date” Servlet.

// Function For The Second Part Of The Document i.e Get Time

function getTime()

{

xmlHttp=getXMLHttp();

if(xmlHttp==null)

{

alert('Your Browser Does Not Support AJAX!');

}

else

{

xmlHttp.onreadystatechange=functionTime;

xmlHttp.open("GET","/AJAX/GetDate",true);

xmlHttp.send(null);

}

}

function functionTime()

{

if(xmlHttp.readyState==4)

t2.innerHTML=xmlHttp.responseText;

}

The XMLHttpObject hits the GetDate Servlet and when the response is ready the functionTime gets executed, which displays the value on the page. Below is the functional part of the GetDate Servlet.

protected void processRequest(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

PrintWriter out = response.getWriter();

out.println("

Date From Server Is: " + new java.util.Date() + "

");

out.close();

}

As is evident the Servlet is just pushing the current date into the output Stream which gets displayed on the page.



Friday, August 3, 2007

Exploring JSF

JSF is the latest addition to the list of J2EE frameworks. Lets try to get an insight into what JSF is and why it is the hottest technology being used in the Java Enterprise applications.

JSF stands for "Java Server Faces" and this technology is a "server-side user interface component framework for Java technology-based web applications". The words do sound confusing.

So, in simple terms, JSF is a MVC based framework which brings forth a technology where the UI components are much more than being just normal HTML tags, as is the case with all other frameworks. Each component has its own class in the JSF API and thus every UI component is represented by a Server Side Object which stores the component state on the server. Then there is a “Renderer” for each component which generates the HTML for displaying the component. This renderer layer enables the use of JSF technology on different devices, without any change in the component API. If we want to use JSF with a mobile device, we can just change the renderer kit to one which generates WML instead of HTML. A UI Component class can combine with different renderers to generate different HTML components. So, a change in look-and-feel of a component can be affected by just adding a new renderer and more importantly without adding a new component or changing the API.

Also, the UI Components of JSF are listeners and events enabled, pretty much like the Java Swing Components. By storing the components as objects it becomes easier to associate events and listeners with them and thus JSF can also be seen as the introduction of Java Swing-style components into the web world.

The framework uses FacesServlet as the controller Servlet, so as is the principle of MVC architecture, every request first goes to the FacesServlet which then delegates it to the requisite page. This controller uses a configuration file faces-config.xml, where all the navigation and managed bean related declarations are done.

The UI layer mainly uses the JSPs but the introduction of Facelets has provided a new developer friendly alternative. The Facelets aim to make JSF a completely independent technology.
Facelets is a powerful templating system that allows you to define JSF views using HTML-style templates, reduces the amount of code necessary to integrate components into the view, and doesn't require a web container. While Java Server Faces and JSP are meant to be aligned, Facelets steps outside of the JSP specification and provides a highly per formant, JSF-centric view technology. Anyone who has created a JSP page will be able to do the same with Facelets and familiar XML-tag use. The difference is under the hood where all the burden of the JSP vendor API is removed to greatly enhance JSF as a platform and provide easy plug-and-go development without requiring JSP tag development.

Managed Beans are at the heart of JSF Technology. They are nothing but the Java Bean classes whose objects are instantiated by the framework as and when required and placed in the specified scope i.e. request, session or application. These are the classes which provided dynamism to a JSP. The request parameters may be set as the attributes of these objects and may be accessed on any other page. These classes may also contain methods containing the validators and listeners for the various components on the page.

Also, there are the features of Validators and Converters that can be used with UI Input type components. Converters are used to convert the data into other data types e.g. Date Converters and Number Converters. Validators as the name suggests are used to give the front end validation logic for the components e.g. email validation, string length validation etc.

The frame is fully extensible in the sense that a developer has full freedom to introduce a new component, renderer, converter or validators to suit his needs. Once written they just have to be registered in faces-config and then they are ready to use.

Introduction

The posts here will mainly deal with the concepts of Java and J2EE. I would like to bring up some interesting aspects of Java and specifically J2EE. The aim will be to pen down the knowledge that I have been able to acquire while working as a Java programmer. Comments and suggestions are solicited.