Monday, December 24, 2012

Using Regular Expressions with Javascript

Regular expressions are very powerful when you need to search or replace a certain pattern in a String.
In javascript there are two ways to create a RegExp object.

1. Using RegExp constructor
var pattern = new RegExp(expression);
or
var pattern = new RegExp(expression, modifiers);

Example
var pattern = new RegExp("[a-z]+");//case insensitive search - No modifiers
var pattern = new RegExp("[a-z]+", "i");//case sensitive search - With modifier

2. More simple way
var pattern = /expression/modifiers;

Example
var pattern = /[a-z]+/;//case insensitive search - No modifiers
var pattern = /[a-z]+/i;//case sensitive search - With modifiers

✔  Using RegExp constructor or literal regular expression will give you the same result. But the advantage of using the constructor is you can pass a varible as the argument of the constructor. So you can change the RegExp at runtime.

var exp = "[a-z]+";
var pattern = new RegExp(exp);

✔  When it comes to performance the use of literal regular expression is little bit faster than the
use of RegExp constructor.

Followings are the methods that you can use with RegExp.

1. RegExp.test("text")
The RegExp.test() method searches for a given pattern and returns true if a match found and else false.

Example
var matched = new RegExp("[a-z]+").test("abcDefg"); //true
or
var matched = /[a-z]+/.test("abcDefg"); //true

2. "text".match(pattern)
Without the modifier "g" this method returns the first match.
var result = "abcDefg".match(new RegExp("[a-z]+"));  //abc
or
var result = "abcDefg".match(/[a-z]+/);  //abc

You may have noticed that the above method gives you only one result("abc") although there are
two matches("abc" and "efg").
In order to find all matches you should use the "group" modifier "g".

var result = "abcDefg".match(new RegExp("[a-z]+", "g"));//[abc, efg]
or
var result = "abcDefg".match(/[a-z]+/g);  //[abc, efg]

You can search for groups like this
var arr = "abcDDDefg".match(/[a-z](D+)/); //[cDDD,DDD] 
alert(arr[0]); //whole match - cDDD 
alert(arr[1]); //First group - DDD


3. "text".search(pattern)
This method returns the index of the first letter of the match and -1 if not found.
Example
var result = "123abcDe".search(/abc/); //3


4. "text".replace(pattern, "new text")
Find and replace the occurrences and returns the modified string.
Example
var result = "abcDefg".replace(/[a-z]/, "x"); //xbcDefg
If you want to replace all the matches use modifier "g"
var result = "abcDefg".replace(/[a-z]/g, "x"); //xxxDxxx


5. "text".split(pattern)
Split the given text at the places where the pattern matches and return an array which contains the pieces of the text.
Example
var arr = "regular expressions are smart".split(/\s/);//[regular,expressions,are,smart]


6. RegExp.exec("text")
The exec() method is little bit complicated than the others. That is why I am discussing it here after
the others.
If a match found, this method returns an array which has the matched text as the first item. The other elements of the array contains one item for each capturing group that matched. If no matches found it returns null.
Not only that, the exec() method updates the properties of the regular expression object when it is called.
Yes, I know this is little bit ambiguous. You will understand this properly after looking at following examples.

Example
var pattern = /a(b+)(c)/i;
var text = "aabBBcdeabcde";
var result1 = pattern.exec(text);
var result2 = pattern.exec(text);

alert(result1);//abBBc,bBB,c
alert(result2);//abBBc,bBB,c

Here I have called the exec() method twice on the same RegExp object. Both have given the same result.
Observe the array it has returned.

First element  : This is the first whole match it found.
Second element : This is the first match it found for the group "(b+)"
Third element  : This is the first match it found for the group "(c)"

Obviously there are more matches and they have been ignored.

In order to retrive the ignored matches, I add the modifier "g" to the RegExp.

var pattern = /a(b+)(c)/ig;
var text = "aabBBcdeabcde";
var result1 = pattern.exec(text);
var result2 = pattern.exec(text);

alert(result1);//abBBc,bBB,c
alert(result2);//abc,b,c

