12 May 2006
How to deploy a JSF Application built in JSCreator on Websphere App Server Express 6.0
The application which I deployed to WAS contains around 35 JSF pages & JSF components used from different sources like myfaces-tomahawk (Apache) & Sun, POI (Apache) library to export data in XLS & FOP (Apache) library to generate memos in RTF format. This application includes JAAS security authorization. For authentication WAS 6.0 is configured to use local OS users’ registry.
Before following these steps make sure everything works properly in Sun App Server.
Following are the steps :
1) First of all WAS 6.0 is based on JDK 1.4.2. Hence if you are using JDK 1.5 API calls in your application which is not supported in JDK 1.4.2 then you have to replace those API calls with their equivalents in JDK 1.4.2. In JSCreator a good way to this is to Add a new platform from Project Ecplorer >
2) If your application uses Web Container security, mind you, it’s applicable only to the urls which are sent from client to server in case of Websphere. For server side redirects you will see url patterns secured through security constraint specification in web.xml not being applied. It works for server side redirects also in Sun App Server. Therefore if you have applied security constraint on the url pattern “/faces/*” because you want to protect all your JSF pages and you have set your welcome page as “faces/Index.jsp”, it will be directly rendered on your browser without being asked for authentication. To fix this problem create an index.html page & in it through javascript code "location.href='url'" set the url to your welcome page. This will make browser to make a client side request to a protected resource making the server to render the login page that was configured for form authentication.
3) WAS seems to be stringent about processing included jsp files. Any included jsp file shouldn’t only have the extension 'jspf' or any other supported extension but also should contain <jsp:root> element to indicate WAS 6.0 JSP compiler that it is a JSP page if your JSP page in standard xml format. I haven’t expored behavior of WAS 6.0 JSP compiler with non-xml JSP pages. So, if your included JSP page has first tag as <div> to resolve xml namespaces used on the page, add a <xml> directive & a <jsp:root> element with all the namespaces defined for <div> tag. Remove these namespaces from <div> tag. Strangely enough this page doesn’t compile for Sun App Server. So you will have make change suggested above every time before proceeding to take following steps.
4) Right click on project name node in project explorer of JSCreator. Choose "clean project" to clean your project. Now choose "Export as WAR file" from the same context menu to export your project at a convenient location from where you can import the WAR file into one of the application assembly tools from IBM (Application Server Toolkit, Rational Developer etc.).
5) Now you have got to assemble your application using one of the application assembly tools from IBM as exemplified above. I used Application Server Toolkit (Henceforth referred as AST) which is a built by customization of popular Java IDE called eclipse. Hence following steps pertain to AST :
- i) Choose File > Import > WAR File to import the WAR file created in step 2. While importing, AST imports it as a "Dynamic Web Project". Also make sure to add it to a EAR project. This adds your web project to an enterprise project, which then becomes a deployable unit for WAS 6.0 properly configured with security roles & users/groups mappings. Save it to a location different from file being imported.
- ii) Now in the project explorer window navigate to Enterprise Projects > project-name > Deployment Descriptor. Double click on "Deployment Descriptor" node to open it with Deployment Descriptor Editor.
- iii) Open the security tab. Add the security role. After adding the role enable the authentication method "Users/Groups" option which will let you add users & groups mapping for a particular role. Add appropriate values. Save the changes & close the deployment descriptor editor.
- iv) Now right click on Enterprise Projects > <project-name > and choose to Export EAR file from the context menu. Save it at a location different from previous 2 files.
This completes the assembly of your application.
6) Now before deploying the application to WAS 6.0 we need to complete some security related & datasource configurations in WAS 6.0
- i) Login to WAS 6.0 admin console at http://<host>:<admin-port>/ibm/console. If security is not enabled it will allow you anonymous login. Otherwise you will have to provide a valid administrator user id & password according to the security policy defined in WAS 6.0 . If security is already enabled jump to setp (iii)
- ii) After you do anonymous login, go to Security > Global Security and click on the option "Enable Global Security".
- iii) If "Enforce Java 2 Security" option gets enabled as result of step no. ii) or if it is already enabled then disable this option.
- iv) Just check whether the values for following parameters match :
Active Protocol – CSI and SAS
Active Authentication Mechanism – Simple Websphere
Authentication Mechanism
User Registry – Local OS - v) Define OS level users & organize them in their respective groups just as you defined in step 4-iii) above.
- vi) On this page itself navigate to JAAS Configuration > J2C Authentication Data > New. Create a new use alias as "db2user" & assign username & password value who owns your DB2 database.
- vii) Navigate to Resources > JDBC Providers. If DB2 Universal JDBC Driver Provider is already defined just check whether its specifications meet the details given in this step then move to step viii) this section. Otherwise click on New. On the new page choose following values for different parameters.
Database Type – DB2
Provider Type - DB2 Universal JDBC Driver Provider
Implementation Type – connection pool data source
Click on ‘Next’. On new page, in the classpath section just check whether db2 jar files are located at proper places or not. Generally it is not. To check environment variable values navigate to Environment > Websphere variables. Make appropriate changes to the environment variables or JDBC provider specification or even jar file location in the file system to see everything is proper. Let other default values be as it is. Now save your changes to Master configuration. - viii) Now choose "data source" on the same page. Here specify your data source name & the jndi name which will have the binding to your data source. Specify other database connection related parameters. For the "Component-managed authentication alias" choose the J2C Authentication Data configured in step vi). Save the configuration & press "Test Connection" to check your configuration is all right. Reset "Component-managed authentication alias" method to none & save your configuration.
- ix) Navigate to servers > Web Servers to see whether you have any instance of web server created, up & running . If not create a web server instance and start it.
Configuration of WAS 6.0 is now complete & you are ready to deploy the application.
7) Navigate to Applications > Enterprise Applications to see whether any instance of application that you are trying to deploy is already deployed. If yes, uninstall it first.
8) Choose Applications > Install New Application. Follow the steps to deploy your application. Please read the instructions carefully on each page before submitting each of this 6 step process. You have to be particularly careful at following places.
i) At second step namely "choose to generate default bindings & mappings" enable the option to "generate default bindings". In the virtual host section select "use default virtual host for web modules".- ii) When you are asked to map modules to servers, select one instance of app server & one instance of web server for each web module. Do it as instructed on this page.
- iii) Second, when you are configuring data sources choose the data source you configured in step 5-viii), choose your web application & press apply. For authentication method choose container & select the J2C authentication method defined in step 5-vi).
9) Once your deployment is done & you have saved the data to Master configuration, go to Applications > Enterprise Application. Select the application you just deployed. Set the class loader policy to "Parent Last". Save it. On the same page choose Web Modules > <web-module-war> . Here also set the class loader policy to "Parent First". Save your changes to the Master configuration. This forces WAS 6.0 to load & refer to libraries from your web application first when code in your application refers to them.
10) Now go to Applications > Enterprise Application and start the application which you deployed. Web module’s context name is same as that of WAR file. So, to invoke your application the URL should be http://<host>:<application-port>/<WAR file name without .war extension> .
All the best !!!
Best Regards
-Ajay K
28 April 2006
Useful Links for Agile
Good explanation about Agile:-
http://www.agileadvice.com/archives/interesting/index.html
Agile Documents(Pdf/Ppt):-
http://www.rallydev.com/agile_knowledge.jsp
Invention of Scrum:-
http://www.agilealliance.com/articles/sutherlandjeffinventi/file
Scrum Podcasts:-
http://blogs.conchango.com/howardvanrooijen/archive/category/32.aspx
Scrum on Wikipedia
http://en.wikipedia.org/wiki/Scrum_%28in_management%29
Everything with good Examples.
Everything I mean Scrum, Ajax, Software Design, Software writing, Summer Internships very well described with an example.
http://www.joelonsoftware.com/
Sachin...
15 February 2006
Free Cross Browser UI APIs
Have a look at the site http://developer.yahoo.net/yui/ - a set of Free
UI controls & objects provided by Yahoo... Also has some good
information on how Yahoo approaches cross-browser support.
14 February 2006
ObjectOriented JavaScript
* Null,
* Boolean,
* Number, and
* String.
var NumericalValue = 354;
var StringValue = "This is a String";
alert(typeof BooleanValue) // displays "boolean"
alert(typeof NumericalValue) // displays "number"
alert(typeof StringValue) // displays "string"
An Object
These properties can either be primitive data types, other objects, or functions (which in this case are called methods).
A constructor function (or simply, constructor) is a function used to create an object.
JavaScript comes with many built-in objects, such as the Array, Image, and Date objects.
Image1.src = "myDog.gif";
the src property.
Image1 is a new Image object; in other words, it is an instance of the Image object.
Using JavaScripts dot-structure ( . ), the code above then accesses and sets the src property of
your new Image object.
}
alert(typeof myObject); // displays "object"
In fact weve created a myFunc object. myFunc() is a constructor function; it lays out the blueprint from
which objects that are created from it will follow (although, in this case, it doesnt lay out much of a blueprint).
So, how does JavaScript know to create an instance of the myFunc object, rather than to return its results?
Lets compare the example above with the following, more conventional use of a function:
return 5;
}
alert(typeof myObject); // displays "number"
So, whats the difference between these two scripts? Answer: the new keyword.
It tells JavaScript to create an object following the blueprint set forth in the myFunc() constructor function.
In fact, when we create an Image object, we do the same thing, except that instead of using our own constructor
function, we use one of JavaScripts built-in constructor functions, the Image() constructor function.
function. In our example, weve created a myFunc() constructor and created an instance of the myFunc object,
which we assigned to the variable myObject.
myObject can be assigned properties:
}
myObject.StringValue = "This is a String";
alert(myObject.StringValue); // displays "This is a String"
However, if we create another instance of the myFunc object (using the myFunc() constructor function),
we also have to assign the StringValue property to this new instance. For example:
}
myObject.StringValue = "This is a String";
var myObject2 = new myFunc();
alert(myObject2.StringValue); // displays "undefined"
this.StringValue = "This is a String";
}
var myObject2 = new myFunc();
alert(myObject2.StringValue); // displays "This is a String"
but every object can have its own distinctive value for StringValue.
In other words, we can change the StringValue property for one myFunc object, without affecting the others:
this.StringValue = "This is a String";
}
myObject.StringValue = "This is myObject's string";
var myObject2 = new myFunc();
alert(myObject.StringValue); // displays "This is myObject's string"
alert(myObject2.StringValue); // displays "This is a String"
this.StringValue = StringValue;
}
var myObject2 = new myFunc("This is a String");
alert(myObject.StringValue); // displays "This is myObject's string"
alert(myObject2.StringValue); // displays "This is a String"
while StringValue refers to the functions local variable that was passed as an argument.
So, now that weve assigned properties to objects, what about methods?
An object's method is a function it can perform. Let's take a look at this example.
For this one, lets create a Circle object. First, were going to have to define our functions,
and then make them methods of our Circle object. Lets define our Circle() constructor and a Circle object or two:
function Circle(radius){
this.radius = radius;
}
var smallCircle = new Circle(2);
return (this.radius*this.radius*3.14);
}
var diameter = this.radius*2;
var circumference = diameter*3.14;
return circumference;
}
this always refers to the current object, in this case, the Circle object.
So this.radius refers to the radius property of the Circle object.
So, how do we attach these functions to our object? Its not as hard as you might think.
Lets change our Circle() constructor:
this.radius = radius;
this.getArea = getArea;
this.getCircumference = getCircumference;
}
alert(bigCircle.getCircumference()); // displays 618
alert(smallCircle.getArea()); // displays 12.56
alert(smallCircle.getCircumference()); // displays 12.56
Native objects are those objects supplied by JavaScript. Examples of these are String, Number, Array, Image,
Date, Math, etc.
Host objects are objects that are supplied to JavaScript by the browser environment. Examples of these are
window, document, forms, etc.
And, user-defined objects are those that are defined by you, the programmer.
except for the primitive data types.
We can use JavaScripts built-in constructor functions (just like the ones weve created) to create objects:
Image1.src = "myDog.gif";
* height = 100
* src = "myDog.gif"
var myObj = new Object();
Every object in JavaScript derives from JavaScripts native Object object.
alert(myString); // displays "This is my string"
alert(typeof myString); // displays "string"
alert(myString); // displays "This is my string"
alert(typeof myString); // displays "object"
But why would we want to? Well, once we've done that, we can add distinctive properties and methods to that object.
A primitive data type contains the properties and methods laid out in its object constructor,
but it cannot, itself, hold any distinctive properties/methods.
For example, a String primitive data type contains the length property as well as the many methods defined in
the native String() object constructor, such as substring().
However, a String object contains the properties and methods defined in the String() object constructor as well
as any unique values assigned to that particular object.
Now, lets create a Number object and add a method to it:
myNumber.doubleIt = new Function("return this*2");
alert(myNumber.doubleIt()); // displays 4
alert(typeof myNumber); // displays "object"
Note that typeof myNumber is "object". This is because objects are able to contain unique properties and methods.
Primitive data types, such as String, Boolean, Number, Undefined, and Null, cannot,
and this is what differentiates the two.
However, the Function object is different. When we create an object, we first enter the new keyword,
then follow it with the object constructor function, and this returns a new instance of that particular object.
Then, using the returned value (which we usually assign to a variable),
we can add properties and methods to that object. However, because a Function object is also a callable block
of code, JavaScript makes the distinction and tells us that its not only an object (which it is, as we can add
properties and methods to it), but is also a callable block of code. So, when we enter:
The Function() constructor function can take more arguments. The last argument passed to the Function()
constructor becomes the body of the function, while the others become parameters:
"parameter3"," // function body");
And a function is always an object - it always has the ability to hold unique properties and methods.
The creation of a function automatically creates a Function object:
myFuncObj.someVariable = "x";
alert(myFuncObj.someVariable) // displays "x"
Note that the Function() constructor is a special case all other constructors must be called with the new
keyword, or they simply return a value, instead of a new object.
var pimitiveString2 = String("This is a primitive string");
var stringObject = new String("This is a String object");
primitiveString2.prop = "This is a property";
stringObject.prop = "This is a property";
alert(primitiveString2.prop) // displays "undefined"
alert(stringObject.prop) // displays "This is a property"
alert(typeof primitiveString2); // displays "string"
alert(typeof stringObject) // displays "object"
but instead, we assign the returned value (which is a primitive data type, String) to a variable.
You can also see that primitiveString1 and primitiveString2 are not objects, as we cannot assign them properties.
Note that primitiveString1/primitiveString2 and stringObject return different results when used with the typeof
operator. This is even true for Date, Image, Option, and other objects. For example:
var x = Date();
alert(typeof x); // displays "string"
var myFuncObj = Function();
var myFuncObj = function(){}
function myFuncObj(){}
27 January 2006
Factory Pattern
Creational Patterns:
Creational Patterns are design patterns that deal with object instantiation mechanisms, trying to create objects in manner suitable to situation. In software engineering creational design patterns are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. The basic form of object creation could result in design problems or added complexity to the design.Creational design patterns solve this problem by somehow controlling this object creation.
Some examples of creational design patterns include:
- Abstract factory pattern
- Anonymous subroutine objects pattern
- Builder pattern
- Factory method pattern
- Lazy initialization pattern
- Prototype pattern
- Singleton pattern
Factory Pattern:
The Factory Method pattern is an object-oriented design pattern. Like other creational patterns, it deals with the problem of creating objects (products) without specifying the exact class of object that will be created. Factory Method, one of the patterns from the Design Patterns book, handles this problem by defining a separate method for creating the objects, which subclasses can then override to specify the type of product that will be created. More generally, the term Factory Method is often used to refer to any method whose main purpose is to create objects.
The Problem
One of the goals of object-oriented design is to delegate responsibility among different objects. This kind of partitioning is good since it encourages Encapsulation and Delegation. Sometimes, an Application (or framework) at runtime, cannot anticipate the class of object that it must create. The Application (or framework) may know that it has to instantiate classes, but it may only know about abstract classes (or interfaces), which it cannot instantiate. Thus the Application class may only know when it has to instantiate a new Object of a class, not what kind of subclass to create.
A class may want it's subclasses to specify the objects to be created.
A class may delegate responsibility to one of several helper subclasses so that knowledge can be localized to specific helper subclasses.
The Solution
Factory Method is a creational pattern. This pattern helps to model an interface for creating an object which at creation time can let its subclasses decide which class to instantiate. We call this a Factory Pattern since it is responsible for "Manufacturing" an Object. It helps instantiate the appropriate Subclass by creating the right Object from a group of related classes. The Factory Pattern promotes loose coupling by eliminating the need to bind application-specific classes into the code. Factories have a simple function: Churn out objects. Obviously, a factory is not needed to make an object. A simple call to new will do it for you. However, the use of factories gives the programmer the opportunity to abstract the specific attributes of an Object into specific subclasses which create them.
Example:
/**
* Represents a Resource present at some URL.
*/
abstract class Resource {
/**
* Creates a resource specified at location.
* @param location URL
* @return Resource
*/
public static Resource getResource(URL location) {
final String protocol = location.getProtocol();
Resource resource = null;
if (protocol.equals("file")) {
resource = new LocalResource();
} else if (protocol.equals("ftp")) {
resource = new FTPResource();
} else if (protocol.equals("http")) {
resource = new HTTPResource();
}
return resource;
}
/**
* @return Returns identifier resource type.
*/
public abstract String getIdentifier();
}
/**
* Represents a local file system resource.
*/
final class LocalResource extends Resource {
private final String identifier = "Local";
public String getIdentifier() {
return identifier;
}
}
/**
* Represents a resource present at FTP site.
*/
final class FTPResource extends Resource {
private final String identifier = "FTP";
public String getIdentifier() {
return identifier;
}
}
/**
* Represents a resource present at HTTP site.
*/
final class HTTPResource extends Resource {
private final String identifier = "HTTP";
public String getIdentifier() {
return identifier;
}
}
public class ResourceFactoryTest {
public static void main(String[] args) throws Exception {
Resource resource = Resource.getResource(
new URL("file://C:/dummy.txt"));
System.out.println("Obtained resource from: "
+ resource.getIdentifier());
resource = Resource.getResource(
new URL("ftp://ftp.omniscientweb.com/resources/dummy.txt"));
System.out.println("Obtained resource from: "
+ resource.getIdentifier());
resource = Resource.getResource(
new URL("http://www.omniscientweb.com/index.htm"));
System.out.println("Obtained resource from: "
+ resource.getIdentifier());
}
}
Executing above code will print:
Obtained resource from: Local
Obtained resource from: FTP
Obtained resource from: HTTP
Above code can be the simplest example simulating factory pattern. Class Resource, is an abstract class which defines a general contract for the “Resource”. The Resource class has a static getResource method which creates a resource given the resource location.
The resource may be present at either local system, ftp site or it may be http resource or even it can be present at NFS.
Typically we don’t want to expose the actual implementations of the Resource. As I had mentioned in last article “it is always better to code to the interface instead of coding to specific implementations”, suppose we always use the Resource contract and never are concerned with the actual implementations. The factory method for the Resource class takes the URL, identifies the protocol required to communicate with resource and creates the specific subclass instance.
This methodology gives us flexibility to change the underlying Resource implementations for the protocols without hampering the system. We can even transparently and easily add another type of resource in future. This is how most of the Factory methods in the APIs provide abstraction over their API.
24 January 2006
Some more infoe about XMLHttpRequest
traditional Web where you have a very distinct request and response model. For example, go to Amazon.com and
click a button or enter a search term. A request is made to a server and then a response comes back to your browser.
That request has a lot more than just a list of books and titles, though; it's actually another complete HTML page.
As a result, you probably get some flashing or flickering as your Web browser's screen is redrawn with this new HTML page.
In fact, you can clearly see the request and response, delineated by each new page you see.
The Web 2.0 dispenses with this very visible back-and-forth (to a large degree). As an example,
visit a site like Google Maps or Flickr (links to both of these Web 2.0, Ajax-powered sites are in Resources).
On Google Maps, for example, you can drag the map around and zoom in and zoom out with very little redrawing.
Of course, requests and responses do go on here, but all behind the scenes. As a user, the experience is much
more pleasant and feels a lot like a desktop application. This new feel and paradigm is what you see when someone
refers to Web 2.0.
Obviously, you've still got to make requests and field responses, but it's the redrawing of the HTML for
every request/response interaction that gives the perception of a slow, clunky Web interface. So clearly you need
an approach that allows you to make requests and receive responses that include only the data you need, rather than
an entire HTML page as well. The only time you want to get a whole new HTML page is when you want the user to see
a new page.
But most interactions add details or change body text or overlay data on the existing pages. In all of these
cases, Ajax and a Web 2.0 approach make it possible to send and receive data without updating an entire HTML page.
Sending requests with XMLHttpRequest
is to allow us to make requests and receive responses. Everything else changing the user interface, swapping out
images, even interpreting the data that the server sends back is the job of JavaScript, CSS, or other code in our
pages.
Ajax has a sandbox security model. As a result, Ajax code (and specifically, the XMLHttpRequest object) can
only make requests to the same domain on which it's running. The code running on our local machine can only make requests
to server-side scripts on our local machine.
With a URL to connect to, we can configure the request. we can accomplish this using the open() method on
XMLHttpRequest object. This method takes as many as five parameters:
* request-type: The type of request to send. Typical values are GET or POST, but we can also send HEAD requests.
* url: The URL to connect to.
* asynch: True if you want the request to be asynchronous and false if it should be a synchronous request.
This parameter is optional and defaults to true.
* username: If authentication is required, you can specify the username here.
This is an optional parameter and has no default value.
* password: If authentication is required, you can specify the password here.
This is an optional parameter and has no default value.
Internet developers disagree about what exactly the open() method does. What it does not do is actually open a
request. If you were to monitor the network and data transfer between your XHTML/Ajax page and the script that it
connects to, you wouldn't see any traffic when the open() method is called. It's unclear why the name was chosen,
but it clearly wasn't a great choice.
Example:
function getCustomerInfo() {
var phone = document.getElementById("phone").value;
var url = "/cgi-local/lookupCustomer.php?phone=" + escape(phone);
request.open("GET", url, true);
}
parameter, the content to send.Although we can send data using send(), we can also send data through the URL itself.
In fact, in GET requests (which will constitute as much as 80 percent of your typical Ajax usage), it's much easier
to send data in the URL. When you start to send secure information or XML, then you want to look at sending content
through send() . When you don't need to pass data along through send(), then just pass null as the argument to this
method.
When a request is set up and then made, because this is asynchronous request, the JavaScript method
(getCustomerInfo() in the example) will not wait for the server. So the code will continue; in this case, that
means that the method will exit and control will return to the form. Users can keep entering information and
the application isn't going to wait on the server.This creates an interesting question, though: What happens when
the server has finished processing the request? The answer, at least as the code stands right now, is nothing!
Obviously, that's not good, so the server needs to have some type of instruction on what to do when it's finished
processing the request sent to it by XMLHttpRequest.This is where that onreadystatechange property comes into play.
This property allows you to specify a callback method. A callback allows the server to call back into your Web page's
code. It gives a degree of control to the server, as well; when the server finishes a request, it looks in the
XMLHttpRequest object and specifically at the onreadystatechange property. Whatever method is specified by that
property is then invoked. It's a callback because the server initiates calling back into the Web page regardless
of what is going in the Web page itself. This is actually where the asynchronicity comes into play: The user operates
the form on one level while on another level, the server answers a request and then fires off the callback method
indicated by the onreadystatechange property.
After the server finishes up handling the request. The server looks at the onreadystatechange property
and figures out what method to call. Once that occurs, you can think of your application as any other app,
asynchronous or not. In other words, you don't have to take any special action writing methods that respond to
the server; just change the form, take the user to another URL, or do whatever else you need to in response to
the server.
The server, once finished with a request, looks up what method to call in the onreadystatechange property
of XMLHttpRequest. That's true, but it's not the whole truth. In fact, it calls that method every time the
HTTP ready state changes. So what does that mean? Well, you've got to understand HTTP ready states first.
An HTTP ready state indicates the state or status of a request. It's used to figure out if a request has
been started, if it's being answered, or if the request/response model has completed. It's also helpful in
determining whether it's safe to read whatever response text or data that a server might have supplied.
we need to know about five ready states in our Ajax applications:
* 1: The request is set up, but hasn't been sent (before you've called send()).
* 2: The request was sent and is being processed (you can usually get content headers from the response at this point).
* 3: The request is being processed; often some partial data is available from the response, but the server hasn't finished with its response.
* 4: The response is complete; you can get the server's response and use it.
expect to always see the ready state move from 0 to 1 to 2 to 3 to 4, but in practice, that's rarely the case.
Some browsers never report 0 or 1 and jump straight to 2, then 3, and then 4. Other browsers report all states.
Still others will report ready state 1 multiple times.
For Ajax programming, the only state you need to deal with directly is ready state 4, indicating that a
server's response is complete and it's safe to check the response data and use it. To account for this, the first
line in your callback method should be as shown
if (request.readyState == 4)
alert("Server is done!");
}
What if the server responds to your request and finishes processing, but reports an error? Remember,
your server-side code should care if it's being called by Ajax, a JSP, a regular HTML form, or any other type
of code; it only has the traditional Web-specific methods of reporting information. And in the Web world,
HTTP codes can deal with the various things that might happen in a request.For example, you've certainly entered
a request for a URL, typed the URL incorrectly, and received a 404 error code to indicate a page is missing.
This is just one of many status codes that HTTP requests can receive as a status. 403 and 401, both indicating
secure or forbidden data being accessed, are also common. In each of these cases, these are codes that result
from a completed response. In other words, the server fulfilled the request (meaning the HTTP ready state is 4),
but is probably not returning the data expected by the client.In addition to the ready state then, you also need
to check the HTTP status. You're looking for a status code of 200 which simply means okay. With a ready state
of 4 and a status code of 200, you're ready to process the server's data and that data should be what you asked
for (and not an error or other problematic piece of information).
if (request.readyState == 4)
if (request.status == 200)
alert("Server is done!");
else if (request.status == 404)
alert("Request URL does not exist");
else
alert("Error: status code is " + request.status);
}
JUnit - Creating a one-time Setup
However, what is not obvious to must developers is how JUnit works with your testcases. Consider a situation where you have created a test class which executes multiple test cases (or methods). The JUnit framework will do the following -
1. Check for a method with the signature "public static Test suite()"
- ELSE -
Use reflection to identify all methods starting with "test"
2. Create separate threads for each method identified
3. Create an instance of the testcase class in each thread
4. Invoke the setUp() method to initialize fixtures (or pre-requisites for a test method)
5. Invoke one method of the testcase class in each thread
6. Invoke the tearDown() method to clean up fixtures
The important thing here is that JUnit runs each test method in a separate instance, the constructor, setUp() & tearDown() methods once for each test method. In case you want to do some heavy-weight processing, like pre-loading a database, then doing it in setUp() or the constructor can cause an issue.
But fear not, like all good solutions, JUnit provides a solution under the covers. This is provided by the TestSetup class in the junit.extensions package. Comment/Uncomment any one of the suite() methods at a time in the code below to see how various features of JUnit can be controlled.
...Enjoy !!!
M1l@n
------------------------------------------------------
import junit.extensions.TestSetup;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class OneTimeSetupTestCase extends TestCase {
public OneTimeSetupTestCase() {
super();
System.out.println("Constructor Called");
}
public OneTimeSetupTestCase(String name) {
super(name);
System.out.println("Constructor Called");
}
// Uncomment this method to see how the suite takes precedence over the auto-identification of methods
// public static Test suite() {
// TestSuite suite = new TestSuite("JUnit Sample with One Time Setup");
// System.out.println("Executing Suite - " + suite.getName());
// suite.addTestSuite(OneTimeSetupTestCase.class);
// return suite;
// }
// Uncomment this method to see how the suite can be configured to execute specific tests
// public static Test suite() {
// TestSuite suite = new TestSuite("JUnit Sample with One Time Setup");
// System.out.println("Executing Suite - " + suite.getName());
// suite.addTest(new OneTimeSetupTestCase("testFirstTest"));
// suite.addTest(new OneTimeSetupTestCase("testThirdTest"));
// return suite;
// }
// Uncomment the following method to see how the one time setup/teardown methods are invoked
// public static Test suite() {
// TestSuite suite = new TestSuite("JUnit Sample with One Time Setup");
// System.out.println("Executing Suite - " + suite.getName());
// suite.addTest(new OneTimeSetupTestCase("testFirstTest"));
// suite.addTest(new OneTimeSetupTestCase("testThirdTest"));
// return createWrapper(suite);
// }
public static Test createWrapper(Test suite) {
TestSetup wrapper = new TestSetup(suite) {
public void setUp() {
oneTimeSetUp();
}
public void tearDown() {
oneTimeTearDown();
}
};
return wrapper;
}
private static void oneTimeSetUp() {
System.out.println("Suite-level Setup Called");
}
private static void oneTimeTearDown() {
System.out.println("Suite-level Teardown Called");
}
public void setUp() {
System.out.println("Unit-level Setup Called");
}
public void tearDown() {
System.out.println("Unit-level Teardown Called");
}
public void testFirstTest() {
System.out.println("First Test");
}
public void testSecondTest() {
System.out.println("Third Test");
}
public void testThirdTest() {
System.out.println("Third Test");
}
}
29 December 2005
Problems with AJAX
Hi All,
The Following is a extract from http://www.softwareas.com/ajax-podcastSome of the Problems with ajax are
It’s Hard to Code
Any Javascript usually makes life more difficult, and early discussions indicate AJAX is no different. At present, coding for AJAX may well be more difficult, although if you look at the code examples around, you’ll see that you’re not exactly facing a Turing Test either. In any event, it’s inevitable that design patterns and supportive frameworks will emerge. A few frameworks already facilitate this mode of development: the always-controversial, uber-funky Ruby On Rails, JSON-RPC-Java, Dynamic Web Remoting. SAJAX, Echo 2. Fortunately for evolution, a wide variety of approaches is being taken. Cross-fertilisation will undoubtedly follow.
In particular, the best frameworks will probably generate as much Javascript as possible, so developers don’t need to co-ordinate between Javascript and server-side controllers.
Testability May Suffer
It’s nice to be able to perform system tests with a robot like httpUnit. Any use of Javascript makes that more difficult. At the same time, because AJAX promotes a more component-based architecture, unit testing may actually be improved. With a good design, it should be quite feasible to test the scripts that are accessed by the XMLHttpRequest object.
Accessibility May Suffer
Any form of interactivity is often anathema to many different types of specialised needs. Nevertheless, this should not stop the technology from progressing, and providing rich interaction to those who can use it. As always, accessibility must be maintained, and multiple mechanisms might be required. Furthermore, new technologies can improve accessibility too. It’s easy to imagine, for example, how an AJAX-enabled site could let users quickly resize and move around certain screen elements to meet their individual needs.
AJAX Will Collapse the Network
AJAX does represent a potential challenge to networking infrastructure. Traditional web applications can feel like earlier client-server applications. Submit your offerings, then receive a response and meditate on it for a while. AJAX makes the term “web application” a lot more honest. The server really is involved, possibly even after each keystroke. Interestingly, bandwidth requirements may go down because usually only small changes need to be sent each way. However, latency is another question: using an AJAX application might feel like typing against a slow telnet connection. Stuff… hap…pens…much…sl..ower…than you…can…think… .
This will probably not be a major concern on intranets, where there are relatively few users and usually good connectivity to the server (especially as it’s often nearby). However, it’s still an open question how AJAX will be used on the public web. Certainly, it can be used to incrementally improve just about any form-based application. And it can surely go beyond that, as Google demonstrates. But can it scale to the requirements of a major site, offering a fully-scaleable wiki or genuinely playable gaming?
It’s Just a Name, the Tech’s Not New At All
XMLHttpObject has been around for a few years, but it would be hard to believe anything called “XMLHttpObject” could trigger a revolution on the PCs of the world. Frames and IFrames supported this sort of interaction even earlier. History and logic would suggest that a standard name and community, combined with some flagship applications, are powerful tools indeed. And the timing is right: users have lived with static web applications long enough, broadband is now mainstream, and the economy hungers for innovation. The raw technology may have been around, and even used in doses.
Flash Can Do All This, and MoreFlash is a bit of a mystery, since it’s extremely cross-platform, having excellent support on all the major browsers and platforms. And yet, it’s never taken off for serious application work. In fact, it’s really been used for not much more than ads and fancy presentations. It’s certainly capable of doing much more serious applications, and maybe Flash MX will still shine. It took a long time for Macromedia to target serious development. Perhaps this was a strategic mistake, or perhaps it was an intentional means of gaining wide browser share.
Software Design Patterns
Hi all,
I would like to share some important things on Software Design. As we are
keeping up to date with latest technology we also must be up to the mark
with some basics.
Software Design is a very
important aspect of Software engineering. After coming here I have learnt a lot
about design, which I feel is just the bit of it. We are involved in very high
end work in product engineering, which demands more of us every time and is
very challenging. Design becomes an important aspect of our work.
Software Design:
Software Design helps us develop scalable piece of software. The design
lays down general structure of the software. We identify various components
of the system and their responsibilities. The contract between individual
components is defined. The contract is the way two components speak to each
other, what services a component offers to outside world. Other components
always use this common service interface to talk to the component.
Well, this is being too theoretical! Let me put it ‘Java way!’ Our components
are our classes, or packages or even the set of packages. These together provide
some common set of services to the entire software. These components are nothing
but bunch of interfaces, which are ‘Contracts’ The best methodology is we always
code to the interfaces, in the sense we always use the set of methods defined in
the interface rather than using specific implementation classes to communicate
with the components. That is why we always use Collection interface but
we are least bothered about the underlying implementation of the Collection, it
may be ArrayList, Vector etc. This gives us complete freedom to change the
underlying implementation without affecting other components dependent on it. So, we
always use Collection as parameter of member or whatever everywhere,
underlying Collection maybe anything. Never deal with specific types such as ArrayList,
Vector unless one really is exploiting some extra functionality not
accessible through the interface.
Well thought design gives us tremendous flexibility to add new
functionality, modify existing functionality withot affecting other comonents of the
system. In the product domain, we see how many changes we make daily to the code
base. Better designs help maintain software the better way and makes
collaborative development simpler.
Design Patterns:
The term “design patterns” sounds a bit formal and can be
somewhat off-putting when you first encounter it. But, in fact, design
patterns are just convenient ways of reusing object-oriented code between
projects and between programmers. The idea behind design patterns is simple-- write
down and catalog common interactions between objects that programmers have
frequently found useful.
The fundamental reason for using varies design patterns is
to keep classes separated and prevent them from having to know too much
about one another. There are a number of strategies that OO programmers use to
achieve this separation, among them encapsulation and inheritance.
Design patterns is very matured science at this stage.
People have been using patterns since last two decades. Design patterns
began to be recognized more formally in the early
1990s by Helm (1990) and Erich Gamma (1992), who described
patterns incorporated in the GUI application framework, ET++. The
culmination of these discussions and a number of technical meetings was the
publication of the parent book in this series, Design Patterns -- Elements of Reusable
Software, by Gamma, Helm, Johnson and Vlissides.(1995). This book, commonly referred
to as the Gang of Four or “GoF” book, has had a powerful impact on those
seeking to understand how to use design patterns and has become an all-time
best seller. We will refer to this groundbreaking book ads Design Patterns,
throughout this book and The Design Patterns Smalltalk Companion (Alpert,
Brown and Woolf, 1998) as the Smalltalk Companion.
This was very brief about Software Design and Design Patterns.
In coming time I will discuss the widely used and recognized
Design Patterns and some things about Performance Engineering.
Keep Reading and Keep Sharing..
-- Kalpak