Wednesday, June 30, 2010

RichFaces StateManager API



JSF has an advanced navigation mechanism that lets you define navigation from view to view. In a web application, navigation occurs when a user changes from one page to another by clicking on a button, a hyperlink, or another command component. There is no switch mechanism between some logical states of the same view. For example, inLogin/Register dialog, an existing user signs in with his user name and password, but if a new user attempts to register, an additional field (Confirm) is displayed, and button labels and methods are changed when the user clicks the To register link:

RichFaces State API lets you easily define a set of states for pages, and properties for these states.

The States class interfaces with a map, where the keySet defines the State name and the entrySet is a Statemap. The State map defines the properties, method bindings, or constant state variables of a key or object, where these values may change depending on the active State.


One of the most convenient features of the RichFaces State API is the ability to navigate between States. The API implements changes in State through standard JSF navigation. When the action component returns an outcome, the JSF navigation handler (extended through the RichFaces State API) checks whether the outcome is registered as aState change outcome. If true, the corresponding State is activated. If false, standard navigation handling is called.

Implement the RichFaces State API like so:

Register the State Navigation Handler and the EL Resolver in your faces-config.xml file:

org.richfaces.ui.application.StateNavigationHandler

org.richfaces.el.StateELResolver

Register an additional application factory in the faces-config.xml:

org.richfaces.ui.application.StateApplicationFactory

Register two managed beans in the faces-config.xml:

state

org.richfaces.ui.model.States

request

states

org.richfaces.ui.model.States

#{config.states}

config

org.richfaces.demo.stateApi.Config

none

One bean (config) defines and stores State as seen in the following example:

public class Config {

/**

* @return States

*/

public States getStates() {

FacesContext facesContext = FacesContext.getCurrentInstance();

States states = new States();

// Registering new User State definition

states.setCurrentState("register"); // Name of the new state

// Text labels, properties and Labels for controls in "register" state

states.put("showConfirm", Boolean.TRUE); // confirm field rendering

states.put("link", "(To login)"); // Switch State link label

states.put("okBtn", "Register"); // Login/Register button label

states.put("stateTitle", "Register New User"); // Panel title

ExpressionFactory expressionFactory = facesContext.getApplication()

.getExpressionFactory();

// Define "registerbean" available under "bean" EL binding on the page

ValueExpression beanExpression = expressionFactory

.createValueExpression(facesContext.getELContext(),

"#{registerbean}", Bean.class);

states.put("bean", beanExpression);

// Define "registeraction" available under "action" EL binding on the

// page

beanExpression = expressionFactory.createValueExpression(facesContext .getELContext(), "#{registeraction}", RegisterAction.class);

states.put("action", beanExpression);

// Define method expression inside registeraction binding for this state

MethodExpression methodExpression = expressionFactory.createMethodExpression(

facesContext.getELContext(), "#{registeraction.ok}",

String.class, new Class[] {});

states.put("ok", methodExpression);

// Outcome for switching to login state definition states.setNavigation("switch", "login");

// Login Existent User State analogous definition

states.setCurrentState("login");

states.put("showConfirm", Boolean.FALSE);

states.put("link", "(To register)");

states.put("okBtn", "Login");

states.put("stateTitle", "Login Existing User");

beanExpression = expressionFactory.createValueExpression(facesContext

.getELContext(), "#{loginbean}", Bean.class);

states.put("bean", beanExpression);

beanExpression = expressionFactory.createValueExpression(facesContext

.getELContext(), "#{loginaction}", LoginAction.class);

states.put("action", beanExpression);

methodExpression = expressionFactory.createMethodExpression(

facesContext.getELContext(), "#{loginaction.ok}",

String.class, new Class[] {});

states.put("ok", methodExpression);

states.setNavigation("switch", "register");

return states;

}

}

The second bean, with the org.richfaces.ui.model.States type (state), contains the managed propertystates, which is bound to the first config bean.

Next, use state bindings on the page, as in the following example:

Code for the JSP Page is:

Monday, June 21, 2010

RichFaces with Facelets Support

Working on RichFaces with Facelets support for my own project timesheet Application. Purpose of this application is to build a timesheet management system that handles time sheets submission from all the employees whoever working at different clients. This is a convenient system for most of the employers. Started to make it as a RIA Application.

Technologies being used in this system are
1. Front End
RichFaces, JSF
2. Application Level
Spring
3. Persistence Layer
JPA (Java Persistence API)
4. Database
Oracle or MySql database. (Not decided yet)

Not going much at the work apart form analyzing new requirements.




Thursday, June 17, 2010

Today I came across new situation but this happened when I converted my code from Struts 1.2.8 to Struts 1.3.