See the results. Now result1 and result2 are not the same. result1 has not changed. But result2 has
given a different result.
The elements of the array "result2" can be described as below.

First element  : This is the second whole match found.
Second element : This is the second match found for the group "(b+)"
Third element  : This is the second match found for the group "(c)"

Now you can understand something important about exec() method. When you call the same method twise,
it has given you two different results. When you call it first time it returns the first matches and at
your second call it returns second matches.
Yes, really...!!! The exec() method with the modifier "g" is ideal for iterations.

var pattern = /a(b+)(c)/ig;
var text = "aabBBcdeabcde";
while(result = pattern.exec(text)) {
   alert(result);
}

Those are the methods that you meet when working with regular expressions in javascript.

Another common requirement you meet when working with Strings and Regular expressions is to replace the matched groups with different texts.

For an example lets assume that you have the following text which contains the name and the age of
the student combined.

var text = "Tom15";
Assume you want to display this information like this.
    "The age of Tom is 15."

This is simple with regular expressions.

var text = "Tom15";
var pattern = /([a-z]+)(\d+)/ig;
var sentence = "The age of $1 is $2.";
var result = text.replace(pattern, sentence);
alert(result);//The age of Tom is 15.

Yes, it is such simple.
Note that $1 and $2 represents the group1 and group2 respectively.

Saturday, December 1, 2012

How to use rich:beanValidator together with Hibernate annotations to validate input components

<rich:beanValidator/> component from Richfaces is very useful because it lets us validate input components by using Hibernate annotations. This highly reduces our need of writing validator classes.

This tutorial will show you how to use this component with @NotNull annotation to avoid NULL inputs and to display a custom message.

Create a JSF managed bean or a SEAM component as below.
public class MyBean {
  Integer number;
  
  @NotNull(message = "Please enter a value")
  public Integer getNumber() {
    return number;
  }

  public void setNumber(Integer number) {
    this.number = number;
  }
}

You need to add this import.
import org.hibernate.validator.NotNull;

This is your xhtml page.
<h:form>
  <h:inputText value="#{myBean.number}" id="txtNumber">
    <rich:beanValidator/>
  </h:inputText>
  <rich:message for="txtNumber"/>
  <a4j:commandButton value="Submit"/>
</h:form>

In this page we have a <h:inputText>  component. inside it we have a <rich:beanValidator/> component. What that component does is when the user enters a value and click the button that value is validated according to the hibernate annotations in the bean class. In this example since we have used the @NotNull annotation, the value is checked for null. If the value is null then our message "Please enter a value" is displayed in the <rich:message> component.

Similarly toy can use <rich:beanValidator/> component with other Hibernate validator annotations.

✔  You can find a list of validator annotations here

    If your page contains lot of input components you would have to put <rich:beanValidator/>s inside each of them. But it could be painful. So Richfaces introduces another component for this. It is <rich:graphValidator/> component. Instead of using <rich:beanValidator/>s inside each element, you can get the same result by wrapping all the input elements with only one <rich:graphValidator/> as below.


<h:form>
  
  <rich:graphValidator>
    <h:inputText value="#{myBean.number}" id="num" />
    <rich:message for="num" /><br />

    <rich:calendar value="#{myBean.date}" id="dte" />
    <rich:message for="dte" /><br/>
     </rich:graphValidator>

  <a4j:commandButton value="Save" />
</h:form>

Internationalize your seam application

► What is Internationalization?
  In computing, Internationalization (or i18n) can be described as "making your application to be easily adapted to more than one locale".

How to implement Internationalization in your SEAM project 
   This is not very much difficult. This tutorial will guide you through the steps.

If you open the faces-config.xml file in your WEB-INF folder you will see there are several locales already defined in it as below.
<application>
........
    <locale-config>
      <default-locale>en</default-locale>
      <supported-locale>bg</supported-locale>
      <supported-locale>de</supported-locale>
      <supported-locale>en</supported-locale>
      <supported-locale>fr</supported-locale>
      <supported-locale>tr</supported-locale>
    </locale-config>
</application>

