Share this page 

Use a Java class (PB9)Tag(s): Powerscript


We simply need to build an "EJB proxy" to our class even if it's not an EJB.

Consider the following simple class :

[Simple.java]
public class Simple {
    public Simple() {  }
    public static String sayHello(){
        return "Hello world";
    }
    public String sayNonStaticHello(){
        return "Hello world";
    }    
    public static void main(String[] args) {
        System.out.println(Simple.sayHello());
    }
}
Before generating the proxy, we need a "dummy" SimpleHome class.
[SimpleHome.java]
public interface SimpleHome { }
Compile both files. Now, we will build a Powerbuilder application and use our "Simple" class from Powerscript.

  1. Start Powerbuilder.
  2. Create a new application, call it "pbjsimple", put everything in the same directory(.class and .pbl).
  3. Start the EJB Proxies Wizard, Type "Simple" as the component and the classpath is the folder containing the "Simple.class" file.
  4. Run the project, Powerbuilder will generate proxies for your classes and also for most standard Java classes!
  5. Next, open a window from the application and drop a Button and insert the following Powerscript in the "click event".
    JavaVM lJavaVM
    EJBConnection lEJBConn
    Simple lnv_simple
    long    ll_return
    
    lJavaVM = CREATE JavaVM
    
    // need to specify the classpath form the Simple class
    ll_return = &
       lJavaVM.CreateJavaVM("C:\Applications\rega\dev\Work\pb9\Target3", FALSE)
    CHOOSE CASE ll_return
        CASE 1
        CASE 0
        CASE -1
           MessageBox ( "", "jvm.dll was not found in the classpath.")
        CASE -2
           MessageBox ( "", "pbejbclient90.jar file was not found." )
        CASE ELSE
           MessageBox ( "", "Unknown result (" + String (ll_return ) + ")"  )
    END CHOOSE
    
    IF ll_return < 0 THEN
       DESTROY lJavaVM
    END IF
    
    lEJBConn = CREATE EJBConnection
    ll_return = lEJBConn.CreateJavaInstance( lnv_simple, "Simple")
    IF ll_return <> 0 THEN
       MessageBox("", "CreateJavaInstance returned " +string(ll_return))
       destroy lEJBConn
    ELSE
       TRY
         MessageBox("From Java!" , lnv_simple.sayNonStaticHello())
       CATCH (CreateException ce)
         MessageBox( "Create Exception", ce.getMessage() )
       CATCH (Throwable t)
         MessageBox(" Other Exception", t.getMessage())
       END TRY
    END IF
    
    Note : AFAIK Java static methods are not visible from Powerbuilder.

You can download this example here