While converting I have to replace lot of jar files and other configuration files in the source code and this is well maintained by Clearcase SCM. I have deleted one of directory and pasted again with new libraries in it. I should not delete a directory instead should have deleted contents in the directory and paste new libraries in it.

Because of this deletion of directory Clearcase made entries in the lost+found folder in the VOB database. So when I try to deliver the content to the Integration stream it is not allowing. Once I delete the contents in the lost+found folder in the VOB database with the help of Clearcase Admin then I was able to deliver content successfully. I have to study all the materials about how things get into lost+found folder when we do work on source code. It is very interesting to find our there are some couple of ways where we can end up in this situation.

Some of the notes about it

The lost+found directory

Every VOB includes a special directory element, lost+found, which is used to hold elements that become stranded when they are not cataloged in any directory version in the VOB.

An element can become stranded when you do any of the following:

  • Create new elements, and then cancel the checkout of directory in which they were created
  • Delete the last reference to an element by using the rmname command
  • Delete the last reference to an element by deleting a directory version with the rmver, rmbranch, or rmelem command

When an element is moved to lost+found, its name changes to this form:

element_leaf_name.UUID

For example, an element named util.c could have the name util.c.41a00000bcaa11caacd0080069021c7.

The lost+found directory has several unique properties:

  • It cannot be checked out.
  • Its contents can be modified even though it is not checked out.
  • No branches can be created within it.

To conserve disk space, periodically clean up the lost+found directory:

  • If you need an element in lost+found, move it to another directory by using cleartool mv.
  • You can use cleartool rmelem to remove elements from lost+found if you are sure that they are no longer needed. See the rmelem reference page for additional cautions about using rmelem.

Clearcase content deliver issue


ClearCase Delivery Issue.
This issue I have encountered while delivery the content from the development stream to the Integration stream.
ClearCase uses the information associated with your development stream to determine which activities have been worked on and are ready to be delivered. Based on that information, it detects which files need to be merged to your project's Integration stream.

As long as there are no conflicts between your changes and changes made by other developers on your project, the delivery will be completed without any further intervention.

I got the above error while delivering the content.

Undo of the above delivery gives another error described as.

Error canceling delivery to stream kgd62144_SR1144_ASAPS_Current.
Cannot cancel because the integration activity has checkins.
you must remove the checkedin versions then redo cancel or resume operation.
You must manually remove these versions from changesets.
unable to undo checkins.



I have followed following steps to resolve the issue.

1 )Check the delivery status of the stream

ct deliver -status -stream @

Do a long listing of the delivery activity that is created in the target
stream. If there are checkins, then you have to to either do rmver or
handle the checkedin changes later, post delivery cancellation. If there
are checkouts, uncheckout them later,post delivery cancellation

2) Get the dump of the source stream

ct dump -l stream:@

look for the value of the process variable UCM_INTEGRATION_ACTIVITY . Any
nonzero value means that the variable value has to be reset

3)Get the dump of the activity

ct dump -l activity:@

Look for the value of the process variable UCM_DELIVER . Any nonzero value
means that the variable value has to be reset

4)Reset the value for the variables

Reset the value set for UCM_INTEGRATION_ACTIVITY
/opt/rational/clearcase/etc/utils/ucmutil setpvar -pvar
UCM_INTEGRATION_ACTIVITY -none activity:@
ucmutil: Warning: VOB is replicated; can only repair objects mastered in
this replica.
You are about to modify internal data. Any mistake will damage the
objects.
Do you want to continue? no yes
Set UCM_INTEGRATION_ACTIVITY = "" cleared
Reset the value set for UCM_DELIVER
/opt/rational/clearcase/etc/utils/ucmutil setpvar -pvar UCM_DELIVER -none
stream:@
ucmutil: Warning: VOB is replicated; can only repair objects mastered in
this replica.
You are about to modify internal data. Any mistake will damage the
objects.
Do you want to continue? no yes
Set UCM_DELIVER = "" cleared




Wednesday, June 16, 2010

Struts 1.3 Observations.
Below are some of differences I noticed in struts behaviors while converting one of my project at work from struts 1.2.8 to struts 1.3.
In Struts 1.2.x Tiles processing required configuring the framework to use the TilesRequestProcessor implementation when you override RequestProcessor.
In Struts application if we need any custom RequestProcessor, we have to create an extension of the Struts RequestProcessor:

public class ExtendedRequestProcessor extends RequestProcessor {

public ExtendedRequestProcessor() {

}

public boolean processPreprocess(HttpServletRequest request,
HttpServletResponse response) {

...

return true;
}
}
Easy enough-I added a controller entry to my struts-config.xml file:


and restarted my container. As I am watching the console output fly by, I saw the following:
javax.servlet.ServletException: TilesPlugin : Specified RequestProcessor not compatible with TilesRequestProcessor
at org.apache.struts.tiles.TilesPlugin.initRequestProcessorClass(TilesPlugin.java:360)
at org.apache.struts.tiles.TilesPlugin.init(TilesPlugin.java:164)
at org.apache.struts.action.ActionServlet.initModulePlugIns(ActionServlet.java:1158)
at org.apache.struts.action.ActionServlet.init(ActionServlet.java:473)
at javax.servlet.GenericServlet.init(GenericServlet.java:258)

Because I use Tiles, I am forced to extend their RequestProcessor.
public class ExtendedRequestProcessor extends TilesRequestProcessor {

public ExtendedRequestProcessor () {

}

public boolean processPreprocess(HttpServletRequest request,
HttpServletResponse response) {
...

return true;
}

}

But in Struts 1.3 this will not work in the same way. In the Struts 1.3 Chain based request processor using Tiles simply involves configuring it to use an additional Tiles Command, and deploying the tiles sub-project jar(Struts-tiles.jar). The following Command is in the org.apache.struts.tiles.commands package.
Here we need to extend ComposableRequestProcessor and include the following content in the web.xml telling the framework to use Tiles Preprocessor.

chainConfig
org/apache/struts/tiles/chain-config.xml

Since version 1.3, the default Request Processor (ComposableRequestProcessor) is composed using Commons Chain, which is an implementation of the Chain of Responsibility pattern (CoR). It is designed as a drop-in replacement of the Struts 1.2.x behaviour and brings greater flexibility and easier customization to the request processing process. Each step of the processing is represented as a separate Command in the Chain. By inserting, substituting, or removing Commands, you can customize the framework to work your way. Let's take a look at thedefault commands for the ComposableRequestProcessor Chain in turn. These Command classes are in either theorg.apache.struts.chain.commands or org.apache.struts.chain.commands.servlet packages.

Tuesday, June 15, 2010

Sql Injection



1

1. What is SQL Injection?

SQL injection refers to the act of someone inserting a SQL statement to be run on your database without your knowledge. Injection usually occurs when you ask a user for input, like their name, and instead of a name they give you a SQL statement that you will unknowingly run on your database.


2. SQL Injection Example.

Below is a sample string that has been gathered from a normal user and a bad user trying to use SQL Injection. We asked the users for their login, which will be used to run a SELECT statement to get their information.

// a good user's name

name = "Ravi";

query = "SELECT * FROM customers WHERE username = 'name'";

Logger.debug(“This is normal Entry from the user-----------à”);

// user input that uses SQL Injection

name_bad = "' OR 1'";

// our SQL query builder, however, not a very safe one

query_bad = "SELECT * FROM customers WHERE username = '$name_bad'";

// display what the new query will look like, with injection

Logger.debug(“This is bad input from user trying to inject SQL Vulnerability-----à”);

3. Query Formation for both Inputs.

Normal Query: SELECT * FROM customers WHERE username = ‘Ravi’
Injection Query: SELECT * FROM customers WHERE username = '' OR 1''

The normal query is no problem, as our SQL statement will just select everything from customers that has a username equal to Ravi.

However, the injection attack has actually made our query behave differently than we intended. By using a single quote (') they have ended the string part of our SQL query

  • username = ' '

and then added on to our WHERE statement with an OR clause of 1 (always true).

  • username = ' ' OR 1

This OR clause of 1 will always be true and so every single entry in the "customers" table would be selected by this statement

Although the above example displayed a situation where an attacker could possibly get access to a lot of information they shouldn't have, the attacks can be a lot worse. For example an attacker could empty out a table by executing a DELETE statement.

name_evil = "'; DELETE FROM customers WHERE 1 or username = '"; 
 
// our MySQL query builder really should check for injection
query_evil = "SELECT * FROM customers WHERE username = 'name_evil'";
 
// the new evil injection query would include a DELETE statement
Logger.debug(“This will delete everything from the database table customers------à”);

Display:

SELECT * FROM customers WHERE username = ' '; DELETE FROM customers WHERE 1 or username = ' '

If you were run this query,then the injected DELETE statement would completely empty your "customers" table. Now that you know this is a problem, how can you prevent it?

4. Dynamic Queries via String Concatenation

The important thing to remember is to never construct SQL statements using string concatenation of unchecked input values. Creating of dynamic queries via the java.sql.Statement class leads to SQL Injection.

§ SQL Injection Prevention

All queries should be parametrized.

All dynamic data should be explicitly bound to parametrized queries.

String concatenation should never be used to create dynamic SQL.