You can add or remove <supported-locale> tags as necessary.

    Now open the resource directory of your web project and you will see the file messages_en.properties. Note the name of the file. Similarly you can create multiple files by naming like messages_<locale>.properties.
These files store texts in various languages, so that when you change the locale, the text is displayed in relevant language.
In this example we are going to show the welcome message in japanese when the user select the Japanese locale.

Let's start...
First add a <supported-locale> tag to the faces-config.xml file which includes japanese locale.
The locale code for Japanese is "ja".  So add
<supported-locale>ja</supported-locale>

Then create the file messages_ja.properties in your resource directory.
Add this line to messages_en.properties file.
welcome_msg=Welcome

Add this line to messages_ja.properties file.
welcome_msg=歓迎


Now what we want is to display the welcome message in English if the locale is en and to display the welcome message in Japanese if the locale is ja.

We are going to use the built-in seam component localeSelector.
Add this code in to your page.
<h:form>
  <h:selectOneMenu value="#{localeSelector.localeString}">
    <f:selectItems value="#{localeSelector.supportedLocales}"/>
    <a4j:support event="onchange" reRender="txtMsg"/>
  </h:selectOneMenu>
  <h:outputText id="txtMsg" value="#{messages.welcome_msg}!"/>
</h:form>

I think it is not necessary to explain what above code does.
Yes, when you select a locale from the combo box it displays the welcome message from the selected language.
Note: You can use #{messages['helloWorld']} instead of #{messages.welcome_msg}. Both give the same result.

See the result...
Save and deploy your application. Open the browser, type the url and go to the page.
Open the combo box and you will see something like this.










Now select the Japanese locale and it should display the message in Japanese language.

Problem....?
Unfortunately you may not get the expected result. You may see something weird like this.




Don't worry. The reason is this.
In .properties  files ISO 8859-1 character encoding is used to encode the input/output stream. Characters which can't be directly represented in this encoding have to be written using Unicode escapes.
So edit your messages_ja.properties file as below.
welcome_msg=\u6B53\u8FCE

Wow... Now you get the desired result.




Note: There are lot of online Unicode escape applications.This is one

Wednesday, November 28, 2012

Handling styles and style classes using javascript - Quick guide

In this short post I am going to show you how handle styles and style classes using javascript. Having a good understanding on this is vital for any developer who works on web applications.

Ok, first assume that you have following CSS classes and a DIV as below.
<style>
 .oldClass{
    background-color:yellow;
    border:solid;
 }
 .newClass {
    background-color:green;
 }
</style>

<div id="myDiv" class="oldClass">
Content here...
</div>

As you already know you can apply a style to the div as below. (Here I am applying a background color to the DIV)

document.getElementById("myDiv").style.backgroundColor = 'red';

You know that the css property for background color is background-color. But in above javascript it is used as backgroundColor. Similarly any css property which contains hyphens are written in camel case when using with javascript as above.

Following script adds a css class to the div.
document.getElementById("myDiv").className = "newClass";

Note that if your element already has one or more css classes defined, all of them are removed when new class is applied.
Following also do the same thing, but doesn't work in IE.
document.getElementById("myDiv").setAttribute("class", 'newClass');

Below one works in IE only and also do the same thing.
document.getElementById("myDiv").setAttribute("className", 'newClass'); 


Sometimes you may need to add another class to the element without replacing the existing classes. This is how to do that.
Here both classes are applied to the DIV.
Note the space before the class name. It is required.
document.getElementById("myDiv").className += " newClass";
Here both classes are applied to the DIV.

Now assume that your div already has more than one classes applied to it like this.
<div id="myDiv" class="oldClass1 oldClass2">
    Content here...
</div>
Now think that you want to remove only the class oldClass2 .

You can simply do it as below.
document.getElementById('myDiv').className =
    (document.getElementById('myDiv').className).replace('oldClass2', '');

Sunday, November 25, 2012

