Inline::Java::Callback(3pm)

NAME
Inline::Java::Callback - Callback into Perl from Java.

SYNOPSIS
   use Inline Java => <<'END' ;
      import org.perl.inline.java.* ;

      class Pod_caller extends InlineJavaPerlCaller {
         public Pod_caller() throws InlineJavaException {
         }

         public String perl()
            throws InlineJavaException, InlineJavaPerlException {

            return (String)CallPerlSub("main::perl",
               new Object [] {}) ;
         }
      }
   END

   my $pc = new Pod_caller() ;
   print($pc->perl() . "\n") ; # prints perl

   sub perl {
      return "perl" ;
   }

DESCRIPTION
"Inline::Java::Callback" allows you to call Perl functions from Java. To do this you need to create an "org.perl.inline.java.InlinePerlCaller" object. Here is a example of a typical use:

   use Inline Java => <<'END' ;
      import java.util.* ;
      import org.perl.inline.java.* ;

      class Pod_regexp extends InlineJavaPerlCaller {
         public Pod_regexp() throws InlineJavaException {
         }

         public boolean match(String target, String pattern)
            throws InlineJavaException {
            try {
               String m = (String)CallPerlSub("main::regexp",
                  new Object [] {target, pattern}) ;

               if (m.equals("1")){
                  return true ;
               }
            }
            catch (InlineJavaPerlException pe){
               // $@ is in pe.GetObject()
            }

            return false ;
         }
      }
   END

   my $re = new Pod_regexp() ;
   my $match = $re->match("Inline::Java", "^Inline") ;
   print($match . "\n") ; # prints 1

   sub regexp {
      my $target = shift ;
      my $pattern = shift ;

      return ($target =~ /$pattern/) ;
   }

CALLBACK API
Here are the various methods that one can use to call into Perl:

public Object CallPerlSub(String sub, Object args[], Class cast) throws InlineJavaException, InlineJavaPerlException
    Calls the specified subroutine with the supplied arguments and tries to create an object of type 'cast' with the result.

       /* Example */
       Integer sum = (Integer)CallPerlSub("main::add", new Object [] {Integer.valueOf(5), Integer.valueOf(3)}, Integer.class) ;

public Object CallPerlStaticMethod(String pkg, String method, Object args[], Class cast) throws InlineJavaException, InlineJavaPerlException
    Calls the specified static package method (using the $pkg->$method() notation) with the supplied arguments and tries to create an object of type 'cast' with the result.

       /* Example */
       Integer sum = (Integer)CallPerlStaticMethod("main", "add", new Object [] {Integer.valueOf(5), Integer.valueOf(3)}, Integer.class) ;

public Object eval(String code, Class cast) throws InlineJavaPerlException, InlineJavaException
    Evaluates the given Perl code and tries to create an object of type 'cast' with the result.

       /* Example */
       Integer sum = (Integer)eval("5 + 3", Integer.class) ;

public Object require(String module_or_file) throws InlineJavaPerlException, InlineJavaException
    Requires the specified module/file by using a heuristic (currently, checks whether or not the file exists) and calling Perl's "require" function using the appropriate construct.

       /* Example */
       require("Someting")

public Object require_file(String file) throws InlineJavaPerlException, InlineJavaException
    Requires the specified file.

       /* Example */
       require_file("./my_stuff.pl") ;

public Object require_module(String module) throws InlineJavaPerlException, InlineJavaException
    Requires the specified module.

       /* Example */
       require_module("Data::Dumper") ;

Note: For all CallPerl* and eval methods, the 'cast' parameter is optional and defaults to 'String.class'.

These methods can throw 2 types of exceptions: "InlineJavaException" and "InlineJavaPerlException" (both of these belong to the "org.perl.inline.java" package). The former designates an internal "Inline::Java" error and the latter indicates that the Perl callback threw an exception (die() or croak()). The value of $@ (this can be a scalar or any valid "Inline::Java" object) can be retrieved using the GetObject() method of the "InlineJavaPerlException" object (if you are certain that $@ was a Perl scalar, you can use the GetString() method).

CALLBACK CONTEXT
By default, callback are executed in scalar context. However if you want to call certain functions in list context, you must insert "@" in front of the function name. The result will then be passed on to Java as an Array:

   use Inline Java => <<'END' ;
      import org.perl.inline.java.* ;

      class Pod_Context {
         static private String dummy[] = {} ;

         static public String [] get_list()
            throws InlineJavaException, InlineJavaPerlException {
            InlineJavaPerlCaller pc = new InlineJavaPerlCaller() ;
            return (String [])pc.CallPerlSub("@main::list",
                null, dummy.getClass()) ;
         }
      }
   END

   sub list {
      return ('a', 'b', 'c') ;
   }

   print(Pod_Context->get_list()->[1] . "\n") ; # prints b

Note: When calling a Perl function that returns a list or array, you will need to pass the Class object for the expected array type (in this case String []). Since these Class objects are difficult to access for array types, the easiest way to do this is to create a dummy array of the desired type and call the getClass() method on that object (as seen above).

