RSS

Monthly Archives: November 2008

Wicket Framework

Objective

Wicket Web Framework document provides basic idea on Wicket framework and also helps to build simple application.

What is Wicket?

Wicket is a Java web application framework that takes simplicity, separation of concerns and ease of development to a whole new level. Wicket pages can be mocked up previewed and later revised using standard WYSIWYG HTML design tools. Dynamic content processing and form handling is all handled in Java code using a first-class component model backed by POJO data beans that can easily be persisted using your favorite technology.

Why Wicket is invented?

1) Most existing web frameworks provide weak to non-existent support in managing server-side state

In Wicket, all server side state is automatically managed. You will never directly use an Http Session object or similar wrapper to store state. Instead, state is associated with components. Each server-side page component holds a nested hierarchy of stateful components, where each component’s model is, in the end, a POJO (Plain Old Java Object). Wicket maintains a map of these pages in each user’s session. One purpose of this page map (and the component hierarchy on each page) is to allow the framework to hide all details of how your components and models are accessed. You deal with simple, familiar Java objects and Wicket deals with things like URLs, session ids and GET/POST requests.

In simple statement we can say “Wicket is to JSP as Java is to C

2) Most existing frameworks require special HTML code

JSP is by far the worst offender, allowing the embedding of Java code directly in web pages, but to some degree almost all of the frameworks introduce some kind of special syntax to your HTML code.

Wicket does not introduce any special syntax to HTML. Instead, it extends HTML in a standards-compliant way via a Wicket namespace that is fully compliant with the XHTML standard. This means that you can use Macromedia Dream weaver, Microsoft Front Page, Word, Adobe Go Live, or any other existing HTML editor to work on your web pages and Wicket components. To accomplish this, Wicket consistently uses a single id attribute in the Wicket namespace (“wicket:id”) to mark HTML tags that should receive special treatment by the toolkit. If you prefer not to render Wicket name spaced tags and attributes to your end-users, Wicket has a simple setting to strip them all out, resulting in ordinary, standards-compliant HTML

So that web designers can work on the HTML with very little knowledge of the application code (they cannot remove the component name tags and they cannot arbitrarily change the nesting of components, but anything else goes). Likewise, coders can work on the Java components that attach to the HTML without concerning themselves with what a given page looks like. By not stepping on each other’s toes, everyone can get more work done.

3) Existing frameworks are not easy

Most of the existing toolkits have poorly defined or non-existent object models. In some cases, the model is defined using special XML syntaxes. The syntaxes may be so cumbersome that special tools are required to manipulate all the configuration information.

Wicket is all about simplicity. There are no configuration files to learn in Wicket. Wicket is a simple class library with a consistent approach to component structure. In Wicket, your web applications will more closely resemble a Swing application than a JSP application. If you know Java (and especially if you know Swing), you already know a lot about Wicket

4) Existing frameworks inhibit reusability

Most of the frameworks don’t have component models that allow reusing.

Wicket has been explicitly designed to make it very, very easy to create reusable components. Components in Wicket can be packaged up in JAR files and reused by simply dropping them in your lib folder – no configuration necessary!

Developing a Web Application with Wicket

Functional flow of this application is to have homepage consisting of a dropdown box to select the type of pizza, check boxes to select the toppings and a text box to add a comment as below

image13

After filling all the details and if you click submit as shown in below screenshot

image22

You will be navigated to another page where the whole data given in home page will be displayed

image33

Technical Overview

Since Wicket works with standard HTML, the presentation layer was designed with HTML .Wicket has the concept of model objects, these objects are simple POJOs (Plain Old Java Objects) that hold the values of the components on a page.  These model objects are a similar concept to Backing Beans in JSF or Form Beans in Struts.  The HTML pages containing Wicket components have some special HTML attributes that are used for mapping them to the Model objects, the attribute names must match fields of the Model objects, when a user enters some data in the HTML form and submit the page, the appropriate properties on the Model object are populated with the data entered by the user.

When writing applications with wicket, each HTML page must have a corresponding Java object extending the WebPage class.  The HTML file and the Java class must have the same name, for example, an HTML file called MyWicketPage.html must have a corresponding MyWicketPage.java. The HTML files must be deployed to the same directory where the corresponding java classes reside. Wicket has several components meant to be mapped to HTML form fields.  Components can be added to each other in a matter similar to the DOM of the HTML page.  If the page has a form with a drop down, some checkboxes and a text field, instances of the Dropdown Choice, Checkbox and Text Field classes must be added to an instance of the Form class. The Form then needs to be added to the java class corresponding to the HTML page.

For the example WebApplication home page code(WicketTestPage.html) looks like this:

<form wicket:id="pizzaForm">
<div style="font-weight: bold;" font-weight="" bold=""><big>Online Pizza Builder</big></div>
<table style="text-align: left; width: 427px; height: 112px;" border="1"
cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td style="font-weight: bold; text-align: right;">Crust:</td>
<td><select wicket:id="crust">
<option>option 1</option>
<option>option 2</option>
<option>option 3</option>
</select></td>
</tr>
<tr>
<td style="font-weight: bold; text-align: right;">Toppings:</td>
<td>Pepperoni<input wicket:id="pepperoni" type="checkbox" /> Sausage<input
wicket:id="sausage" type="checkbox" />&nbsp;Onions<input
wicket:id="onions" type="checkbox" />&nbsp;Green Peppers<input
wicket:id="greenPeppers" type="checkbox" /></td>
</tr>
<tr>
<td style="font-weight: bold; text-align: right;">Comments:</td>
<td><input maxlength="50" size="50" wicket:id="comments" type="text" /></td>
</tr>
<tr>
<td style="text-align: center;" colspan="2"><input value="Submit"
name="Submit" type="submit" /></td>
</tr>
</tbody>
</table>
</form>

The corresponding java code for the WicketTestPage class extending wicket.markup.html. WebPage which should have the same name as homepage (WicketTestPage.html)

public class WicketTestPage extends WebPage
{
PizzaForm pizzaForm = new PizzaForm("pizzaForm");
public WicketTestPage()
{
super();
add(pizzaForm);
}
}

You should have a PizzaModel class to hold the user-entered values on the form as shown below

public class PizzaModel implements Serializable
{
  private String crust;
  private boolean pepperoni;
  private boolean sausage;
  private boolean onions;
  private boolean greenPeppers;
  private String comments;
  
  public String getComments()
  {
    return comments;
  }
  public void setComments(String comments)
  {
    this.comments = comments;
  }
  public String getCrust()
  {
    return crust;
  }
  public void setCrust(String crust)
  {
    this.crust = crust;
  }
  public boolean getGreenPeppers()
  {
    return greenPeppers;
  }
  public void setGreenPeppers(boolean greenPeppers)
  {
    this.greenPeppers = greenPeppers;
  }
  public boolean getOnions()
  {
    return onions;
  }

public void setOnions(boolean onions)
  {
    this.onions = onions;
  }
  public boolean getPepperoni()
  {
    return pepperoni;
  }
  public void setPepperoni(boolean pepperoni)
  {
    this.pepperoni = pepperoni;
  }
  public boolean getSausage()
  {
    return sausage;
  }
  public void setSausage(boolean sausage)
  {
    this.sausage = sausage;
  }  
}

Notice how the field names on the PizzaModel class match the <wicket:id> attributes in the HTML file. To bind the properties in the PizzaModel class to the fields in the HTML form you have to add following line of code in the PizzaForm class:

setModel(new CompoundPropertyModel(pizzaModel)); 

The wicket.model.CompoundPropertyModel class takes care of populating the fields in the Model object (PizzaModel in this example) with the appropriate user-entered values.

Now write a new Model class (CrustType) to model the options in the drop down, for the Pizza Application:

public class CrustType implements Serializable
{
  String id;
  String text;
  
  public CrustType()
  {
    super();
  }
  
  public CrustType(String crustName)
  {
    setId(crustName);
    setText(crustName);

}
  public String getId()
  {
    return id;
  }
  public void setId(String id)
  {
    this.id = id;
  }
  public String getText()
  {
    return text;
  }
  public void setText(String value)
  {
    this.text = value;
  }
  @Override
  public String toString()
  {
    return getText();
  }
}

Then you had to instantiate the wicket.markup.html.form.DropDownChoice , which is the Wicket component used to map to an html <select> field (more commonly called a drop down), using the following constructor:

public DropDownChoice(java.lang.String id,
                      IModel model,
                      IModel choices,
                      IChoiceRenderer renderer)

The parameters you had to pass to make it all work together are as follows:

crustDropDown = new DropDownChoice(
        "crust",new PropertyModel(pizzaModel, "crust"), Arrays
        .asList(new CrustType[]
                              { new CrustType("Thin & Crispy"), 
                                new CrustType("Hand Tossed"),
                                new CrustType("Pan Pizza") }), 
                                new ChoiceRenderer("text", "id"));

PizzaModel is the instance of the Model object that maps to the HTML form. "crust" is the name of the property in the model that will hold the value the user selected in the drop down. wicket.markup.html.form.ChoiceRenderer implements the wicket.markup.html.form.IChoiceRenderer interface, the two parameters to its constructor represent the displayed text and the value of the drop down options, respectively

And to map the form in OnlinePizzaBuilder.html, PizzaForm class is provided as below which uses the models explained above. It extends wicket.markup.html.form.Form class, which provides an onSubmit() method that is executed when the form is submitted.

public class PizzaForm extends Form
{
  private DropDownChoice crustDropDown;
  private CheckBox pepperoniCheckBox = new CheckBox("pepperoni");
  private CheckBox sausageCheckBox = new CheckBox("sausage");
  private CheckBox onionsCheckBox = new CheckBox("onions");
  private CheckBox greenPeppersCheckBox = new CheckBox("greenPeppers");
  private TextField commentsTextField = new TextField("comments");
 
  public PizzaForm(String id)
  {
    super(id);
    PizzaModel pizzaModel = new PizzaModel();
    setModel(new CompoundPropertyModel(pizzaModel));
    crustDropDown = new DropDownChoice(
        "crust",new PropertyModel(pizzaModel, "crust"), Arrays
        .asList(new CrustType[]
                              { new CrustType("Thin & Crispy"), 
                                new CrustType("Hand Tossed"),
                                new CrustType("Pan Pizza") }), 
                                new ChoiceRenderer("text", "id"));
 
    add(crustDropDown);
    add(pepperoniCheckBox);
    add(sausageCheckBox);
    add(onionsCheckBox);
    add(greenPeppersCheckBox);
    add(commentsTextField);
  }
}

To be able to manipulate the user-entered values, the onSubmit() method of the wicket.markup.html.form.Form method must be overwritten. The onSubmit() method of the PizzaForm class follows:

protected void onSubmit()
  {
    PizzaModel pizzaModel = (PizzaModel) getModelObject();
     setResponsePage(new WicketTestConfPage(pizzaModel));
  }

The getModelObject() method call obtains an instance of the Model object populated with the user-entered values. The requestCycle.setResponsePage() directs the browser to a new page. The WebPage instance that the browser will be redirected to must have a constructor taking an instance of the Model object as a parameter.

Now the last step is to display a confirmation page displaying all the user entered values and here is the source for the confirmation page:

public class WicketTestConfPage extends WebPage
{
   public WicketTestConfPage(PizzaModel pizzaModel)
  {
    super();
    add(new Label("crust", pizzaModel.getCrust()));
    add(new Label("pepperoni", new Boolean(pizzaModel.getPepperoni())
        .toString()));
    add(new Label("sausage", new Boolean(pizzaModel.getSausage()).toString()));
    add(new Label("onions", new Boolean(pizzaModel.getOnions()).toString()));
    add(new Label("greenPeppers", new Boolean(pizzaModel.getGreenPeppers())
        .toString()));
    add(new Label("comments", pizzaModel.getComments()));
  }
}

All it does is create some labels to displaying the values of the Model object it takes as its sole constructor parameter. Here are the relevant sections of the corresponding HTML file (WicketTestConfPage.html):

<table style="text-align: left; width: 427px; height: 112px;" border="1"
cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td style="font-weight: bold; text-align: right;">Crust:</td>
<td><span wicket:id="crust">Hello</span></td>
</tr>
<tr>
<td style="font-weight: bold; text-align: right;">Toppings:</td>
<td>Pepperoni:&nbsp; <span wicket:id="pepperoni"></span>
Sausage:&nbsp;<span wicket:id="sausage"></span>&nbsp;Onions: &nbsp;<span
wicket:id="onions"></span>&nbsp;Green Peppers:&nbsp;<span
wicket:id="greenPeppers"></span></td>
</tr>
<tr>
<td style="font-weight: bold; text-align: right;">Comments:</td>
<td><span wicket:id="comments"></span></td>
</tr>
</tbody>
</table>

Of interest here are the <span> fields; these correspond to the labels in the WicketTestConfPage java class. You may notice some of the <span> tags have text inside them, this text will only be displayed in the browser when mocking up the pages, when displayed from the Wicket application, they will display whatever value the corresponding Label instances have.

How to deploy the application in tomcat

When deploying wicket applications, the application is declared in a standard web.xml file, using wicket.protocol.http.WicketServlet as the servlet, and passing instance of a class extending wicket.protocol.http.WebApplication as its only initialization parameter. As an example, here are the relevant sections of the web.xml used for the sample application:

<servlet>
<servlet-name>WicketTestApplication</servlet-name>
<servlet-class>
wicket.protocol.http.WicketServlet
</servlet-class>
<init-param>
<param-name>applicationClassName</param-name>
<param-value>
net.ensode.wickettest.WicketTestApplication
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>WicketTestApplication</servlet-name>
<url-pattern>/app/*</url-pattern>
</servlet-mapping>

The class extending wicket.protocol.http.WebApplication for the sample application is trivial, all it does is call getPages().setHomePage(WicketTestPage.class) from its constructor. This method call will set the initial page of the application to the HTML page corresponding to WicketTestPage.java

To download the source code for above sample application click SourceCode

Do the required setup with the help of readme.txt file from downloaded Zip file.

The application would be accessed using the URL: http://localhost:8080/wickettestapp/app. This URL assumes you are deploying to your local workstation and that the servlet container is listening to port 8080, substitute the host name and port as appropriate.

Summary from Sample Application

  • Provides clear separation of concerns where web designers don't have to add any special markup to the HTML files to make them work with wicket, allowing them to use any WYSIWYG editor to create the pages.
  • Makes it easy to create Java code that is able to execute outside of a servlet container or application server, making this code easy to unit test. For these reasons, Wicket is a good choice when creating web applications and dynamic web sites.
  • Does not require special XML configuration files

Advantages of Wickets

EASY (SIMPLE / CONSISTENT / OBVIOUS)

  • POJO-centric
  • All code written in Java ala Swing
  • Minimize "conceptual surface area"
  • Avoid overuse of XML configuration files
  • Fully solve back button problem
  • Easy to create bookmarkable pages
  • Maximum type safety and compile-time problem diagnosis
  • Maximum diagnosis of run-time problems
  • Minimum reliance on special tools
  • Components, containers and conventions should be consistent

REUSABLE

  • Components written in Wicket should be fully reusable
  • Reusable components should be easily distributed in ordinary JAR files

NON-INTRUSIVE

  • HTML or other markup not polluted with programming semantics
  • Only one simple tagging construct in markup
  • Compatible with any ordinary HTML editor
  • Easy for graphics designers to recognize and avoid framework tagging
  • Easy to add tagging back to HTML if designers accidentally remove it

SAFE

  • Code is secure by default
  • Only explicitly bookmarkable links can expose state in the page or URL
  • All logic in Java with maximum type safety
  • Easy to integrate with Java security

EFFICIENT / SCALABLE

  • Efficient and lightweight, but not at the expense of other goals
  • Clustering through sticky sessions preferred
  • Clustering via session replication is easy to accomplish and easy to tune by working with detachable models

Some disadvantages of Wicket

  • Not as well documented as other web application frameworks like Struts or Java Server Faces.
  • Has limited AJAX support (in the latest beta), although more AJAX support is planned.

References

 
Leave a comment

Posted by on November 25, 2008 in Web

 

Tags:

Secure Web Application Modeling

Overview

The core function of the Analysis & Modeling is to identify security threats, while facilitating the process of defining application framework with security strategy. Even if you are not a security subject-matter expert, you now have the ability to consistently and objectively identify threats to your software application.

Creating a secure application framework model is a three-phase process. First, you define your application context. Second, you model your threats on top of your application context. Third, you measure the risk that is associated with each threat. Once you have completed these phases, you can assimilate your application framework.

The application framework model has the capability to assimilate and build security artifacts such as access control matrices, data flow and trust flow.

When it comes to developing an application, writing secure code should be the aim of every developer, since much vulnerability is caused by bad coding practices, sometimes the OS or the third party component that we’re using could have vulnerabilities, and through developers not being aware of the nature of certain types of threats. In this document we investigate some common types of vulnerabilities that we expose ourselves to when not treating the client with sufficient caution.

We look at various types of attacks that might be launched if we do not protect ourselves from the client, and how we test the attacks and code the application with the corresponding technology techniques.

By designing the application for the various types of attacks listed in this document, we can guarantee that our web application is secure from the common attacks.

What is application context?

In order to understand your application context, you must understand the individual elements that, together, create it. Defining the various elements of your application individually enables each element to be analyzed and coupled together to define an application context. This makes it possible to identify potential threats, and then systematically build an effective security strategy.

How is this done?

To define your application context, it is necessary to first define your application requirements, and then define your application architecture. The application requirements consist of business objectives, user roles, data, and use cases, all of which are defined by business owners. The application architecture consists of components, service roles, external dependencies, and calls, and is defined by application architects.

Define Application Requirements

Application requirements consist of your business objectives, user roles, data and use cases. Before you can begin to define the application requirements, you must first define the scope of the application and identify various threats in the defined scope.

Business Objectives

Business objectives are your goals – that is, the reason for creating your software application. Applications are developed to fulfill specific business needs, or to solve some specific business problem. These needs or problems are your objectives that need to be fulfilled by your application in order to benefit your business.

User Roles

Roles define the trusts of your software application, and they are primarily used to make authorization decisions. Any user who will be interacting with the application must be assigned a user role.

Data

Data defines the information type that is maintained or processed by your software application. Optionally, data types can be broken down into specific elements that, together, make up that specific data.
Example: User profile data consists of the following elements: salutation, user’s first name, user’s middle initial, user’s last name, street address, and so on.
In order to identify the data types within a software application, data elements are grouped into logical sets, which can then be classified.

Application Use Cases

Once you have defined your roles, data and access control, you must define use cases that, at the very least, define the scenarios that are used to realize specific subsets of the defined access control.

A Use Case is an ordered sequence of actions that are used to realize an effect. This effect, known as the Net Data Effect, is a specific subset of the access control matrix that is realized at the end of the use case.
Example: Reading product information, or updating credit card records.

When you run the data access control matrix, you will see all the access controls that are maintained by your application. These access controls are realized with use cases.

Example: Suppose you have a use case called Creating Customer Account. If you define a user role with the access control to create credit card information, your use case must support this.

Use cases can be analyzed, to determine what elements are required in order to accomplish them, as well as how they interact with other objects.

Example: A user role, website component, and database component are some of the elements required for the creating customer account use case.

In short, a use case defines what needs to happen.

Define Application Architecture

Your application architecture is comprised of your components, service roles, external dependencies and calls. You begin defining your application architecture by defining your components.

  • Components

Components are the building blocks of a software application that define an instance of a technology type such as databases and web services.
Example: A database in which a user’s credit card information is stored, web services, websites, and thick clients.

  • Service Roles

Service roles are trust levels that contain specific identities that define the context of various components running in your software application.

Example: Website roles and database roles for your website and database components, respectively.

  • External Dependencies

External dependencies are components with which your application will interact, and over which you have no control.
Example: .NET Passport is an external dependency of http://www.hotmail.com.

  • Calls

The call captures the connection between two pre-defined elements (user roles, service roles, components, external dependencies) in the form of a caller (the element that is invoking the action) acting on a component (the element effected) through a specified action. The data transfer between the coupled elements for the specified action is also captured in the call and the transfer could be from the caller to the component (data sent) or from the component back to the caller (data received). A collection of calls for a specified action allows you to define how that use case is realized in the context of your application.
Recall that use cases define the set of actions or features that need to be supported by your application, and these allotted actions can be executed by specific roles in order to achieve a net data effect. Put simply, use cases define what needs to happen, and calls define how it happens.

Model

Application modeling is meant to be an iterative process in which the application evolves through the many stages that information is consolidated from different members of your application team.

  • Identifying Threats

Once you have defined your application context, we should analyze the threats for the defined context. Threats are identified by systematically corrupting the allowable actions (defined calls) of your application. They are then classified into the following three threat categories: confidentiality threats, integrity threats, and availability threats.

  • Primary Threat Factors

After your threats have been identified you will be able to select the primary threat factors for each individual threat. These threat factors help provide a better context to aid in the process of analyzing your threats, which is essential to building your security strategy.

  • Confidentiality Threat

There are two primary threat factors that fall into the confidentiality category. Given an allowable action on a component by a role, its confidentiality can primarily be compromised through the unauthorized disclosure of the executing identity or the data.

  • Integrity Threat
    There are three primary threat factors that fall into the integrity category. The primary factors are the violation of access control, business rule(s), or data integrity.     

    • Violation of access control Example: In your access control, you set permissions that allow administrators to create, edit, and delete product pricing information, while you set permissions that allow registered users to read product information. If your access control was violated and registered users were allowed to edit product pricing information, it would be possible for them to set all pricing to zero. This would be an enormous threat to your business. 
    • Violation of business ruleThe violation of business rule is something to consider that may be outside the realm of access control and data integrity.
      Example: A banking transaction use case is made up of two calls, a withdrawal and a deposit. The business rule is that a user cannot make a withdraw without first making a deposit (i.e. there needs to be money in the users account in order for them to take any out). If a user was allowed to withdrawal money from a bank without having to make a deposit first, banks would surely be depleted quickly.
      Note: If you check Violation of business rule as a primary threat factor, you must supply the business rule.
    • Violation of data integrityExample 1: Consider a user’s credit card information. It is crucial that the correct credit card number is paired with its rightful owner (user).
      Example 2: Consider a case where an attack is able to compromise your application and modify the price of all your products that you sell to $1. This attack violates your data integrity by compromising your product information and pricing. 
  • Availability Threat There are two primary threat factors that fall into the availability category. The compromise could happen through the ineffective execution of the action or due to performance degradation.
    • Unavailability
      Example: When a website is required to be available 99.9% of the time or a bank that needs to be open during their advertised business hours, the unavailability of either could cause significant business impacts.
      Note: If you check Unavailability as a primary threat factor, you must supply a definition of the availability condition.
    • Performance degradation
      Example: If an e-commerce site takes more than 5 seconds to respond to a request, this may be considered a threat, especially if this ineffective execution will result in a loss of potential business.
      Note: If you check Performance degradation as a primary threat factor, you must supply a definition of the performance requirement.
      After you have classified your threats, your next step is to define how you will respond to them. 

Measure

The process of measuring risk is very subjective. Because of this subjectivity, once the Threat Analysis & Modeling has modeled your application context and identified threats, you should measure the probability and impact of each threat in relation to your own business needs.
In the measure phase, you will attempt to quantify your threats. This is achieved through quantifying the risk associated with each threat.

Note: Although risk measurement is subjective, as long as the user stays consistent in the measurement, the user is provided with a priority that can be used to appropriately allocate resources in an effort to guard against the realization of threats.

Risk Response

Along with measuring the risk associated with each threat, your threat model should also facilitate and document the responses to those identified risks. There are four responses one can have towards an identified risk. You can choose to accept, avoid, reduce, or transfer the risk.

  • Accept: Choosing to accept a risk would be appropriate when the business supporting the software application takes full ownership of that risk, and all that it entails in terms of the negative business impact.
  • Avoid: Risk is avoided when all supporting features for the underlying factors are removed. If, for example, the threat is concerned with the unavailability of some action, then that action needs to be removed.
  • Reduce: Risk is reduced by applying countermeasures which lessen either the impact or the probability of the threat.
  • Transfer: Risk is transferred when the underlying action is transferred to an external dependency. Risk is also transferred when the risk inherent in the action is illustrated to the user and the user accepts that risk in order to use that feature.

Attack Library

Overview

An attack library is a collection of attack types along with their relevant vulnerabilities and proposed countermeasures to those vulnerabilities. Attack libraries enable software application teams to define and adopt secure engineering techniques, gain the information necessary to detect security concerns, and create relevant security test cases.
Attack libraries provide a way to define, with absolutely minimal permission, the relationship between the exploit (attack), the cause (vulnerability), and the fix (countermeasure). The attack library helps ensure that various development teams understand the security assumptions and dependencies of your application.

Note: Attack libraries are meant to be created by security subject-matter experts and consumed in the process of threat modeling.

Buffer Overflow

A buffer overrun occurs when a buffer declared on the stack is overwritten by copying data larger than the buffer. Variables declared on the stack are located next to the return address for the function’s caller. The usual culprit is unchecked user input passed to a function such as strcpy, and the result is that the return address for the function gets overwritten by an address chosen by the attacker. In a normal attack, the attacker can get a program with a buffer overrun to do something he considers useful, such as binding a command shell to the port of their choice.

How to Test:
The most common way to detect potential Buffer Overflow attacks is listed below:

  • Identify all entry points of the application that collect user input via text boxes, command line parameters etc.
  • Provide exceedingly long input via all entry points [For e.g AAAAAAAAA….] and submit the request.
  • If the long input that you provided results in buffer overflow attack, you would receive an exception message.

Note: If you don’t have a development environment on your system, this information will be logged in the Dr. Watson logs.

Canonicalization

Different forms of input that resolve to the same standard name (the canonical name), is referred to as canonicalization. Code is particularly susceptible to canonicalization issues if it makes any decisions based on the name of a resource that is passed to the program as input. Files, paths, and URLs are resource types that are vulnerable to canonicalization because in each case there are many different ways to represent the same name.

How to Test:

The most common way to detect the potential of a Canonicalization attack:

  • Identify entry points that collect user input for file paths, url’s in text boxes, query string parameters, etc.
  • Try to enter the following strings which could represent the same file and submit the request. (Valid file name is somefile.dat) c:\temp\subdir\…\somefile.dat,   c:\ temp\ somefile.dat,  ..\somefile.dat, C%3A%5Ctemp%5Csubdir%5C%2E%2E%5Csomefile.dat.
  • If the application accepts the above mentioned different forms of file names application is vulnerable to Canonicalization.
  • Please note that the exception/error messages/control flow/program flow may be logged therefore simply checking the UI will not be sufficient.

Cross-Site Scripting (XSS)

Cross-site script (XSS) attacks can occur whenever a users input is echoed back to the browser without adequate validation, sanitization or encoding, enabling an attacker to supply input which the victim’s browser interprets as client-side script originating from the vulnerable application.

The XSS attacks could be categorized as persistent or non-persistent.

In the “direct” or “persistent” scenario, the attacker posts malicious data to the web server which is stored and later replayed to the victim. In the “indirect” or “non-persistent” scenario, the attacker supplies the victim with a URL or HTML form which contains malicious script. The victim’s browser passes the malicious script to the vulnerable site, which replays it to the victim’s browser. In both cases, the script is executed in the trust context of the vulnerable site.

Typical XSS exploits target the victim’s cookies, transmitting them to the attacker so that the attacker can impersonate the victim on the vulnerable site. In general, XSS exploits enable attackers to take arbitrary actions on the vulnerable site on the victim’s behalf. In the worst-case scenario, an attacker can use XSS to seize remote control of the victim’s computer

How to Test:

The most common way to detect the potential of a XSS attack:

  • Identify entry points that collect user input such as Form inputs [e.g text boxes], query string parameters, etc.
  • Check if the user input is echoed back to the browser.
  • Insert “” as an input and submit the request.
  • If this pops up an alert box saying “XSS” attack was successful.
  • Depending on the context of the output this payload might need more tweaking. Do a View Source to find where & how the input was echoed back.
  • Presence of the input without encoding in the source indicates XSS vulnerability.

Cryptanalysis Attacks

Cryptanalysis is the science of cracking codes, decoding secrets, violating authentication schemes and breaking cryptographic protocols. It is also the science devoted to finding and correcting weaknesses in cryptographic algorithms. It is understood within the field of Cryptology that an algorithm should not rely on its secrecy. An algorithm should always be made available for public scrutiny. It is this scrutiny that will make it a well trusted algorithm. Inevitably, vulnerability in the algorithm will be exploited.

How to Test:

The most common way to detect the potential of a Cryptanalysis attack:

  • Check for the algorithm which is used for encryption in the application.
  • Check for any custom algorithms are being used in the application.
  • Check the bit length of Keys that are used for encryption.
  • Check for how the Keys are secured and maintained.

Denial of Service

A Denial of Service (DoS) attack is an incident in which a user or organization is deprived of the services of a resource they would normally expect to have. Typically, the loss of service is disruption of services like e-mail, directory services etc. In the worst cases, for example, a Web site accessed by millions of people can occasionally be forced to temporarily cease operation. A denial of service attack can also destroy assets in a computer system. Although usually intentional and malicious, a denial of service attack can sometimes happen accidentally. A denial of service attack is a type of information theft which will cost organization’s time & money.

How to Test:

The most common way to detect the potential of a Denial of Service attack:

  • Identify entry points that accept user input (such as file upload, accepting user comments etc).
  • Insert huge/unexpected input as an input and submit the request.
  • Repeat step 3 until resources (memory, CPU Utilization) get exhausted.
  • Identify whether application behaved in an unexpected way.
  • Also identify whether an exception/error message was generated relating to request (e.g., Page cannot be displayed).

Please note that the exception may be logged therefore simply checking the UI for an error message will no be sufficient.

Forceful Browsing

With the forceful browsing attack, the attacker gains access to a restricted page within a Web application by supplying a URL directly (forcing the URL) instead of accessing it by following links from other pages in the application. The intended workflow to get to the restricted page is through another page which authorizes the user to access the target page. This attack also allows attacker to gain access to resources to which no direct links exist.

How to Test:

The most common way to detect the potential of a forceful browsing attack:

  • Identify vulnerable Files, Hidden Un – Referenced Files, Back-Up Files / Temp Files etc.
  • If user can be able to access the above files, then forceful browsing is achieved.

Format String

A common function used to output data are the printf family of functions. When a programmer calls these functions with user input without explicitly specifying a format string several threats are created. By manipulating input to these functions, attackers can read and write to generally arbitrary regions of memory and create several unfavorable application conditions such as arbitrary code execution.

How to Test:

The most common way to detect the potential of a format string attack:

  • Identify code instances were the printf classes of functions are called without providing explicit format strings.

HTTP Replay Attack

Attacker Replays old HTTP requests to the web server by monitoring the HTTP packets from USER-Server traffic. The web server will not be able to differentiate the request sent by an attacker. With HTTP Replay attack, the attacker captures the user’s authentication cookie using monitoring software and replays it to the application to gain access under a false identity.

How to Test:

The most common way to detect the potential of a HTTP Replay attack:

  • User access valid site (ex: http://www.abcbank.com)
  • User submits a request. (ex: for money transfer)
  • Attacker tries to capture the HTTP packet using any sniffing tool. (ex:Netmon)
  • Attacker replays the packet and tries to access the actual site through this information.
  • If actual site consumes the request & process it then it is prone to HTTP replay attacks.

Integer Overflow/Underflow

Integer arithmetic’s are frequently used in computer programs on all types of systems.

The register width of the processor determines the native type of integer and the range of operand values. Typical binary sizes for integers include 8 bits, 16 bits, 32 bits (the most common width as of 2005), 64 bits, and 128 bits. Since a math operation may give a result larger than the available register width, an error condition may result.

On systems where the result of an arithmetic operation is simply stored, and no error is returned (this is the general case), it may not be possible for the software to determine that the value stored is erroneous. If an integer value is used to specify the location of other code or variable values in memory, the resulting pointer error may be exploited to create a buffer overflow condition or
to write and execute arbitrary (and possibly harmful) code to the resulting (and unexpected) position.

How to Test:

Scan code performing arithmetic operations.

  • LDAP Injection – The Lightweight Directory Access Protocol (LDAP) API provides a mechanism for connecting to, searching, and modifying internet directories. A LDAP (Lightweight Directory Access Protocol) injection attack exploits vulnerabilities in input validation to run arbitrary LDAP statements against information directories. It can occur when your application uses input to construct dynamic LDAP statements to access directory services. Using the LDAP injection attack, the attacker can execute arbitrary statements against the directory services.

How to Test: 

The most common way to detect the potential of a LDAP Injection attack:

  • Identify entry points that collect user input such as text boxes, query string parameters, etc.
  • Insert any character (‘(‘, ‘|’, ‘&’) as an input and submit the request.
  • Identify whether an exception/error message was generated relating to LDAP (e.g., Page cannot be displayed).

Please note that the exception may be logged therefore simply checking the UI for an error message will no be sufficient.

  • Man in the Middle Attack  -A man in the middle attack occurs when the attacker intercepts messages sent between the sender and receiver. The attacker then changes message and sends it to the original recipient. The receiver has no way to identify if the message is from the actual sender. Here the attacker is spoofing the identity of both sender and receiver.

How to Test:

Any network request involving client-server communication is subject to man in the middle attacks. These include

  • Web requests
  • Distributed Component Object Model (DCOM) requests
  • Calls to remote components
  • Web services
  • Network Eavesdropping

Network Eavesdropping

Network Eavesdropping is the act of monitoring network traffic for data, such as clear-text passwords or configuration information. With a simple packet sniffer, all plaintext traffic can be read easily. Also, lightweight hashing algorithms can be cracked and the payload that was thought to be safe can be deciphered.

How to Test:

The most common way to detect the potential of a Network Eavesdropping attack:

  •  Install any sniffing tool (e.g. Network Monitor, packetyzer, etc…) and observe the communication channel between the source and destination server. Check whether packets captured in the sniffing tools shows sensitive or high business impact data (like password, connection strings, bank a/c numbers & cc number etc.) in clear text.

One-Click Attack

One-click attack has been called by several names within the security community. It is can also be called -CSRF, Page bounce, and Session Riding attack. A one-click attack is, when a third-party attacker causes an action of their choice to be taken on a victim’s behalf at the vulnerable site. In a one-click attack, the attacker must entice the victim into clicking a link or viewing a web page that was generated by the attacker.

The attacker lures an unsuspecting user into browsing to the page, and then causes the page to be sent to the server where the view state is valid. The server has no way of knowing that the view state originated from the attacker.

Consider this example, where vulnerable.com authenticates the user and subsequently maintains state using session cookies. Vulnerable.com has an administration page, /admin/deluser.asp. This page expects a query with the ID number of the user to delete as a parameter to the query.

How to Test:

The most common way to detect the potential of a one-click attack:

  • Identify the areas in the application which are performing critical operations (for ex. Deleting user, transferring funds etc.)
  • Verify if the application is re-authenticating the user at these points or not.
  • Verify if the application design checks whether these requests are being placed by the genuine users or not.
  • Create a duplicate pre-filled form and try to post it to same vulnerable site in the background to launch the attack.

Password Brute Force

A Password Brute Force attack is an automated process of trial and error used to guess a user’s credentials until successfully found. Brute Force Attack is performed using an educated guess to attempt to narrow down the key value. For example, someone could begin guessing a password by using a person’s first and last names, then spouse’s name, then pet’s name, and continuing with other common strings for passwords.

How to Test:

The most common way to detect the potential of a Password Brute Force attack:

  • Identify an entry point that collects user credentials as input such as text boxes, query string parameters, etc.
  • Input guessed credentials; submit the request for n number of time until you succeed.[Note : this can also be automated via brute force tools]

Repudiation Attack

Repudiation is the ability of users (legitimate or otherwise) to deny that they performed specific actions or transactions. Without adequate auditing/Logging, repudiation attacks are difficult to prove. Repudiation attack allows an attacker to carry out a transaction and leave no evidence that the transaction was performed by the attacker.

How to Test:

  • Check if the application is configured with anonymous authentication.
  • Check if the application implements a poor authorization model.
  • Check if application lacks logging or maintains ineffective logging.

Response Splitting

HTTP Response Splitting techniques provide attackers with new attack vectors for defacing website content and end-users. User controllable input parameters placed into HTTP response headers in the absence of adequate data validation creates the potential for HTTP Response Splitting attacks. HTTP Response Splitting attacks allow for both local and remote cache poisoning which can result in arbitrary content being displayed to website visitors. This type of attack is possible when server script code embeds user data in HTTP response headers in the absence of any data validation.

How to Test:

The most common way to detect the potential of a Response Splitting attack:

  • Identify all the points where user controlled data is placed in to HTTP Response headers.
  • Try to send this payload in the input which supposedly is being placed in the response header by the application.
  • If you get back page with Hacked! displayed, then application is vulnerable to response splitting attacks.

Session Hijacking

Session hijacking is the act of taking control of a user session after successfully obtaining or generating an authentication session ID. In session hijacking an attacker using a captured, brute forced or reverse-engineered session ID seizes control of a legitimate user’s Web application session while that session is still in progress. The severity of the damage incurred depends on what’s stored in the session state.

How to Test:

The most common ways to detect the Session Hijacking attack are:

  • The communication channel is over HTTP
  • Site Vulnerable to XSS attack
  • Session IDs in URL
  • No authorization check in code.
  • Use of persistent cookies.

SQL Injection

A SQL injection attack exploits vulnerabilities in input validation to run arbitrary commands in the database. It can occur when your application uses input to construct dynamic SQL statements to access the database. It can also occur if your code uses stored procedures that are passed strings that contain raw user input. Using the SQL injection attack, the attacker can execute arbitrary commands in the database. The issue is magnified if the application uses an over-privileged account to connect to the database. In this instance it is possible to use the database server to run operating system commands and potentially compromise other servers, in addition to being able to retrieve, manipulate, and destroy data.

How to Test:

The most common way to detect the potential of a SQL Injection attack:

  • Identify entry points that collect user input such as text boxes, query string parameters, etc.
  • Insert the single quote character (‘) as an input and submit the request.
  • Identify whether an exception/error message was generated relating to SQL.

Please note that the exception may be logged therefore simply checking the UI for an error message will no be sufficient.

XML Injection

An XML injection attack exploits vulnerabilities in input validation to create a new node to alter the program decision/flow. It can also be used to insert malicious characters into XML and break functionality. It occurs when the application uses input from the user to construct dynamic XML to send it to the backend database or does transformation to display it back to the user.

How to Test:

The most common way to detect the potential of a XML Injection attack:

  • Identify entry points that collect user input such as form fields, query string parameters, etc.
  • Identify the XML attributes that may be injected in XML, causing an unexpected behavior (such as exceptions while parsing the generated file, reference to external entities, tampering data, etc)
  • If you use XML functions, such as constructing XML string or use XSLT template expansion with the tainted data, you are most likely vulnerable.

Summary

Secure Web Application Modeling discipline advocates the use of proactive, structured threat management for software development projects. The Secure Web Application Modeling is a process of six logical steps (identification, analysis, planning, tracking, controlling, and learning) through which a project team should cycle continuously during the project life cycle. The learning step is used to communicate Secure Web application Development lessons learned and feedback on enterprise-level application threat resources to an enterprise-wide threat risk knowledge base.

References

Following are the web references:

 
2 Comments

Posted by on November 24, 2008 in Web

 

Tags: , , , , , , , , , , , , , , , , , , ,

Ajax and DOM

Abstract

Ajax is a powerful approach to building Web sites and it’s not nearly as hard to learn as an entire new language.

Before I dig into what Ajax is, though, let’s spend just a few moments understanding what Ajax does. Today’s applications can be divided into two broad categories:

  • Desktop applications
  • Web applications

Desktop applications are installed completely on the computer. The code that runs these applications resides on the desktop. Web applications on the other hand run on a Web server we access the application with the Web browser. More important than where the code for these applications runs, though, is how the applications behave and how we interact with them. Desktop applications are usually pretty fast (they’re running on your computer), have great user interfaces (usually interacting with your operating system), and are incredibly dynamic. On the other hand, Web applications provide services we could never get on our desktop . However, with the power of the Web comes the time lag — waiting for a server to respond, waiting for a screen to refresh, waiting for a request to come back and generate a new page. This is where the Ajax steps in to make the interaction faster. 

Ajax attempts to bridge the gap between the functionality and interactivity of a desktop application and the always-updated Web application. We can have dynamic user interfaces and fancier controls like a desktop application, but it’s available to on a Web application. Most Web applications use a request/response model that gets an entire HTML page from the server. The result is a back-and-forth operation that usually involves clicking a button, waiting for the server, clicking another button, and then waiting for some more time. With Ajax, we can use a request/response model that never leaves users waiting for a server to respond.

AJAX Overview

Overview of Ajax:

  • AJAX stands for Asynchronous JavaScript And XML.
  • AJAX is a type of programming made popular in 2005 by Google (with Google Suggest).
  • AJAX is not a new programming language, but a new way to use existing standards.
  • With AJAX we can create better, faster, and more user-friendly web applications.
  • AJAX is based on JavaScript and HTTP requests.
  • With AJAX, the JavaScript can communicate directly with the server, using the
  • JavaScript XMLHttpRequest object. With this object, the 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.
  • AJAX is a browser technology independent of web server software.

Here are the basic technologies involved in Ajax applications:

  • HTML
  • JavaScript code is the core code running Ajax applications and it helps facilitate communication with server applications.
  • XML
  • DOM, the Document Object Model, will be used (through JavaScript code) to work with both the structure of your HTML and (in some cases) XML returned from the server.

Classic Vs AJAX Web Application

In any web application that we develop will have HTML pages rendered in the client and on submit of the (aspx / jsp / jsf) page, the screen is refreshed and a new HTML page will be rendered. 

AJAX Web Application will also render only HTML pages and on submit the page will get refreshed. But, if we need any other information from the web server before the user submits the page or if we need to show any data as the user start using the web page, we can’t do so at present. It’s possible by implementing AJAX using a JavaScript method in the HTML page which in-turn gets fired based on certain client side events. This JavaScript method will call a Web Service or a Server side method to get the data and can be shown using DHTML / CSS in the client or show an alert or validate certain data and inform the user before he submits the page. Simply put, classic model is synchronous, AJAX model is asynchronous. What makes AJAX based clients unique is that the client contains page-specific control logic embedded as JavaScript technology. The page interacts with the JavaScript technology based on events such as the document being loaded, a mouse click, focus changes, or even a timer. AJAX interactions allow for a clear separation of presentation logic from the data. An HTML page can pull in bite-size pieces of data as needed rather than reloading the whole page every time a change needs to be displayed. AJAX will require different server-side architecture to support this interaction model. Traditionally, server-side web applications have focused on generating HTML documents for every client event resulting in a call to the server. The clients would then refresh and  re-render the complete HTML page for each response. Rich web applications focus on a client fetching an HTML document that acts as a template or container into which to inject content, based on client events using XML data retrieved from a server-side component. While seemingly simplistic, AJAX opens doors for Web-application developers that had previously been shut. It relies on nothing but the built-in browser internals. No extra software needs to be distributed to users, making AJAX an attractive option for companies that are concerned about the security and logistical implications of distributing installed software to users.

The traditional Web-application architecture (sometimes referred to as the postback model) is inefficient because it wastes communications bandwidth. Every hyperlink activation or buttonpress results in a postback (or reload) of an entire Web page, when perhaps all that was required was a tiny block of text from the database. AJAX solves this problem with XMLHttpRequest.

ajaxdom1

Using XML HTTP and JavaScript, a developer can make an asynchronous request for a block of information from a server without needing to reload an entire page. The result is Web applications that react more quickly to user interaction.

For example, a user might want to see the details about a customer in a Web page. In a traditional Web application, the user might have to click and wait for the entire page to refresh before seeing those details. In an AJAX model, the user could click on the customer’s name and have the data retrieved instantly from the server, then displayed directly on the Web page.

All major browser platforms now support AJAX, including Internet Explorer, Mozilla FireFox, Netscape, Opera and Safari. There’s also a move toward standardization of XML HTTP, the core component of AJAX. Performing targeted information updates, or microupdates, can substantially reduce network loads, in addition to faster interaction with live data. Benefits can be measured through total bytes transferred, total download time and steps/seconds to complete a task.

Lifecycle of an Ajax Application

The Ajax lifecycle is more like that of a traditional GUI than a traditional web application, with DOM objects acting like GUI widgets. The script registers event listeners on DOM objects, and manipulates the DOM in response to those events. As part of the event-processing cycle, the server may be invoked. There’s actually a slight complication here in that the server calls are asynchronous, so the event-listening phase is split from the event responding phase.

Here’s a typical Ajax lifecycle within the browser:

  • Visit: The user visits a site the usual way, i.e. by clicking on a link or typing a URL.
  • Initialization The page initially loads. Callbacks are established to handle user input
  • Event Loop:
    • Browser Event An event occurs, such as a key press.
    • Server Request The browser sends a request to the server.
    • …<Server processes the event>
    • Server Response A moment later, the server responds, and the response is passed into a request callback function, one that was specified when the request was issued.
    • Browser Update The request callback function updates the DOM, including any JavaScript variables, according to the response.

In particular, many events are handled locally and don’t actually trigger a trip to the server. Also, some Ajax applications are short-lived and the browser interaction is eventually terminated with the user submitting a form. Others remain to interact with the user as long as they are in the user’s browser.

Note that the Browser Event and the Server Request occur in one thread, and the Server Response and Browser Update occur in a separate thread. This is due to the asynchronous nature of the server request.

Implementing AJAX

The heart of the AJAX is the XMLHttpRequest Object. It is a JavaScript object and handles all server communication. In a normal Web application, users fill out form fields and click a Submit button. Then, the entire form is sent to the server, the server passes on processing to a script and when the script is done, it sends back a completely new page. That page might be HTML with a new form with some data filled in or it might be a confirmation or perhaps a page with certain options selected based on data entered in the original form. Of course, while the script or program on the server is processing and returning a new form, users have to wait. Their screen will go blank and then be redrawn as data comes back from the server. This is where low interactivity comes into play — users don’t get instant feedback and they certainly don’t feel like they’re working on a desktop application.

Ajax essentially puts JavaScript technology and the XMLHttpRequest object between your Web form and the server. When users fill out forms, that data is sent to some JavaScript code and not directly to the server. Instead, the JavaScript code grabs the form data and sends a request to the server. While this is happening, the form on the users screen doesn’t flash, blink, disappear, or stall. In other words, the JavaScript code sends the request behind the scenes; the user doesn’t even realize that the request is being made. Even better, the request is sent asynchronously, which means that JavaScript code (and the user) doesn’t wait around on the server to respond. So users can continue entering data, scrolling around, and using the application. 

Then, the server sends data back to JavaScript code (still standing in for the Web form) which decides what to do with that data. It can update form fields on the fly, giving that immediate feeling to your application — users are getting new data without their form being submitted or refreshed. The JavaScript code could even get the data, perform some calculations, and send another request, all without user intervention! This is the power of XMLHttpRequest. It can talk back and forth with a server all it wants, without the user ever knowing about what’s really going on. The result is a dynamic, responsive, highly-interactive experience like a desktop application, but with all the power of the Internet behind it.

Ajax implementation can be divided into following steps:

  1. Getting a request object
  2. Making a request to a server resource.
  3. Handling and processing the server response data

Getting a request object

The request object is implemented in IE as Microsoft.XMLHTTP object or Msxml2.XMLHTTP object whereas other browsers(Mozilla, Firefox, Safari, Opera, and almost every other non-Microsoft browser that supports Ajax in any form or fashion.) implement it as XMLHttpRequest object. 

A cross browser Ajax implementation can create request object in the below given manner:

var xmlHttp;try{          xmlHttp = new ActiveXObject(“Msxml2.XMLHTTP”);} catch (e) {

try {

xmlHttp = new ActiveXObject(“Microsoft.XMLHTTP”);

} catch (e1) {

try {

xmlHttp = new XMLHttpRequest();

} catch (e2) {

xmlHttp = false;

alert(“Error initializing XMLHttpRequest!”);

}

}

}

The request object obtained is responsible for communicating with the server. The XMLHttpRequest object has following methods and properties:

Properties:

  • Onreadystatechange: Event handler for an event that fires at every state change
  • readyState: Provides the current HTML ready state.
  • responseText: The text that the server sends back to respond to a request.
  • responseXML: DOM-compatible document object of data returned
  • status: HTTP status code
  • statusText: String message associated with the status code

Methods:

  • open(): Sets up a new request to a server.
  • send(content): Sends a request to a server.
  • abort(): Bails out of the current request.
  • getAllResponseHeaders()
  • getResponseHeader(“<headerName>”)
  • setRequestHeader(“<name>”, “<value>”)

Making a request to a server resource:

We can begin the request/response cycle once we have the request object. XMLHttpRequest’s only allows us to make requests and receive responses. Everything else like 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 the pages. Ajax implements sandbox security model and as a result, our Ajax code (and specifically, the XMLHttpRequest object) can only make requests to the same domain on which it’s running.

We use the open() of the XMLHttpRequest object to create a request to the server. The open method takes in the following parameters:

  • request-type: The type of request to send. Typical values are GET or POST, but you can also send HEAD requests.
  • url: The URL of the server resource 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.
xmlHttp.open(“GET”, url, true);

The send() method of the request object is used to send the request to the server. The send method takes in the data object, required to be send to the server, as the parameter. While using the GET method we normally send the data in the URL. When there is no need to pass data along through send(), then just pass null as the argument to this method

xmlHttp.setRequestHeader(“Content-Type”, “text/plain”);xmlHttp.open(“GET”, url, true);   xmlHttp.onreadystatechange = callback function;

request.send(null);

While sending a POST request, as opposed to a GET request, it requires a plaintext or xml to be sent with the request. However, sending an XML across to the server makes the process slow. The XML sent should also comply with the XML format accepted by the server.

xmlHttp.setRequestHeader(“Content-Type”, “text/xml”);xmlHttp.open(“POST”, url, true);   xmlHttp.onreadystatechange = callback function;

request.send(parameterString/parameterXMLString);

Handling and processing the server response data:

In the previous section we understood how to obtain a XMLHttpRequest object and making a server request. After sending the request the response data obtained from the server is processed in the JavaScript code of your page.

The onreadystatechange property of the request object is used to lookup the JavaScript function responsible for handling the server response. These methods are popularly known as callback methods. 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.

In fact, the callback method is called every time the HTTP ready state changes. So what does that mean? 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. There are five ready states in any Ajax applications:

  • 0: The request is uninitialized (before we called open()).
  • 1: The request is set up, but hasn’t been sent (before we called send()).
  • 2: The request was sent and is being processed (we 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; we get the server’s response and use it.

Below given is the example of a call back function skeleton:

function updatePage() {
if (request.readyState == 4) {
//do something
}
}

But the above given callback function is a short-sighted and error-prone approach to Ajax programming.

Suppose a script requires authentication and the request does not provide valid credentials, the server will return an error code like 403 or 401. However, the ready state will be set to 4 since the server answered the request (even if the answer wasn’t what was expected for the request). As a result, the user is not going to get valid data and might even get a nasty error when the JavaScript tries to use non-existent server data. This problem is solved by using the status property of the XMLHttpRequest object. It takes minimal effort to ensure that the server not only finished with a request, but returned an “Everything is OK” status code (200) reported through the status property of the XMLHttpRequest object. The following function checks the status of the request:

function updatePage() {
if (request.readyState == 4) {
if (request.status == 200) {
//do something
} else
alert(“status is ” + request.status);
}
}

With the addition of a few lines of code, we can be certain that if something does go wrong, the user will get a (questionably) helpful error message rather than seeing a page of garbled data with no explanation.
With ready states and the server’s response in our bag of Ajax programming techniques, we’re ready to add another level of sophistication to our Ajax applications — working with HTTP status codes.

  • 401: Unauthorized
  • 403: Forbidden
  • 404: Not Found

We can add another layer of control and responsiveness (and particularly more robust errorhandling) to our Ajax applications, by checking the status codes in a request and respond appropriately and handling them.

function updatePage() {
if (request.status == 200) {
//do something
} else if (request.status == 404) {
alert (“Requested URL is not found.”);
} else if (request.status == 403) {
alert(“Access denied.”);
} else
alert(“status is ” + request.status);
}
}

The response from the server can be obtained in either the xml format or the plain text format. Response is handled in the JavaScript as shown below:

function updatePage() {
if (request.readyState == 4) {
if (request.status == 200) {
var response = request.responseText; /// for the output in text format.
OR
var xmlDoc = request.responseXML; /// for output in XML format.
// response has the XML response from the server
alert(response);
}
}
}

The HTML Document can then be updated or modified based on the response received.
The HTML page is treated as a HTML DOM. The browser represents the HTML Document as a set of objects, each of which can be changed, added to, or deleted.

DOM – Document Object Model

The Document Object Model is a W3C standard .Because of that, all modern Web browsers support the DOM. The DOM is also a cross-language specification; in other words, you can use it from most of the popular programming languages

The HTML web pages are all about the organization of the content on the page. Markup is all about providing this level of organization; a p indicates that text is in a paragraph, img denotes an image, div divides a page up into sections, and so forth. The browser takes all this textual organization and turns it into something much more interesting — a set of objects, each of which can be changed, added to, or deleted. Today’s web browsers change the markup language pages into an object tree structure.

For example the below given HTML page is converted to the shown tree structure:

<html>
<head>
<title>Trickier nesting, still</title>
</head>
<body>
<div id=”main-body”>
<div id=”contents”>
<table>
<tr><th>Steps</th><th>Process</th></tr>
<tr><td>1</td><td>Figure out the <em>root
element</em>.</td></tr>
<tr><td>2</td><td>Deal with the <span id=”code”>head</span>
first,
as it’s usually easy.</td></tr>
<tr><td>3</td><td>Work through the <span id=”code”>body</span>.
Just <em>take your time</em>.</td></tr>
</table>
</div>
<div id=”closing”>
This link is <em>not</em> active, but if it were, the answers
to this <a href=”answers.html”><img src=”exercise.gif” /></a>
would be there. But <em>do the exercise anyway!</em>
</div>
</div>
</body>
</html>
domimage

The above given tree structure is the DOM tree notation of the HTML page. DOM stands for Document Object Model and is a specification available from the World Wide Web Consortium. More importantly though, the DOM defines the objects’ types and properties that allow a browser to represent markup.

Node:

A node is the most basic object type in the DOM. In fact, almost every other object defined by the DOM extends the node object. In a DOM tree, almost everything is a node. Every element is at its most basic level a node in the DOM tree. Every attribute is a node. Every piece of text is a node.

According to the DOM, everything in an HTML document is a node.The DOM says that:

  • The entire document is a document node
  • Every HTML tag is an element node
  • The texts contained in the HTML elements are text nodes
  • Every HTML attribute is an attribute node
  • Comments are comment nodes

Properties of a node

The key properties of a DOM node are:

  • nodeName reports the name of the.
  • nodeValue gives the “value” of the node.
  • nodeType gives the type of node(element node, attribute node, text node or document node)
  • parentNode returns the node’s parent.
  • childNodes is a list of a node’s children.
  • firstChild is just a shortcut to the first node in the childNodes list.
  • lastChild is another shortcut, this time to the last node in the childNodes list.
  • previousSibling returns the node before the current node. In other words, it returns the node that precedes the current one, in this node’s parent’s childNodes list .
  • nextSibling is similar to the previousSibling property; it turns the next node in the parent’s childNodes list.
  • attributes is only useful on an element node; it returns a list of an element’s attributes.

Methods of a node

Next up are the methods available to all nodes:

  • insertBefore(newChild, referenceNode) inserts the newChild node before the referenceNode.
  • replaceChild(newChild, oldChild) replaces the oldChild node with the newChild node.
  • removeChild(oldChild) removes the oldChild node from the node the function is run on.
  • appendChild(newChild) adds the newChild node to the node this function is run on.
  • newChild is added at the end of the target node’s children.
  • hasChildNodes() returns true if the node it’s called on has children, and false if it doesn’t.
  • hasAttributes() returns true if the node it’s called on has attributes, and false if there are no attributes.

Common node types

In most Web applications, you’ll only work with four types of nodes:

  • Document node represents an entire HTML document.
  • Element nodes represent HTML elements like a or img.
  • Attribute nodes represent the attributes on HTML elements, like href (on the a element) or src (on the img element).
  • Text nodes represent text in the HTML document, like “Click on the link below for a complete set list.” This is the text that appears inside elements like p, a, or h2.

Document node

The first node type is used in almost every piece of DOM-based code: the document node. The document node is actually not an element in an HTML (or XML) page, but the page itself. So in an HTML Web page, the document node is the entire DOM tree. In JavaScript, the document node can be accessed by using the document keyword:

// These first two lines get the DOM tree for the current Web page, and then the <html> element
for that //DOM tree
var myDocument = document;
var htmlElement = myDocument.documentElement;

The document keyword in JavaScript returns the DOM tree for the current Web page. From there, we can navigate to and work with all the nodes in the tree.

We can also use the document object to create new nodes, using methods like these:

  • createElement(elementName) creates an element with the supplied name.
  • createTextNode(text) creates a new text node with the supplied text.
  • createAttribute(attributeName) creates a new attribute with the supplied name.

The key thing to note is that these methods create nodes, but do not attach them or insert them into any particular document. For this, we have to use one of the insertBefore() or appendChild().

var pElement = myDocument.createElement(“p”);
var text = myDocument.createTextNode(“Here’s some text in a p element.”);
pElement.appendChild(text);
bodyElement.appendChild(pElement);

Element node

In an HTML DOM, every HTML tag is an element node

  • Methods that relate to working with attributes:
  • getAttribute(name) returns the value of the attribute named name.
  • removeAttribute(name) removes the attribute named name.
  • setAttribute(name, value) creates an attribute named name, and sets its value to value.
  • getAttributeNode(name) returns the attribute node named name.
  • removeAttributeNode(node) removes the attribute node that matches the supplied node.

Methods that relate to finding nested elements:

  • getElementsByTagName(elementName) returns a list of element nodes with the supplied name.
  • getElementById(id) returns an element node with the supplied id.
var imgElement = document.createElement(“img”);
imgElement.setAttribute(“src”,
imgElement.setAttribute(“width”, “130”);
imgElement.setAttribute(“height”, “150”);
bodyElement.appendChild(imgElement);

In the code above, the JavaScript creates a new img element, sets up some attributes, and then adds it to the body of the HTML page.

Attribute node

The DOM represents attributes as of the HTML tags, and we can always get an element’s attributes using the attributes property of an element, as shown here:

// Remove all the top-level <img> elements in the body
var imgElements = bodyElement.getElementsByTagName(“img”);
for (i=0; i<imgElements.length; i++) {
var imgElement = imgElements.item[i];
// Print out some information about this element
var msg = “Found an img element!”;
var atts = imgElement.attributes;
for (j=0; j<atts.length; j++) {
var att = atts.item(j);
msg = msg + “\n ” + att.nodeName + “: ‘” + att.nodeValue + “‘”;
}
alert(msg);
bodyElement.removeChild(imgElement);
}

We use the methods available on the element node to work with attributes. The methods are as follows:

  • getAttribute(name) returns the value of the attribute named name.
  • removeAttribute(name) removes the attribute named name.
  • setAttribute(name, value) creates an attribute named name and sets its value to value.

Text node

The last type of node in working with HTML DOM trees is the text node. We use the nodeValue property to get the text from a text node, as shown here:

var pElements = bodyElement.getElementsByTagName(“p”);
for (i=0; i<pElements.length; i++) {
var pElement = pElements.item(i);
var text = pElement.firstChild.nodeValue;
alert(text);
}

A few other methods are specific to text nodes. These deal with adding to or splitting the data in a node:

  • appendData(text) adds the text you supply to the end of the text node’s existing text.
  • insertData(position, text) allows you to insert data in the middle of the text node. It inserts the text you supply at the position indicated.
  • replaceData(position, length, text) removes the characters starting from the position indicated, of the length indicated, and puts the text you supply to the method in the place of the removed text.

What type of node?

Most of what we have seen so far assumes we already know what type of node we are working with, which isn’t always the case. So we need to figure out what type of node we have before we can do much with it.

The DOM node type defines several constants, like this:

  • Node.ELEMENT_NODE is the constant for the element node type.
  • Node.ATTRIBUTE_NODE is the constant for the attribute node type.
  • Node.TEXT_NODE is the constant for the text node type.
  • Node.DOCUMENT_NODE is the constant for the document node type.

We use the nodeType property to compare a node to the above constants, as shown here:

var someNode = document.documentElement.firstChild;
if (someNode.nodeType == Node.ELEMENT_NODE) {
alert(“We’ve found an element node named ” + someNode.nodeName);
} else if (someNode.nodeType == Node.TEXT_NODE) {
alert(“It’s a text node; the text is ” + someNode.nodeValue);
} else if (someNode.nodeType == Node.ATTRIBUTE_NODE) {
alert(“It’s an attribute named ” + someNode.nodeName
+ ” with a value of ‘” + someNode.nodeValue + “‘”);
}

WHY USE AJAX?

Building a web application that employs AJAX is more difficult than building it the classic way. We need to go to extra lengths to make sure that the user experience is and remains enjoyable, and not annoying. With all the hype going around AJAX, a lot of applications that do not have a real need for it have been built. These are toys meant to prove that AJAX is fun, but with little or no use in real-life situations. The decision whether an application would benefit from using AJAX or not is entirely up to the developer.

Advantages of AJAX

Here are some of the advantages AJAX has over classic web development techniques:

  1. The interface is much more responsive, as explained before, because only a small part of the page is transferred at a time. The user has the feeling that changes are instantaneous.
  2. In a classic web application, when the web server sends a web page to the browser, it can use multiple connection threads to speed up delivery. However, this happens for content only – what is between the <body> tags. All script and CSS files linked in the page’s <head> section are transferred using only one connection thread, which diminishes performance. With AJAX, we only have to load the basic scripts and CSS files, and request the rest as content, through multiple connections.
  3. Waiting time is reduced – when the visitor submits a form, they no longer have to wait for the entire page to be rebuilt and re-transmitted by the server. Instead, only the relevant content changes, and in non-critical cases, the visitor can still work while the data is being submitted.
  4. If a page section encounters an error, other sections are not affected (if not logically linked) and the data already entered by the user is not lost. This way, the application fails graciously, without causing head-aches for the users.
  5. Traffic to and from the server is reduced considerably – because we do not have to send the entire page content (CSS, images, static sections), the bandwidth usage is most likely to decrease.

Disadvantages of AJAX

As with most new web development techniques, AJAX has its critics. There are a couple of disadvantages that need to be considered before considering an AJAX-based solution:

  1. Building an AJAX-powered application can increase development time and costs. It is usually considered more difficult than building a classic web application, because of the mixture of technologies and the special concern about everything going smoothly. However, because it is dealing with relatively known technologies, AJAX is easy to learn.
  2. Although AJAX relies on existing and mature technologies like Javascript, HTML and CSS, the available frameworks and components still need to completely mature. Tools like the Dojo toolkit or the Rico framework are just a milestone on this long road. More frameworks that target a specific area are likely to come your way. 
  3. Not all concerns regarding security and user privacy have been answered. This fueled a wave of criticism about how safe is the AJAX way of building applications. 
  4. Using AJAX to asynchronously load bits of content into an existing page conflicts with the way we are used to navigate and create bookmarks in modern browsers. Because viewing some part of the page information no longer corresponds to a newly loaded page, the browser history and bookmarks will not be able to restore the exact page state. Also, clicking the Back button in a browser might not have any effect, since the URL was unchanged (even if parts of the page were changed).
  5. AJAX is not meant to be used in every application. A much better idea than creating complete AJAX applications would be to scatter AJAX features within the application.
  6. The biggest concern with AJAX is accessibility. This is because not all browsers (especially older ones) have complete support for JavaScript or the XMLHttpRequest object. Some of the visitors do have browsers with the required features, but they choose or have to turn off JavaScript support. When you design the application you must make sure that a fail-safe solution exists for those users, so it can be accessed by anyone. Further more, the way to access and use the XMLHttpRequest object in Internet Explorer and other browsers is different, which leads to a fork in the code and the need to treat each case separately.
  7. The last disadvantage lies in the actual XMLHttpRequest object itself. Due to security constraints, you can only use it to access information from the host that served the initial page. If you need to display information from another server, it is not possible within the AJAX paradigm.

Some uses of AJAX in a J2EE Application:

  1. REALTIME FORM DATA VALIDATION: Form data such as user ids, serial numbers, postal codes, or even special coupon codes that require server-side validation can be validated in a form before the user submits a form.
  2. AUTO-COMPLETION: A specific portion of form data such as an email address, name, or city name may be auto-completed as the user types. Another use can be automatic filling of data based on some entry or selection in the form.
  3. MASTER DETAILS OPERATIONS: Based on a client event an HTML page can fetch more detailed information on data such as a product listing that enables the client to view the individual product information without refreshing the page.
  4. SOPHISTICATED USER INTERFACE CONTROLS: Controls such as tree controls, menus, and progress bars may be provided that do not require page refreshes.
  5. REFRESHING DATA ON THE PAGE: HTML pages may poll data from a server for up to date data such as scores, stock quotes, weather, or application specfic data.
  6. SERVER-SIDE NOTIFICATIONS: An HTML page may simulate a server-side push by polling the server for event notifications which may notify the client with a message, refresh page data, or redirect the client to another page.
  7. INFORMATION POP-UPS: We can display information about some of the required fields in the page in the form of pop-ups attached to onmouseover event. 

Performance Considerations

An application is really useful only when it functions at a reasonable speed. The performance depends on two factors – how fast a program runs and the amount of resources it consumes. This is critical for AJAX development as the AJAX based applications involve lots of JavaScript codes and DOM elements. JavaScript is relatively a slow language and does not do calculations as fast as any other programming languages. Therefore we should try to do the as much of calculation as possible in the server. Also DOM elements occupy considerable amount of memory. As execution speed and memory consumption are two important factors affecting the performance of an application, excessive care has to be taken while developing AJAX based applications.

Execution Speed

The execution speed can always be improved by optimizing the codes. The process of measuring the execution speed is called profiling. 

To measure the execution time in JavaScript codes, instantiate Date Objects in the beginning and ending of execution parts. Subtracting these two will give the time taken for that execution in milliseconds. This is a simple way to find out the execution time for a JavaScript programming unit.

This is illustrated below.

function executionTime(){
var begin = new Date();
// execution part – programming unit with complex logics
var end = new Date();
var timeTaken = begin – end; // This variable gives the execution
//time for the execution unit
}

Optimization – AJAX

Some optimization techniques for AJAX (JavaScript codes and DOM elements) are mentioned in the subsequent sections.

Dot notations

In JavaScript the variables of objects in the deeply nested hierarchy can be specified using dots as follows:

var hour= object1.clock.hands.hour;
var minute= object.1clock.hands.minute;
var second= object1.clock.hands.second;

The variables available in the hands object i.e. hour, minute, second are retrieved by doing nine look ups. The hands object is looked up for each and every variable’s retrieval which could have been avoided by compiler optimization as Java does. But JavaScript does not do this optimization. Therefore the programmer has to do the optimization in such scenarios in the code itself. The above code can be optimized to make five look ups only as follows.

var element = object1.clock.hands;
var hour= element.hour;
var minute= element.minute;
var second= element.second;

Optmizing Loops:

Consider the following example:

function loopCounter(var count){
var value=0;
for(var i=0;i<count;i++){
value++;
}
return value;
}
function realLogic(var count){
for(var i=0;i<loopCounter(count);i++){
// do some complex logic
}
}

In the above mentioned examples, the realLogic(count) function will take a long time as the function loopCounter(count) used in the condition part of For loop will have to executer for all the loop iterations. This function can be optimized as follows so that the loopCounter(count) function will be called only once and the rest of the logic will remain intact.

function realLogic(var count){
var condition =loopCounter(count);
for(var i=0;i<condition;i++){
// do some complex logic
}
}

Thus this simple optimization of removing the function call from the condition part of for loop to before for loop will increase the execution time of the programming part considerably.

DOM Manipulation

Avoid writing output multiple times to the document, concatenate the data and then write all in one go.

function modifyData(){
var element = document.getElementById(‘dest’);
element.innerHTML = ‘’; // Clear out the previous
element.innerHTML += modifyTitle();
element.innerHTML += modifyData();
element.innerHTML += modifyFooter();
}

The above function can be optimized as follows to increase the execution speed.

function modifyData ()
{
var elementText = modifyTitle () + modifyData () + modifyFooter();
document.getElementById(‘dest’).innerHTML = elementText;
}

Consider the example below:

var newElement = document.createElement(“div”);
var appendElement = document.getElementById(“append”);
appendElement.appendChild(newElement);
for(var i=0;i<count;i++){
// Add few more elements to the newElement
var element1== document.createElement(“div”);
//Apply style/logic to element1
newElement.append(element1);
}

Optimized code:

var newElement = document.createElement(“div”);
var appendElement = document.getElementById(“append”);
for(var i=0;i<count;i++){
// Add few more elements to the newElement
var element1== document.createElement(“div”);
//Apply style/logic to element1
newElement.append(element1);
}
appendElement.appendChild(newElement);

Conclusion

We have seen that AJAX interactions can solve many problems. J2EE technology provides a good base to develop and deploy AJAX-based applications with APIs for tying in HTTP processing, databases, web services, XML processing, and business objects. With a better understanding of this interaction model, today’s applications can become more interactive, providing the end user with a better experience.

What is particularly attractive about this is that AJAX applications do not require a separate plug-in, and are platform and browser-neutral. That said, AJAX is not supported as well in older browsers. Care needs to be taken in writing client-side script that accounts for the differences between browsers. Using AJAX requires that we use the latest browser versions that support the XMLHttpRequest object needed for AJAX interactions. Using AJAX also requires a great deal of client-side JavaScript technology and CSS. As an application architect or developer, you will need to weigh the needs of having a rich application against browser support, architecture complexity, and developer training. As the AJAX programming model evolves, existing technologies and frameworks will make this transition easier.

Despite some drawbacks, AJAX has generated real excitement with its promise of more responsive Web interactions. Hopefully by now you realize that AJAX is simply exchanging information over HTTP in the background of a page, and updating that page dynamically based on the results.

References

 
3 Comments

Posted by on November 24, 2008 in Web

 

Tags: , , , ,

UI Framework – A Modern Approach for Web Applications

ABSTARCT

UI frameworks are emerging to become an accepted standard for building complex, consistent and maintainable presentation layer for a web application. UI frameworks, when implemented sets standard for developing presentation layer of any web application.

Adopting such a framework can greatly simplify application development, and provide a measure of consistency and predictability across a family of developed systems.

This whitepaper explores more about what is UI framework and how the power of Sun’s Java Server Faces can be leveraged to build a more generic UI framework for a complex web application. It also includes advantages and some examples of the UI framework implementation.

Introduction

The Internet has no doubt become the most popular source of information today. More and more businesses have adopted the Internet as the vehicle to display their business information, advertise their products, and maintain customer interactions. The activity of developing Web applications occupies a fair amount of resources, time, and effort. Doing so in an efficient and timely manner directly contributes to a business’s success.

The ability to rapidly develop a Web site to support business changes poses a challenge to many companies. Consequently, a reusable, scalable, and extensible user interface (UI) framework for developing Web applications is undoubtedly desirable.

what is UI framework?

UI framework development essentially promotes some common design goals like: modularity, information hiding, ease of use and layered approach in order to conquer complexity.

  • A typical web UI framework involves following features:
  • Rapid Application development support
  • Clean component model
  • Advanced form handling
  • Rich  and reusable component set
  • Pluggable look and feel
  • Easy internationalization
  • Integration with the other frameworks/applications.

Rapid application development support 

It is absolutely necessary that one is able to compose a form or even a flow of forms in a website in a rapid prototyping mode. The Developer should not much bother about the underlying technology.

Clean component model

The framework system provide a clean and concise object oriented component model as known from traditional UI programming. This includes super classes that provide common behavior and state. Also, there will be a common event handling mechanism as well as a mechanism to separate view, controller and model in a proper way.

Advanced form Handling

Handling of forms is automated as much as possible. This includes automatic type conversion of form input as well as form value formatting. Of course, form handling provides an automatic error handling facility at the level of individual components but also at the level of the form itself. The framework also provides a set of typical validators.

Rich Component Set

Given today requirements, the framework provides a component set that includes all the standard html controls. But other components are also there include to offer real benefits, since these are the components developed (or copy-and-pasted) over and over again in typical web projects. Such components include but are not limited to 

  • Tables – with events of course
  • Calendar controls
  • Date and time chooser
  • Country chooser
  • Tabbed panes
  • Tree controls 

Pluggable Look and Feel

Each and every website has a unique look and feel. The framework provides a support for pluggable rendering facilities. This can be achieved with a clear component model for renderers and pluggable render factories. Also, a sophisticated framework provides support for on-line switching of the underlying render engine and for choosing a custom render mechanism for individual components to satisfy typical customer’s requirements. 

Easy Internationalization

Internationalization is there in every aspect of the ui components – renderers as well as formatters and type converters – in a way that makes it possible to switch internationalization settings at any point at runtime.

Integration with other programming models  of frameworks

Framework provides integration with other technologies also through various mechanisms. This feature allows UI to sustain amidst multi-technical platforms.  Like, there may be a requirement to for an application to talk to a different application. So, framework caters such requirements.

UI Framework Benefits

Adopting a UI framework for any web application development results into following advantages:

  • Today, the major part of web application across any enterprise suffers from lack of these features discusses above, which in turn results into higher development cost for any enterprise, If they are having multiple UI based application portfolio. Incorporating a framework makes cost down.
  • This allows the UI (i.e., Web pages) to be developed independently of the business logic, enabling a loose coupling between presentation and business implementation.
  • Adoption of framework dictates standards across applications.
  • Developers are required to be very knowledgeable in a wide variety of UI coding languages such as html, jsp, css, asp, JavaScript and xsl.
  • When one follows a UI standard, there are typically IDE plug-ins that greatly simplify building the UI.

Currently, there are a variety of frameworks available to implement the above features like Sun’s Struts and Java server faces. Some open source like iternum. Also, some companies prefer to develop their own framework on platforms like J2EE or .net.

Java Server Faces –  Introduction

In the past, technologies such as JavaServer Pages (JSP) have provided a primitive approach to develop HTML-based Web applications using Java. However, they have failed to provide a standard and reusable UI framework. The JavaServer Faces (JSF) technology offers a standard and effective way to manage and develop reusable UI components, which together assemble a Web application.

Some key points about JSF are as follows:

  •  JSP page is made up of UI components
  • UI component values are stored as properties in Managed Java Beans. Each UI component will specify a specific bean and bean property that it represents.  As a result there can be many beans that represent the html form. This is unlike Struts where there is only one bean per form – the Form Bean.
  • UI components can be associated with a Java Bean (the whole component, not just the value of the component). In this case the Java Bean is called a Backing Bean. Using a backing bean gives the developer access to all UI components in a form.
  • Actions are associated with UI components unlike Struts where an action is associated with the form.

The following diagram shows the typical request flow of  a JSF based web page:

image6

UI Framework development with JSF

JSF provides certain UI components that can be used to develop web pages easily coupled with Java beans for business logic.

Any web application’s UI has following features in general like:

  • Framework (including login, banner, navigator tree, content area, page path)
  • Data Manager ( table /List)
  • Search
  • Properties Pages
  • Wizards
  • Modal Dialogues (including confirmation, error, warning, wait, etc.)
  • Special Messages window
  • On-line Help

A JSF component can be written for all these features in a more generic way and the same can be utilized in more generic way across pages/across applications.

 And coding in a page would be as simple as :

 <b:myPage  styleClass=”subtle”  styleClassSecond=”datashow” class=”someBean” />

 instead of hundreds of lines of HTML/JavaScript code.

An Example of Framework based Application

Below we have screenshot to two sample application that are  built using JSF based UI framework.

The main feature which have been utilized here are: 

  • Tiles for common layout like banner, navigator and content page
  • table component functionality which will be used across application
  • JSF component for navigation tree
  • JSF component for path 

Conclusion

In today’s customer-oriented economy, even the best technology does not guarantee market acceptance. Factors such as benefits to business, cost of adoption, and availability of service and support from tools influence a business’s decision on whether or not to adopt a new technology. Businesses must understand the implications of a new technology on each of the above concerns. So a UI framework eases the process of designing, developing, and maintaining Web applications and creates a cost effective development environment.

 
Leave a comment

Posted by on November 22, 2008 in Web

 

Tags: ,

SmartGWT 1.0 Released! – GWT wrapper on SmartClient

Sanjiv Jivan, original creator of GWT-Ext, posted on SmartGWT, a new wrapper on top of SmartClient.

Here is the release announcement : 
http://www.jroller.com/sjivan/entry/smartgwt_1_0_released 

Google Code Project Page : http://code.google.com/p/smartgwt/ 

Showcase Demo : http://www.smartclient.com/smartgwt/showcase/ 

Javadocs : http://www.smartclient.com/smartgwt/javadoc/ 

SmartGWT uses the new GWT 1.6 event API’s

Screenshots:

smartgwt
smartgwt11
smartgwt2
 
Leave a comment

Posted by on November 21, 2008 in GWT

 

Tags: ,

Spry…!!! – A Framework for AJAX

Introduction

Spry is an AJAX based framework which consists of JavaScript library that provides AJAX functionality enabling designers to provide rich interfaces to its users.

Background

Most of the web designers are inclined towards creating good and vibrant interfaces but are not sure how to get started with AJAX. Considering the steep learning curve for AJAX, an utmost need is felt by the developers for and HTMLcentric framework which can help add basic functionality and interactivity to the pages.

Purpose

Spry is an easy to use and moreover a HTML-Centric framework consisting of JavaScript libraries, and easy to implement for users with basic knowledge of HTML, CSS and JavaScript.

Implementation

The implementation of spry consists of two basic prerequisites.

  • Spry data set
  • Spry dynamic region

 

 A spry data set is an essential requirement for spry pages to work. A spry data set is a JavaScript object. When the user opens the spry page, this object is created and the data is loaded from a XML source. Once the Spry data set is created, the data is displayed in the Spry dynamic region. Before the creation of Spry data sets the necessary files have to be obtained (xpath.js & SpryData.js)*. The file xpath.js is used since it allows the usage of complex XPATH expressions when creating data sets. The file SpryData.js contains the spry data library. The link for both these files need to be present in the HTML file created.

The SpryData.js file is dependent on xpath.js file. Hence it is important that the link for the file xpath.js file comes first in the code.

Some of the functionalities considered in this document include:

  • Widgets – Tabbed panels
  • Autosuggest
  • Tool tip
  • Photo Gallery

* The files are to be obtained from adobe website(http://labs.adobe.com/technologies/spry/) Spry_P1_6_10-01.zip

The details for implementation of each of the above functionalities are as follows:

Widgets

Widgets being a common feature of Ajax frameworks, play a wide role in interactive user interfaces. A widget is a block of HTML, CSS and JavaScript that encapsulates the piece of data for the advanced user interface. The commonly used widgets include trees and tabbed interfaces. Use of these widgets requires advanced coding skills with the conventional frameworks. 

Spry consists of HTML, CSS and custom Spry attributes. There are no additional learning for custom tags included with Spry. This makes it easier to use and implement.

Example of a Spry widget.

<div id=”TabbedPanels1″ class=”TabbedPanels”>
<ul class=”TabbedPanelsTabGroup”>
<li><a href=””>Photo Album</a></li>
<li><a href=””>Tool tip</a></li>
<li><a href=””>Form Validation</a></li>
<li><a href=””>Auto Suggest Widget</a></li>
</ul>
<div id=”contentGroup”>
<div class=”TabbedPanelsContent” id=”widget1″>
<table>
<!– staaart here–>
To view the photo album example click <a
href=”D:\spryWkSpace\Spry\photoGallery.html”> here </a>
<!– end here –>
</table>
</div>
<script type=”text/javascript” language=”javascript”>
function InitPage(){
Spry.$$(“ul.TabbedPanelsTabGroup >
li”).addClassName(“TabbedPanelsTab”);
Spry.$$(“#contentGroup”).addClassName(“TabbedPanelsContentGroup”);
Spry.$$(“.TabbedPanelsTab”).setAttribute(“tabindex”, “0”);
Spry.$$(“.TabbedPanels”).forEach(function(n) { new
Spry.Widget.TabbedPanels(n);});
}
Spry.Utils.addLoadListener(InitPage);
</script>

 

From the code above it is easy to figure out how to build a tabbed panel.

Main container DIV

A DIV for each panel

A DIV for panel header

A DIV for the content.

 One of these kinds includes working with tabbed panels:

This is basically used to store the contents in the compact space. This allows the designer to reveal and hide the contents simultaneously by clicking the tabs. In tabbed panel widget only one content panel is open at any given time. The figure shows the working example for the same.

image12

Fig1: Tabbed Panels

You can set a panel to be open when the page containing the Tabbed Panels widget loads in a browser.
Set the defaultTab option in the constructor as follows:

<script type=”text/javascript”>
var TabbedPanels1 = new
Spry.Widget.TabbedPanels(“TabbedPanels1″, { defaultTab: 0 });
</script>

Note: The Tabbed Panels widget uses a zero-based counting system, so setting the value to 0 opens the first tabbed panel.

Autosuggest

This feature is used for the Search box where the matching search hints will be displayed to the user, underneath the text field. This matching results can thereby be selected by the user.

The autosuggest widget has the container DIV, an input DIV and another DIV tag which contains the search results.

<div id=”productSampleTable” class=”container”
style=”float:left”>
<br />
<form method=”get” onsubmit=”return validate(this);”>
<input type=”text” id=”productFilter” name=”tanya”/>
<div id=”productMenuTable” spry:region=”dsProducts2″>
<table>
<tr spry:repeat=”dsProducts2″
spry:suggest=”{name}”>
<td class=”list”><div>{name}</div></td>
</tr>
</table>
</div>
<input type=”submit” value=”submit”>
</form>
</div>
<script type=”text/javascript”>
validate = function(formEl)
{
var inputs = formEl.getElementsByTagName(‘input’);
var typedValue = ”
for (var i=0; i < inputs.length; i++)
{
if
(inputs[i].getAttribute(‘type’).toLowerCase() == ‘text’){
typedValue +=’ ‘+inputs[i].value;
inputs[i].value = ”;
}
}
alert(‘Entry: \n’ + typedValue);
return false;
}
var as2 = new
Spry.Widget.AutoSuggest(“productSampleTable”,
“productMenuTable”, “dsProducts2″, ‘name’);
</script>

The constructor has the four required values and an optional value.

The outer DIV is the main container of the widget. The ID attribute is reference by the constructor, hence an mandatory field

The widget contains a text field for the search term.

The inner DIV is the container for the results. The container also includes a spry region so that it can display the results.

image32

Fig:2 AutoSuggest Example

Tooltip

The tooltip widget gives the flexibility to the user to move the mouse over a desired content to reveal the additional information.

For the implementation of tooltip, the file SpryTooltip.js is an important resource to be included in the code.

<div id=”container”>This is the tooltip content</div>
<script type=”text/javascript”>
var tt_one = new Spry.Widget.Tooltip(“container”,”#trigger”);
</script>

The arguments for the constructor are:

The ID of the tooltip container.

The CSS selector of the trigger. Notice that we have to put the # in front of this ID, to transform the ID in a CSS selector. The selector can specify an element ID,  can be a class name, HTML tag name or a more complex selector as a combination of the these.

Please refer the figure below for the implementation.

image31

Fig3. ToolTip

Photo Gallery

The implementation for display for photo galley includes the CSS definitions for display of thumbnails and when clicked on any of the thumbnails, corresponding pictures are displayed. This path as well as other display properties for these thumbnails and pictures are provided in the xml file

A snippet of the file image.xml is as below.

<photo
path = “111.bmp”
width = “263”
height = “350”
thumbpath = “travel_01.jpg”
thumbwidth = “56”
thumbheight = “75”>
</photo>

The data set is created in the html file with the use of following code snippet.

<script type=”text/javascript”>
var gallery = new Spry.Data.XMLDataSet(“image.xml”,
“/gallery/photos/photo”);
var data = new Spry.Data.XMLDataSet(“image.xml”,
“/gallery”);
</script>

The snapshot of the application is as follows:

image21

Fig 4: Photo Gallery

Advantages of Spry

  • Helps building interactive user interfaces with minimal use of JavaScript and HTML.
  • Often used with Dremweaver.
  • Spry effects can be modified with desired changes in the CSS and JavaScript.
  • No working knowledge required of AJAX functionality for its usage with Spry.

 

References

  • http://labs.adobe.com 
  • JavaScript Usage Ideas http://www.webmonkey.com/webmonkey/06/21/index3a.html?tw=programming
 
Leave a comment

Posted by on November 21, 2008 in Web

 

Tags: ,

Reengineering Web application Performance

This article explains few points that can make a web site scalable and reliable.

Minimize HTTP based Requests

  • Use Image maps to merge up images which are in sequence, like navigation images.
  • Use Inline images to reduce the requests to the server.
  • Use CSS Sprites to merge up images and setting their position and backgrounds.

Using CSS

  • Use a single .css file by combing all the CSS based classes into a single file. Using multiple .css files will cause a large amount of requests
  • CSS files are normally cached by browsers, so a single and heavy .css file doesn’t cause a long wait on each page request.
  • Avoid using inline .css files because they will make HTML page heavy.

Using JavaScript

  • Avoid using Inline JavaScript, which will make the HTML page heavy.
  • Use a separate JavaScript files or a single JavaScript file to keep all the JavaScript-based scripts in a single place.
  • JavaScript files get cached automatically by browsers, so they usually aren’t requested each time the page is loaded by the browsers.

HTTP Compression

  • Use HTTP Compression to compress the contents from the web server. HTTP requests and responses could be compressed, which can result in great performance gains. Through HTTP compression, the size of the payload can be reduced by about 50%, which will increase the performance of the site.

Correct Formatted Images at the Right Place

  • Use JPG/JPEG format to place a background image, some large image or a screenshot
  • Use PNG format to place small graphics like button images, header images, footer images, navigation bar images or clip arts.
  • Use GIF format, if an image is not required to be in high or true colors and 256 colors are enough.

Compress CSS, JavaScript and Images

  • Compress the CSS files (.css), images and JavaScript (.js) files to remove the unnecessary spaces, comments, unnecessary code and such other things.

CSS at Top

  • Use the CSS links on top of the web page, as it makes the page render progressively efficient.

JavaScript at Bottom

  • Use the JavaScript-based scripts at the bottom of a web page.  It is better to display the HTML contents of a page, and then load any scripting code.
  • Use defer attribute to run the script at the end of the page loading, but this attribute is browser dependent.

Content Delivery Network: (CDN)

  • Distribute web application data in different places around the world so the request can be served from the nearest location and save time. Through CDN, the web site can be placed on multiple servers in different locations.

Ajax

  • Use the GET method for Ajax based Requests, because the POST method then the request header would be sent first, followed by the data, which basically splits the request in two steps. A single-step request can be achieved with GET if a cookie is not too long and the URL is not larger than 2k.
  • When using ASP.NET AJAX and the Update Panel control for partial page rendering, use the maximum number of update panels to update small chunks of page, but use them wisely. Don’t set the Update property to Always unless needed. Instead, set the update mode to Conditional, otherwise all the partial chunks would be sent together after each asynchronous postback.
  • Ajax based requests can also be cached when using the GET method. If the URL is the same, then cached data can be used from the client, and a round trip to the server can be avoided.

Callback

  • Ajax is great mechanism for sending requests to the server without making a full page postback, but call back is a good mechanism to send a request to the server without any rendering.
  • For example, to check whether a user exists or not, or if a user has forgotten his/her password and just need to send a request to the server to check if user name exist, there is no need for client-side render – just a server side operation.

Reduce Cookie size

  • Cookies are stored on the client side to keep information about users (authentication and personalization). Since HTTP is a stateless protocol, cookies are common in web development to maintain information and state. Cookies are sent with every HTTP requests, so try to keep them low in size to minimize effects on the HTTP response.
  • Cookie’s size should be minimized as much as possible.
  • Cookies shouldn’t contain secret information. If really needed, that information should be either encrypted or encoded.
  • Minimize the number of cookies by removing unnecessary cookies.
  • Cookies should expire as soon as they become useless for an application.

Use Cache appropriately

  • Use Cache mechanism is a great way to save server round trips – and also database server round trips – as both round trips are expensive processes.
  • Static contents should be cached, like “Contact us” and “About us” pages, and such other pages which contain static information.
  • If a page is not fully static, it contains some dynamic information. Such pages can leverage the ASP.NET technology, which supports partial page caching.
  • If data is dynamically accessed and used in web pages – like data being accessed from some file or database – and even if data is consistently or regularly changed, then that data could be coached by using ASP.NET 2.0 cache dependency features. As soon as data changes from the back-end by some other means, the cache would be updated.

 Upload compiled code rather than source code

  • Pre-compiled ASP.NET pages perform much better than source code versions. Actually pre-compilation give web sites a performance boost especially when the first request is made to a folder containing that resource.
  • Uploading a pre-compiled version boosts up performance since the server doesn’t need to compile a page at request-time.

Other approaches

  • Avoid redirects until needed.
  • Minimize use of Iframes as it’s costly.
  • Avoid try-catch blocks for control-flow as they perform poorly. Exceptions should be used only in truly exceptional situations.
  • Minimize DOM objects on page as they are heavy weight.
  • Use link tags rather than @import to use/link up CSS. 

Please share your valuable information about Reengineering Web application Performance.

 
Leave a comment

Posted by on November 21, 2008 in Web

 

Tags: , , ,

 
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: