Creating a Java Scalar UDF Version of the SQL substr Function

Create a Java UDF deployment where the SQL function passes multiple arguments to the Java UDF.

Prerequisites
Task
  1. Place this Java code in a file named MyJavaSubstr:
    public class MyJavaSubstr
    {
        public static String my_java_substr( String in, int start, int length )
        {
    	String rc = null;
    	
    	if ( start < 1 )
    	{
    	    start = 1;
    	}
    
    	// Convert the SQL start, length to Java start, end.
    	start --;  // Java is 0 based, but SQL is one based.
    	int endindex = start+length;
    	
    	try {
    	    if ( in != null )
    	    {
    	        rc = in.substring( start, endindex );
    	    }
    	} catch ( IndexOutOfBoundsException ex )
    	{
    	    System.out.println("ScalarTestFunctions:
                    my_java_substr("+in+","+start+","+length+") failed");
    	    System.out.println(ex);
    	}
    	return rc;
     }
  2. In Interactive SQL, connect to the iqdemo database.
  3. In Interactive SQL, install the class file onto the server:
    INSTALL JAVA NEW FROM FILE '<pathtofile>/MyJavaSubstr.class'
  4. In Interactive SQL, create the function definition:
    CREATE or REPLACE FUNCTION java_substr(IN a VARCHAR(255), IN b INT, IN c INT ) 
      RETURNS VARCHAR(255) 
      EXTERNAL NAME 
        'example.MyJavaSubstr.my_java_substr(Ljava/lang/String;II)Ljava/lang/String;' 
      LANGUAGE JAVA

    Notice the code snippet Ljava/lang/String;II indicating parameter types String, int, int.

  5. In Interactive SQL, use the Java UDF in a query against the iqdemo database:
    select GivenName, java_substr(Surname,1,1) from Customers where lcase(java_substr(Surname,1,1)) = 'a';