Hibernate InvalidStateException - How to identify invalid fields

    If you are using Hibernate, you should be familiar with the InvalidStateException which is thrown when you are going to persist data to a table with invalid values. Simply by looking at the stack trace it is impossible to find the table columns or Entity fields for which the validations are failed.
    But actually it is not very difficult to find those fields. First you need to catch the InvalidStateException by using a try-catch block. The InvalidStateException class has a method getInvalidValues() which returns an array of InvalidValue s. In this InvalidValue class there are several methods to find the information you need. So by Iterating through this array you can get the info you need.
try {
  //Persistence logic here...
} catch (InvalidStateException e) {
  for(InvalidValue invalidValue : e.getInvalidValues()) {
    System.out.println(invalidValue.getPropertyName());//Property on which validations
                                                       are failed
    System.out.println(invalidValue.getValue());//invalid value
    System.out.println(invalidValue.getMessage());//message for invalid value
    System.out.println(invalidValue.getBeanClass());//Entity bean which belongs the
                                                    property
  }
}

Sunday, October 28, 2012

How to convert a JSON object array in to a javascript object array

Lets assume that this as our JSON array
var jsonEmployeeArray = [
    {"firstname":"Tom", "lastname":"Hunter", "age":"25"}, 
    {"firstname":"Edward", "lastname":"Watson", "age":"30"}, 
    {"firstname":"William", "lastname":"Martin", "age":"45"}
  ];

Now lets create our javascript object so that it has the same properties

function EmployeeObject(firstname, lastname, age) {
  this.firstname = firstname;
  this.lastname = lastname;
  this.age = age;
}

Following is our function which convert the JSON array in to the EmployeeObject array

function convert(jsonArray) {
  var jsEmployeeArray = new Array();//Define our javascript array like this
  for(var i = 0; i < jsonArray.length; i++) {
    var employee = jsonArray[i];//get i th element
    //Create jsObject of type EmployeeObject as below
    var jsObj = 
      new EmployeeObject(employee.firstname, employee.lastname, employee.age);
    jsEmployeeArray[i] = jsObj;//Add created javascript object in to javascript array
  }
  return jsEmployeeArray;
}

That is all. Now call the above 'convert' function as below and it will return you a javascript array.
convert(jsonEmployeeArray);

Wednesday, October 24, 2012

Highlight certain dates in <rich:calendar> component

In this lesson I am going to show you how to highlight certain dates in <rich:calendar> component.
First you should write two classes by implementing 'CalendarDataModel' and 'CalendarDataModelItem' interfaces.
Here I create 'CalendarDataModelImpl' by implementing 'CalendarDataModel' interface and 'CalendarDataModelItemImpl' class by implementing 'CalendarDataModelItem' interface.

My CalendarDataModelImpl class is like this.

import java.util.Calendar;
import java.util.Date;

import javax.faces.bean.ManagedBean;

import org.domain.cpms.entity.AlertTxn;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.framework.EntityQuery;
import org.richfaces.model.CalendarDataModel;
import org.richfaces.model.CalendarDataModelItem;

@Name("calendarDataModelImpl")
public class CalendarDataModelImpl implements CalendarDataModel {
  public CalendarDataModelItem[] getData(Date[] dateArray) {
    CalendarDataModelItem[] modelItems = new 
              CalendarDataModelItemImpl[dateArray.length];
    for (int i = 0; i < dateArray.length; i++) {
      CalendarDataModelItemImpl modelItem = new CalendarDataModelItemImpl();
      modelItem.setEnabled(true);
      for(Date d : getDatesToBeHighlighted()) {
        if(getDatePortion(d).compareTo(  
                       getDatePortion(dateArray[i])) == 0) {
          modelItem.setStyleClass("green");
        }
      }
      modelItems[i] = modelItem;
    }
    return modelItems;
  }

  public Object getToolTip(Date arg0) {
  return null;
  }
 
//This method skips the time part and retuns the date part only
  private Date getDatePortion(Date date) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    return calendar.getTime();
  }

//This method returns the dates which should be highlighted
  private Date[] getDatesToBeHighlighted() {
    Date[] dates;
    .....your logic to find dates which should be highlighted...
    return dates;
  }
}

Following method is the most important method in 'CalendarDataModelImpl' class.
public CalendarDataModelItem[] getData(Date[] dateArray) {}

In my xhtml page I add a calendar component as below.
<h:form>
  <rich:calendar popup="false" mode="ajax" dataModel="#{calendarDataModelImpl}"/>
</h:form>

Since we have defined the 'dataModel' attribute in the calendar, when our calendar component is rendered, it passes an array of dates to 'getData' method in our 'CalendarDataModelImpl' class.
So now we iterate through that array and set our own css class name for each date that we need to be highlighted.

public CalendarDataModelItem[] getData(Date[] dateArray) {
    CalendarDataModelItem[] modelItems = new
                    CalendarDataModelItemImpl[dateArray.length];
      for (int i = 0; i < dateArray.length; i++) {
    CalendarDataModelItemImpl modelItem = new
                            CalendarDataModelItemImpl();
    modelItem.setEnabled(true);//Enable the date
  for(Date d : getDatesToBeHighlighted()) {//your method which returns an array 
                                                 //of dates which should be highlighted
          if(getDatePortion(d).compareTo(
                getDatePortion(dateArray[i])) == 0) {//comparing our date with dates in                                                      //dateArray
              modelItem.setStyleClass("green");                                 
  }
  }
  modelItems[i] = modelItem;
    }
    return modelItems;
  }

My CalendarDataModelItemImpl class is as below. It contains only several getter and setter methods.

import org.richfaces.model.CalendarDataModelItem;

public class CalendarDataModelItemImpl implements CalendarDataModelItem {
    private boolean enabled;
    private String styleClass;

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public void setStyleClass(String styleClass) {
        this.styleClass = styleClass;
    }

    public boolean isEnabled() {
        return enabled;
    }

    public String getStyleClass() {
        return styleClass;
    }

    public Object getData() {
        return null;
    }

    public boolean hasToolTip() {
        return false;
    }

    public Object getToolTip() {
        return null;
    }

    public int getDay() {
        return 0;
    }
}

That is it.

Thursday, July 19, 2012

Compare two dates in two <rich:calendar> components

In this lesson Im going to show you how to compare the dates of two &lt;rich:calendar> components in a JSF page.

For an example think that you are creating a JSF page to enter employee details.
In that page you have two calendar components. One is to enter the join date and the other one is to enter the retired date of the employee.
So obviously join date should be earlier than the retired date. How do you validate whether join date is earlier than retired date and show a rich:message if validation failed?

1) Method 1 (For JSF users)
If you are not using JBoss SEAM, this method is for you. (Its obvious that SEAM users also can use this method.)

First, you have to create a validator class as below.


package inova;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;


public class DateComparator implements Validator {
public void validate(FacesContext context, UIComponent component, Object date1) throws ValidatorException {
Date joinedDate = (Date) date1;
UIInput retiredDateComponent = 
           (UIInput) component.getAttributes().get("retiredDateComponent");

String dateString = (String) retiredDateComponent.getSubmittedValue();
System.out.println("dateString>" + dateString);
        String pattern = "yyyy/MM/dd hh:mm";
        SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
        Date retiredDate;
        try {
        retiredDate = dateFormat.parse(dateString);        
        } catch (ParseException e) {
            e.printStackTrace();
            return;
        }
        System.out.println("retiredDate> " + retiredDate);
if (joinedDate == null || retiredDate == null) {
            return;
}
        if (joinedDate.compareTo(retiredDate) > 0) {
        retiredDateComponent.setValid(false);
            throw new ValidatorException(new FacesMessage("Retired date should be 
                greator than joined Date"));
        }
    }
}
Now register your validator class in your 'faces-config.xml' file. To do it add the following lines directly within the <faces-config> tags.


<validator-id>dateComparator</validator-id>
  <validator-class>inova.DateComparator</validator-class>
</validator>
Note that 'dateComparator' is the name by using which you are going to access the validator in your page. You can give any name for this.

If you are using a date pattern in your second calendar(end date) component, you have to use the same date pattern in your validator class.
Your page will be as below.


<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:rich="http://richfaces.org/rich"
      xmlns:a4j="http://richfaces.org/a4j"
      xmlns:c="http://java.sun.com/jstl/core"
      xmlns:f="http://java.sun.com/jsf/core"> 


<head></head> 
<body>
  <h:form>
    Start date : 
    <rich:calendar id="cal_1">
      <f:validator validatorId="dateComparator"/>
      <f:attribute name="endDateComponent" value="#{endDate}"/>
    </rich:calendar>
    <br/>
    End date : <rich:calendar binding="#{endDate}" datePattern="yyyy/MM/dd hh:mm"/> 
    <br/>
    <rich:message for="cal_1" style="color:red;"/>
    <br/>
    <a4j:commandButton value="Save"/>
  </h:form>
</body> 
</html>

That is all. I think its clear for you what we have done.
♫ In our xhtml page we bind the 'end date calendar' component to the variable named as 'endDate' by using the 'binding' attribute of it.
♫ Then in our 'start date calendar' component, we use it as an attribute.
♫ In our validator class, we get that attribute by using the 'component.getAttributes().get(....)' method. Then we get the end date.
♫ If two dates are valid according to our criteria, we have nothing to do and if dates are invalid we throws a 'ValidatorException' with our own message.

2) Method 2(For seam users only)
This way is easier than the above method.
 The validator class is almost the same as above except three annotations are introduced before the class name as below.


@Name("dateComparator")
@org.jboss.seam.annotations.faces.Validator
@BypassInterceptors
public class DateComparator implements Validator {
..........
}
✱  Nothing to be put in faces-config.xml. It means you don't need to register your validator class in  faces-config.xml as in method1.

Enjoy......

Monday, July 9, 2012

Dynamically create tabs in <rich:tabPanel> component

In JSF you may have used <a4j:repeat> tag to repeat UI components. For an example you can use <a4j:repeat> tag as below to dynamically create several check boxes.

  <a4j:repeat value="#{userRoleList.resultList}" var="userRole">
    <h:selectBooleanCheckbox/>Click me<br/>
  </a4j:repeat>

The result will be as below.







But this doesn't work with <rich:tabPanel> and <rich:tab> components.
Is there any solution for this?
Yes, your old friend <c:forEach> component is still ready to help you.
Really you can use <c:forEach> of JSTL in your JSF page.
Following is an example. Required parts are colored.

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:rich="http://richfaces.org/rich"
      xmlns:c="http://java.sun.com/jstl/core"


<head></head> 
<body>
  <rich:tabPanel switchType="client">
    <c:forEach items="#{userRoleList.resultList}" var="userRole">
      <rich:tab label="Tab#{userRoleList.resultList.indexOf(userRole) + 1}">
        I am tab no. #{userRoleList.resultList.indexOf(userRole) + 1}
      </rich:tab>
    </c:forEach>
  </rich:tabPanel>
</body> 
</html>

Final result will be as below.

Tuesday, July 3, 2012

How to use <rich:listShuttle> component














In 'ListShuttle' component you have two lists.
The left hand side list is the Source list.Right hand side list is the Target list. When moving an item between two lists, it is passed as a String. So you have to write a converter class to convert this String again to the object. So in order to do this correctly you may need to override the 'toString' method of the class
which you are using as the list item.

In this example I am using following 'UserData' calss to represent an item in the list. So my source list and
target lists has the type of 'UserData'.
Note that 'toString' method in 'UserData' has been overridden.

public class UserData {
String userName;
Integer userId;
public String getUserName() {
  return userName;
  }
public void setUserName(String userName) {
  this.userName = userName;
  }
public Integer getUserId() {
  return userId;
  }
public void setUserId(Integer userId) {
  this.userId = userId;
  }
  @Override
  public String toString() {
    return this.userId + "," + this.userName;
  }
}


My converter class is as below. It can convert a 'UserData' object to a String and, a String representation of 'UserData' object back to a 'UserData' object.
Following three annotations are must
@Name("userDataConverter") - This indicates the converter Id()
@Converter - This registers this class as a converter
@BypassInterceptors - Disabling interceptors.


import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.faces.Converter;
import org.jboss.seam.annotations.intercept.BypassInterceptors;


@Name("userDataConverter")
@Converter
@BypassInterceptors
public class UserDataConverter implements javax.faces.convert.Converter {


  public Object getAsObject(FacesContext fContext, UIComponent uiComp, String value) {
UserData userData = new UserData();
String[] parts = value.split(",");
userData.setUserId(Integer.valueOf(parts[0]));
userData.setUserName(parts[1]);
return userData;
  }


  public String getAsString(FacesContext fContext, UIComponent uiComp, Object obj) {
UserData userData = (UserData) obj;
return userData.toString();
  }
}

My seam class which is bound to the page is as below.

import java.util.ArrayList;
import java.util.List;
import org.jboss.seam.annotations.Name;


@Name("myBean")
public class MyBean {
List<UserData> sourceData;
List<UserData> targetData = new ArrayList<UserData>();

public MyBean() {
sourceData = new ArrayList<UserData>();
UserData u = new UserData();
u.setUserId(100);
u.setUserName("John");
sourceData.add(u);
UserData u2 = new UserData();
u2.setUserId(101);
u2.setUserName("Kate");
sourceData.add(u2);
}

public List<UserData> getSourceData() {
return sourceData;
}

public List<UserData> getTargetData() {
return targetData;
}
}

Finally the ListShuttle component in my xhtml page is this.

    <rich:listShuttle sourceCaptionLabel="All users" targetCaptionLabel="Selected users"  orderControlsVisible="true"  sourceValue="#{myBean.sourceData}" var="userData" 
   targetValue="#{myBean.targetData}" converter="userDataConverter">
      <rich:column width="60px">
        <f:facet name="header">
          <h:outputText value="Username"/>
        </f:facet>
        <h:outputText style="cursor:pointer;" value="#{userData.userName}" />
      </rich:column>
      <rich:column width="60px">
        <f:facet name="header">
          <h:outputText value="Id" />
        </f:facet>
        <h:outputText style="cursor:pointer;" value="#{userData.userId}" />
      </rich:column>
    </rich:listShuttle>

Customize JSF selectOneRadio component

The general use of  '<h:selectOneRadio>' component is as below

    <h:selectOneRadio>
      <f:selectItem itemLabel=": Cheque" itemValue="1" />
      <f:selectItem itemLabel=":Cash" itemValue="2" />
    </h:selectOneRadio>

The appearance of finally rendered component is as below. The Select Items are laid horizontally by default.





If you want to arrange them vertically then change the 'layout' attribute as below.

    <h:selectOneRadio layout="pageDirection">
      <f:selectItem itemLabel="Cheque" itemValue="1" />
      <f:selectItem itemLabel="Cash" itemValue="2" />
    </h:selectOneRadio>






However if you want to place the labels of 'Select Items' components before the radio buttons you have to use css.


    <style>
      .myRad td {
          text-align:right;
      }
      .myRad td input {
          float:right;
          width:35px;
      }
    </style>


    <h:selectOneRadio layout="pageDirection" styleClass="myRad">
      <f:selectItem itemLabel="Cheque :" itemValue="1" />
      <f:selectItem itemLabel="Cash :" itemValue="2" />
    </h:selectOneRadio>

Final result will be as below.



Monday, February 27, 2012

EJBQL Delete Query Example

If you have worked with SEAM you may have used the method "entityManager.remove()" which is used to delete an entry from database. This method accepts one parameter, which is an entity.
(However the entity should be a managed one. Otherwise it throws an exception saying that you are trying to remove a detached object.)
You can use an EJBQL query to delete a record from database directly. In this case no managed entity is required. Following is an example query, which deletes one record from "Client" table.
It deletes the client whose clientId is 10.

DELETE FROM Client client where client.clientId = 10

Now I am going to use SEAM managed EntityManager to create a Query object as below and execute the query by calling it's "executeUpdate()" method.

Injecting EntityManager.
@In
EntityManager entityManager

Creating and executing query
Query q = entityManager.createQuery("DELETE FROM Client client where client.clientId                                       = 10");
q.executeUpdate();//delete row