CALLBACK LOOPS
It is now possible to use callbacks from different Java threads. One of the big advantages of this is that you can now handle, for example, SWING events in Perl. Here's an example:

   use Inline Java => <<'END' ;
      import java.util.* ;
      import org.perl.inline.java.* ;
      import javax.swing.* ;
      import java.awt.event.* ;

      class Pod_Button extends InlineJavaPerlCaller
                       implements ActionListener {
         JFrame frame = null ;

         public Pod_Button() throws InlineJavaException {
            frame = new JFrame("Pod_Button") ;
            frame.setSize(100,100) ;
            JButton button = new JButton("Click Me!") ;
            frame.getContentPane().add(button) ;
            button.addActionListener(this) ;
            frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE) ;
            frame.show() ;
         }

         public void actionPerformed(ActionEvent e){
            try {
               CallPerlSub("main::button_pressed", new Object [] {}) ;
            }
            catch (InlineJavaPerlException pe){
               // $@ is in pe.GetObject()
            }
            catch (InlineJavaException pe) {
               pe.printStackTrace() ;
            }
         }

         public void close(){
            frame.dispose() ;
            frame.hide() ;
            frame = null ;
         }

         public void quit(){
            System.exit(0) ;
         }
      }
   END

   my $b = new Pod_Button() ;
   $b->StartCallbackLoop() ;
   $b->close() ;

   # Maybe do some other stuff

   exit() ;      # in client-server mode, optional
   $b->quit() ;  # in JNI mode

   sub button_pressed {
      print("click!\n") ; # prints click!
      $b->StopCallbackLoop() ;
   }

The StartCallbackLoop method can be called on any "org.perl.inline.java.InlineJavaPerlCaller" object and will block the current thread and allow the reception of callbacks through any InlineJavaPerlCaller that has been created by the same (current) thread. The only way to interrupt such a StartCallbackLoop method is to call the StopCallbackLoop method on any "org.perl.inline.java.InlineJavaPerlCaller" object that has been created by that same thread.

Also, only threads that communicate with Perl through "Inline::Java" are allowed to create "org.perl.inline.java.InlineJavaPerlCaller" objects and invoke their StartCallbackLoop / StopCallbackLoop methods.

SELECT-STYLE CALLBACK LOOPS
The disadvantage with the type of callback loop presented in the previous section is that the main portion of the Perl program is completely blocked while waiting for callbacks. In version 0.51 a new API for callback loops was introduced, allowing for callbacks to be processed much in the same fashion one uses select(2) to read data from a filehandle. Here's an example:

   use Inline Java => <<'END' ;
      import java.util.* ;
      import org.perl.inline.java.* ;
      import javax.swing.* ;
      import java.awt.event.* ;

      class Pod_Button extends InlineJavaPerlCaller
                       implements ActionListener {
         JFrame frame = null ;

         public Pod_Button() throws InlineJavaException {
            frame = new JFrame("Pod_Button") ;
            frame.setSize(100,100) ;
            JButton button = new JButton("Click Me!") ;
            frame.getContentPane().add(button) ;
            button.addActionListener(this) ;
            frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE) ;
            frame.show() ;
         }

         public void actionPerformed(ActionEvent e){
            try {
               CallPerlSub("main::button_pressed", new Object [] {}) ;
            }
            catch (InlineJavaPerlException pe){
               // $@ is in pe.GetObject()
            }
            catch (InlineJavaException pe) {
               pe.printStackTrace() ;
            }
         }

         public void close(){
            frame.dispose() ;
            frame.hide() ;
            frame = null ;
         }

         public void quit(){
            System.exit(0) ;
         }
      }
   END

   my $b = new Pod_Button() ;
   $b->OpenCallbackStream() ;
   while ((my $rc = $b->WaitForCallback(5)) > -1){
      if ($rc > 0){
         # A callback is pending, we must process it.
         $b->ProcessNextCallback() ;
      }
      else {
         # A timeout has occurred after, in this case, 5 secs.
         print "5 seconds have passed, still waiting for callback...\n" ;
         # Maybe do some other stuff
      }
   }
   $b->close() ;

   # Maybe do some other stuff

   exit() ;      # in client-server mode, optional
   $b->quit() ;  # in JNI mode

   sub button_pressed {
      print('click!' . "\n") ; # prints click!
      $b->CloseCallbackStream() ;
   }

The StartCallbackStream method can be called on any InlineJavaPerlCaller object to initialize a channel to receive callbacks. The WaitForCallback method can then be called with a float timeout value (-1 means wait forever, 0 means return immediately). The WaitForCallback method can return:

   rc  >  0, indicating that rc callbacks are waiting to be processed
   rc ==  0, indicating that a timeout has occurred and no callbacks are waiting
   rc == -1, indicating that the callback stream has been closed

The callback stream can be closed by calling CloseCallbackStream, which works similarly to the StopCallbackLoop method used in the previous section.

Also, the restrictions regarding thread communication stated in the previous section are valid in this case as well.

SEE ALSO
Inline::Java, Inline::Java::PerlNatives, Inline::Java::PerlInterpreter.

AUTHOR
Patrick LeBoutillier <patl@cpan.org> is the author of Inline::Java.

Brian Ingerson <ingy@cpan.org> is the author of Inline.

COPYRIGHT
Copyright (c) 2001-2004, Patrick LeBoutillier.

All Rights Reserved. This module is free software. It may be used, redistributed and/or modified under the terms of the Perl Artistic License. See http://www.perl.com/perl/misc/Artistic.html for more details.