Friday, September 22, 2006

Inversion of Control

IoC means you have registered some part of your code with the framework, and the framework will
call this code when the client requests it. This is also referred to as the Hollywood principle. (“Don’t call us. We’ll call you.”)


Inversion of Control, also known as IOC, is an important object-oriented programming principle that can be used to reduce coupling inherent in computer programs.

IOC is also known as the Dependency Inversion Principle [#wp-endnote_Martin 2002_none (Martin 2002:127)]. The Dependency injection [#wp-endnote_Fowler 2004_none (Fowler 2004)] techinque is used in almost every framework and it's a simple example of the IoC principle applied. It has been applied by programmers using object-oriented programming languages such as SmallTalk, [[C++]], Java or any .NET language.

Technical description

Terms and definitions

Class X depends on class Y if any of the following applies:

* X has a Y and calls it
* X is a Y
* X depends on some class Z that depends on Y (transitivity)

X depends on Y does not imply Y depends on X. If both happen to be true this is called a cyclic dependency: X can't then be used without Y, and vice versa. The existence of a large number of cyclic dependencies in an object oriented program might be an indicator for suboptimal program design.

If an object x (of class X) calls methods of an object y (of class Y), then class X depends on Y. The dependency can now be inverted by introducing a third class, namely an interface class I that must contain all methods that x might call on y. Furthermore, Y must be changed such that it implements interface I. X and Y are now both dependent on interface I and class X no longer depends on class Y, presuming that x does not instantiate Y.

This elimination of the dependency of class X on Y by introducing an interface I is said to be an inversion of control (or a dependency inversion).

It must be noted that Y might depend on other classes. Before the transformation had been applied, X depended on Y and thus X depended indirectly on all classes that Y depends on. By applying Inversion of control, all those indirect dependencies have been completely broken up too, not only the dependency from X on Y. The newly introduced interface I depends on nothing.

Friday, August 04, 2006

JSTL function tag ${fn:length....}

c:set var="tempStr" value="I love Java an www.java2s.com"

The length of the test String: ${fn:length(tempStr)}


Does the test String contain "test"? ${fn:contains(tempStr,"test")}


Putting the String into upper case using fn:toUpperCase(): ${fn:toUpperCase(tempStr)}


Splitting the String into a String array using fn:split(), and returning the array length: ${fn:length(fn:split(tempStr," "))}

how to do i find out the length of this arraylist using JSTL tags...





or if

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
${fn:length(theList)}

how to do i find out the length of this arraylist
using JSTL tags...

/That depends on what version of what server (and JSTL) you are using. If you are using JSTL 1.1 (JSP 2.0 server like Tomcat 5.0) then you can use:



If you are Using JSTL 1.0 and a JSP 1.2 server (like Tomcat 4), then you will either have to use a scriptlet, or run a c:forEach:

//scriptlet
<%
List array = (List)request.getAttribute("array");
Integer count = new Integer(array.size());
pageContext.setAttribute("count", count);
%>
//c:forEach

Wednesday, August 02, 2006

sort a table comparator

http://java.sun.com/docs/books/tutorial/uiswing/components/example-1dot4/TableSorter.java

http://java.sun.com/docs/books/tutorial/uiswing/components/example-1dot4/TableSorterDemo.java

BeanComparator

import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.Date;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.collections.comparators.ComparableComparator;
import org.apache.commons.collections.comparators.ReverseComparator;


public class BeanComparator implements Comparator {

private String attribute;
private String sortBy;
private String javaType;

private Comparator comp = new ComparableComparator();

public BeanComparator(String attrib, String sortBy, String javaType) {
this.attribute = attrib;
this.sortBy = sortBy;
this.javaType = javaType;

if(this.sortBy!= null && !this.sortBy.equals("") && this.sortBy.equals("descending") )
comp = new ReverseComparator();
else if (this.sortBy!= null && !this.sortBy.equals("") && this.sortBy.equals("ascending") )
comp = new ComparableComparator();

}

public int compare(Object o1, Object o2) {
if(o1 == null) {
return 1;
} else
if(o2 == null) {
return -1;
}

try {
Object ret1 = PropertyUtils.getProperty(o1, this.attribute);
Object ret2 = PropertyUtils.getProperty(o2, this.attribute);
return this.comp.compare(ret1, ret2);

} catch(Exception e) {
return 0;
}
}

}

Reverse Comparator

+ static class ReverseComparator implements Comparator, Serializable
+ {
+ public int compare(Object a, Object b)
+ {
+ return -((Comparable) a).compareTo(b);
+ }
+ }
+
+ static ReverseComparator rcInstance = new ReverseComparator();
+
/**
* Get a comparator that implements the reverse of natural ordering. This is
* intended to make it easy to sort into reverse order, by simply passing
* Collections.reverseOrder() to the sort method. The return value of this
* method is Serializable.
*/
- // The return value isn't Serializable, because the spec is broken.
public static Comparator reverseOrder()
{
- return new Comparator()
- {
- public int compare(Object a, Object b)
- {
- return -((Comparable) a).compareTo(b);
- }
- };
+ return rcInstance;
}

Date Comparator

// Create Date Comparator for ChangeLogEntry's
Comparator comparator = new Comparator() {
public int compare(Object object1, Object object2) {
ChangeLogEntry entry1 = (ChangeLogEntry)object1;
ChangeLogEntry entry2 = (ChangeLogEntry)object2;

// Compare Dates
int compare = entry1.getDate().compareTo(entry2.getDate());

// Invert so that sort is descending
return (compare * -1);
}
};

// Sort the entries
Collections.sort(filteredEntries, comparator);

NumericString Java Comparator

Collection coll = getPersons(); // full of Person objects.

// Person.getName exists
Collections.sort(coll, new BeanComparator("name"));

or to improve performance:

Collections.sort(coll, BeanComparator.getInstance("name"));

This sits on top of an ObjectComparator which aims to compare any
primitive object. So it uses a UrlComparator, and a ComparableComparator.
Plan is to add more as time goes by.

Then there's a SoundexComparator, a PackageNameComparator (java package
names, ie) java.util comes before com.sun) and a ReverseComparator.

The ReverseComparator is something I love. Very tiny code, big value.

Collections.sort(coll, new
ReverseComparator(BeanComparator.getInstance("name")));

will happily sort in reverse order :) Obviously the implementation is
just:

return -1 * subComparator.compare(o1,o2);

So this reverses a list with no performance problem :) Number of times
I've seen people passing a 'reverse' flag to their comparators.

Anyway, I think this is a pretty nice system and that it might be worthy
of being a sub-package 'compare' inside Commons Collections.

Any thoughts?

Bay

package com.generationjava.compare;

import java.util.Comparator;

/**
* A Comparator which deals with alphabet characters 'naturally', but
* deals with numerics numerically. Leading 0's are ignored numerically,
* but do come into play if the number is equal. Thus aaa119yyyy comes before
* aaa0119xxxx regardless of x or y.
*
* The comparison should be very performant as it only ever deals with
* issues at a character level and never tries to consider the
* numerics as numbers.
*
* @author [EMAIL PROTECTED]
*/
public class NumericStringComparator implements Comparator {

public NumericStringComparator() {
}

public int compare(Object o1, Object o2) {
if(o1 == null) {
return 1;
} else
if(o2 == null) {
return -1;
}

String s1 = o1.toString();
String s2 = o2.toString();

// find the first digit.
int idx1 = getFirstDigitIndex(s1);
int idx2 = getFirstDigitIndex(s2);

if( ( idx1 == -1 ) ||
( idx2 == -1 ) ||
( !s1.substring(0,idx1).equals(s2.substring(0,idx2)) )
)
{
return s1.compareTo(s2);
}

// find the last digit
int edx1 = getLastDigitIndex(s1, idx1);
int edx2 = getLastDigitIndex(s2, idx2);

String sub1 = null;
String sub2 = null;

if(edx1 == -1) {
sub1 = s1.substring(idx1);
} else {
sub1 = s1.substring(idx1, edx1);
}

if(edx2 == -1) {
sub2 = s2.substring(idx2);
} else {
sub2 = s2.substring(idx2, edx2);
}

// deal with zeros at start of each number
int zero1 = countZeroes(sub1);
int zero2 = countZeroes(sub2);

sub1 = sub1.substring(zero1);
sub2 = sub2.substring(zero2);

// if equal, then recurse with the rest of the string
// need to deal with zeroes so that 00119 appears after 119
if(sub1.equals(sub2)) {
int ret = 0;
if(zero1 > zero2) {
ret = 1;
} else
if(zero1 < zero2) {
ret = -1;
}
if(edx1 != -1) {
int comp = compare(s1.substring(edx1), s2.substring(edx2));
if(comp != 0) {
ret = comp;
}
}
return ret;
} else {
// if a numerical string is smaller in length than another
// then it must be less.
if(sub1.length() != sub2.length()) {
return ( sub1.length() < sub2.length() ) ? -1 : 1;
}
}


// now we get to do the string based numerical thing :)
// going to assume that the individual character for the
// number has the right order. ie) '9' > '0'
// possibly bad in i18n.
char[] chr1 = sub1.toCharArray();
char[] chr2 = sub2.toCharArray();

int sz = chr1.length;
for(int i=0; i // this should give better speed
if(chr1[i] != chr2[i]) {
return (chr1[i] < chr2[i]) ? -1 : 1;
}
}

return 0;
}

private int getFirstDigitIndex(String str) {
return getFirstDigitIndex(str, 0);
}
private int getFirstDigitIndex(String str, int start) {
return getFirstDigitIndex(str.toCharArray(), start);
}
private int getFirstDigitIndex(char[] chrs, int start) {
int sz = chrs.length;

for(int i=start; i if(Character.isDigit(chrs[i])) {
return i;
}
}

return -1;
}

private int getLastDigitIndex(String str, int start) {
return getLastDigitIndex(str.toCharArray(), start);
}
private int getLastDigitIndex(char[] chrs, int start) {
int sz = chrs.length;

for(int i=start; i if(!Character.isDigit(chrs[i])) {
return i;
}
}

return -1;
}

public int countZeroes(String str) {
int count = 0;

// assuming str is small...
for(int i=0; i if(str.charAt(i) == '0') {
count++;
} else {
break;
}
}

return count;
}

// UNUSED
private boolean containsOnly(String str, char ch) {
return containsOnly( str.toCharArray(), ch );
}
private boolean containsOnly(char[] chrs, char ch) {
int sz = chrs.length;

for(int i=0; i if(chrs[i] != ch) {
return false;
}
}

return true;
}

}

How to Access parameteters (request.getParameter) in JSF

How to Access parameteters in JSF -- request.getParameter()...

you cannot use #{request.getParameter("c"}. Such syntax is not acceptable.

From the Specification:
param—An immutable Map of the request parameters for this request, keyed by
parameter name. Only the first value for each parameter name is included.

So, #{param} are loaded from request Parameters by definition :-)

Just for testing purpose, put somewhere on your page to see what the #{param} contains.

You cannot use the session scope bean, because its properties cannot be initialized with the objects that have the shorter scope.


EXAMPLE 1
You can access your current request's instance in backing bean like :
String paramValue = ((HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest()).getParameter("paramName");


OR
EXAMPLE 2



OR
EXAMPLE 3
The easiest way to resolve this is to use a commandLink instead of a commandButton. Within your commandLink use f:param to send the subLink1 parameter:

Then in faces.config use the managed property and the implicit JSF expression variable "param" to set the parameter in your managed bean. Something like:

Then add a setter method in your managed bean for subLink1.



Struts Nested Tags

Struts Nested Tags
Since the version 1.1 of Struts, the tag library “nested” is included in Struts. In this tutorial we want to explain what are the features of the new nested tag library and show some little examples howyou can use it.

Copied from www.laliluna.de/struts-nested-iteration-tutorial.html

The nested tag library
Nested tags make it easy to manage nested beans. For example a list like the following:
Department A
Customer A
Customer B
Customer C
Department B
Customer D


All nested tags inside a nested tag refers to the tag which surrounds them. For example your form bean holds an object department and you want the property name of the department. Normally you can use a dot notation to get the name of the department.


With a nested:nest tag you do not need the dot notation any more.


The following example shows a dot notation to output the name of a department bean:



The tags inside the nested:nest can refers directly to the properties of the department. When you have many properties this is quite an advantage. The most functionality elements of the other tag libraries are rebuild as nested tags, like
bean:write is nested:write, logic:iterate is nested:iterate etc. You will find a complete list of all supported tags by the nested tab library in the Apache Struts Nested Tag Library API.


Usage of the nested tags
Create a new struts 1.1 project to get more familiar with the nested tags.
Add a package de.laliluna.tutorial.nested to the src folder of the project.


Object class Customer
Create a new java class Customer in the package de.laliluna.tutorial.nested.object.
Add two properties, id of type int and name of type String. Provide a getter and setter method for each property. Create a constructor that allow you to set the properties on initialization.


The following source code shows the class Customer :
/**
* Object Class Customer
*/
public class Customer {
private int id;
private String name;
//constructors
public Customer(){}
public Customer(int id, String name){
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}


Object class Department
Create a second java class Departments in the same package de.laliluna.tutorial.nested.object. Add two properties, id of type int and name of type String and one property customers of type Collection, which holds a list of customers. Provide a getter and setter method for each property.
Create a constructor that allows you to set the properties on initialization.


The following source code shows the class Department :
/**
* Object Class Department
*/
public class Department {
private int id;
private String name;
//customers collection
private Collection customers;
//constructors
public Department() {}
public Department(int id, String name, Collection customers){
this.id = id;
this.name = name;
this.customers = customers;
}
public Collection getCustomers() {
return customers;
}
public void setCustomers(Collection customers) {
this.customers = customers;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}


Action form class ExampleForm
Create a java class ExampleForm in the package de.laliluna.tutorial.nested.form, which extends the class ActionForm of struts. Add a property department of type Department. Provide a getter and setter method for the property department.
Implement the reset() method of the ActionForm class and provide some dummy data.


The following source code shows the class ExampleForm:
/**
* Action Form Class ExampleForm
*/
public class ExampleForm extends ActionForm {
Department department;
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
/**
* Reset method
* @param mapping
* @param request
*/
public void reset(ActionMapping mapping,
HttpServletRequest request) {
//initial a dummy collection of customers
Collection customers = new ArrayList();
customers.add(new Customer(1, "Maria"));
customers.add(new Customer(2, "Klaus"));
customers.add(new Customer(3, "Peter"));
//initial a dummy department
department = new Department(1, "Department A", customers);
}
}


Action class ExampleAction
Create a java class ExampleAction in the package de.laliluna.tutorial.nested.action, which extends the class Action of struts. Return the forward example.


The following source code shows the class ExampleAction:
/**
* Action Class ExampleAction
*/
public class ExampleAction extends Action {
/**
* Method execute
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
*/
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) {
ExampleForm exampleForm = (ExampleForm) form;
return mapping.findForward("example");
}
}


Configure the struts-config.xml
Open the struts-config.xml and add the form bean and action mapping.


The following source code shows the content of the struts-config.xml.


type="de.laliluna.tutorial.nested.form.ExampleForm" />


attribute="exampleForm"
input="/form/example.jsp"
name="exampleForm"
path="/example"
scope="request"
type="de.laliluna.tutorial.nested.action.ExampleAction"
validate="false" >






The JSP file
Create a new JSP file example.jsp in the folder /WebRoot/form.
Add the reference to the tag library nested at the top of the file. The following source code shows the JSP file. The bold line at the top is the reference to the
nested tag library.




Inside the element you insert the following examples.
Example 1
In the first example we show the usage of dot notation to get the properties form the department


object of the form bean.



Example 2
The second example shows the usage of the nested:nest tag to use the properties inside the
nested:nest tag without dot notation. The attribute property of the nested:nest element refers to
the property department of our form bean.
The nested:text elements inside the nested:nest element refers to the properties of the surrounds
nested tag. The attribute property of the nested:text element refers to a property of the object
class Department.



Example 3
Example 3 shows the usage of an iteration inside a nested:nest tag. The nested:iteration element works like the logic:iteration element, but refers to a property of the parent nested tag.