How to create Extension Functions
JXPath is a java library for Object Graph Navigation using the XPath syntax.
This requires the libraries commons-jxpath-1.3.jar, commons-beanutils.jar and commons-logging.jar to be in classpath.
The following example shows creating and registering an extension function in JXPath.
package com.bethecoder.tutorials.jxpath.common;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Student {
private String name;
private int age;
private String hobby;
private List<String> nickNames = new ArrayList<String> () ;
public Student () {
}
public Student ( String name, int age, String hobby ) {
super () ;
this .name = name;
this .age = age;
this .hobby = hobby;
}
public Student ( String name, int age, String hobby, String [] nickNames ) {
super () ;
this .name = name;
this .age = age;
this .hobby = hobby;
this .nickNames = Arrays.asList ( nickNames ) ;
}
public String getName () {
return name;
}
public void setName ( String name ) {
this .name = name;
}
public int getAge () {
return age;
}
public void setAge ( int age ) {
this .age = age;
}
public String getHobby () {
return hobby;
}
public void setHobby ( String hobby ) {
this .hobby = hobby;
}
public List<String> getNickNames () {
return nickNames;
}
public void setNickNames ( List<String> nickNames ) {
this .nickNames = nickNames;
}
public String toString () {
return "Student[name = " + name + ", age = " + age + ", hobby = " + hobby + ", " + nickNames + "]" ;
}
}
package com.bethecoder.tutorials.jxpath.functions;
public class CaseFormatter {
public static String upper ( String str ) {
return str.toUpperCase () ;
}
public static String lower ( String str ) {
return str.toLowerCase () ;
}
}
package com.bethecoder.tutorials.jxpath;
import org.apache.commons.jxpath.ClassFunctions;
import org.apache.commons.jxpath.JXPathContext;
import com.bethecoder.tutorials.jxpath.common.Student;
import com.bethecoder.tutorials.jxpath.functions.CaseFormatter;
public class FunctionsTest {
/**
* @param args
*/
public static void main ( String [] args ) {
Student std = new Student ( "Sriram" , 2 , "Singing" ) ;
//Create JXPathContext with Student object as ROOT node
JXPathContext context = JXPathContext.newContext ( std ) ;
//Register static methods in given class as functions in the namespace "case"
context.setFunctions ( new ClassFunctions ( CaseFormatter.class, "case" )) ;
System.out.println ( context.getValue ( "case:upper('be the coder')" )) ;
System.out.println ( context.getValue ( "case:upper(/name)" )) ;
System.out.println ( context.getValue ( "case:lower('BE THE CODER')" )) ;
System.out.println ( context.getValue ( "case:lower(/name)" )) ;
}
}
It gives the following output,
BE THE CODER
SRIRAM
be the coder
sriram