Java Interface Library/en: Unterschied zwischen den Versionen

Aus expecco Wiki (Version 2.x)
Zur Navigation springen Zur Suche springen
 
(22 dazwischenliegende Versionen von 4 Benutzern werden nicht angezeigt)
Zeile 1: Zeile 1:
'''This Article describes the old, now obsolete Java Bridge V1. Here is the documentation of the new [[Java Interface Library v2 | "Java Bridge V2"]]'''
Documentation for expecco 2.1


== Introduction ==
== Introduction ==
Zeile 10: Zeile 10:
In addition to what existing blocks of the Java Interface Library provide, programmatic access to Java objects is sometimes required to perform special functions. The following information is useful if you want to write your own elementary Java-blocks, or if you have to enhance the existing library by adding application-specific interface blocks.
In addition to what existing blocks of the Java Interface Library provide, programmatic access to Java objects is sometimes required to perform special functions. The following information is useful if you want to write your own elementary Java-blocks, or if you have to enhance the existing library by adding application-specific interface blocks.
-->
-->

Notice that this document describes the low level framework, which implements the bridge communication. A much easier to use high level interface (called "Groovy Blocks") exists and should normally be used, if you need access to a Java application's internals during testing.
Please take a look at
[[Expecco_API#Groovy_Elementary_Blocks | "Groovy Block API"]]
and [[Testing Java Applications using Groovy blocks/en | "Testing Java Applications using Groovy blocks"]].


== Architecture ==
== Architecture ==
Zeile 28: Zeile 33:




This setup allows for transparent communication with objects inside a local or remote Java VM. This may be either utility functions which happen to be convenient for the test application (for example: file parsing, syntax analysis, protocol implementaitons or access to specific hardware via driver libraries), or the tested application in the system under test itself.
This setup allows for transparent communication with objects inside a local or remote Java VM. This may be either utility functions which happen to be convenient for the test application (for example: file parsing, syntax analysis, protocol implementations or access to specific hardware via driver libraries), or the tested application in the system under test itself.


Especially, it allows for the objects of the tested application to be looked into, manipulated and for functions of it or underlying frameworks to be called.
Especially, it allows for the objects of the tested application to be looked into, manipulated and for functions of it or underlying frameworks to be called.
Zeile 38: Zeile 43:
Notice that a similar mechanism is used in expecco to communicate with DOTNET, Qt (C++) and C applications.
Notice that a similar mechanism is used in expecco to communicate with DOTNET, Qt (C++) and C applications.



 


== Initializing / Releasing the Bridge ==
== Initializing / Releasing the Bridge ==
Zeile 73: Zeile 76:
\exept\expecco\packages\exept\technologyBridge\javaBridge\javaBridge_Server_Client\JavaBridge.jar
\exept\expecco\packages\exept\technologyBridge\javaBridge\javaBridge_Server_Client\JavaBridge.jar


The Javabridge code allows for either side to initiate the connection - i.e. it can be run in server mode,
The Java Bridge code allows for either side to initiate the connection - i.e. it can be run in server mode,
where it awaits an incoming connection, or in client mode, where it actively initiates a connection.
where it awaits an incoming connection, or in client mode, where it actively initiates a connection.
After connection establishment, there is no difference in the operation of the bridge, however depending on the setup of your network infrastructure, especially firewalls, either mechanism may be easier to be used.
After connection establishment, there is no difference in the operation of the bridge, however depending on the setup of your network infrastructure, especially firewalls, either mechanism may be easier to be used.
Zeile 89: Zeile 92:
====Startup Parameters====
====Startup Parameters====
You can use any parameter in any order.
You can use any parameter in any order.
If no parameter is used then the bridge listenes on port 14014 in server mode without keepAlive.
If no parameter is used then the bridge listens on port 14014 in server mode without keepAlive.
;<code>-help</code>
;<code>-help</code>
* Shows the help
* Shows the help


;<code>-ip <aHostnameOrIP></code>
;<code>-ip <aHostnameOrIP></code>
* In client mode this specifies the ip or hostname to connect to.
* In client mode this specifies the IP address or the hostname to connect to.


;<code>-port <aPortNumber> </code>
;<code>-port <aPortNumber> </code>
Zeile 107: Zeile 110:
== Loading Applications (from the expecco side) ==
== Loading Applications (from the expecco side) ==


Normally, you would start your application with the required command line arguments and include the javabridge as jar there. However, in some situations, it may be required to dynamically load other jars into the connection Java VM.
Normally, you would start your application with the required command line arguments and include the Java Bridge as jar there. However, in some situations, it may be required to dynamically load other jars into the connection Java VM.
By accessing a classloader, additional classes, or applications as contained in JAR files can be loaded from the expecco side.
By accessing a classloader, additional classes, or applications as contained in JAR files can be loaded from the expecco side.


Zeile 119: Zeile 122:
== Java Package Import and Class Access==
== Java Package Import and Class Access==


The import (loading) of additional required packages is done automatically in the JVM, when one of the package's classes is accessed for the very first time. In other words, when the Java code references a class for the first time, whose package is not yet loaded, it will search for the package along the class path and load it. Thus the above "addToClassPath:" actually does not yet verify or load the package, but only prepare any future "load on demand". This may be a bit dangerous, as failures may be reported much later, when a missing class is actually loaded (so better double check, that all the class pathes are valid, and the corresponding files are present on the system on which the JVM runs).
The import (loading) of additional required packages is done automatically in the JVM, when one of the package's classes is accessed for the very first time. In other words, when the Java code references a class for the first time, whose package is not yet loaded, it will search for the package along the class path and load it. Thus the above "addToClassPath:" actually does not yet verify or load the package, but only prepare any future "load on demand". This may be a bit dangerous, as failures may be reported much later, when a missing class is actually loaded (so better double check, that all the class paths are valid, and the corresponding files are present on the system on which the JVM runs).




This following code sample simple references (i.e. accesses) the class "JFrame" from the <CODE>"javax.swing"</CODE> package. The fully specified class name in Java would be <CODE>"javax.swing.JFrame"</CODE>. Note that in Smalltalk code, the dots are replaced by underscores and the full class name is written as a message send to the java bridge handle:
This following code sample simple references (i.e. accesses) the class "JFrame" from the <CODE>"javax.swing"</CODE> package. The fully specified class name in Java would be <CODE>"javax.swing.JFrame"</CODE>. Note that in Smalltalk code, the dots are replaced by underscores and the full class name is written as a message send to the Java Bridge handle:
<CODE><PRE>
<CODE><PRE>
java javax_swing_JFrame.
java javax_swing_JFrame.
</PRE></CODE>
</PRE></CODE>


After that call, the JavaVM has loaded the required package(s) and now knows the package <CODE>"javax.swing"</CODE>. It will lookup short form class names in the set of known packages. Now we can access all classes of that package without a need to provide the full class name. For example, if we now want to access the class <CODE>"javax.swing.JButton"</CODE>, it can be done via the class's short name:
After that call, the Java VM has loaded the required package(s) and now knows the package <CODE>"javax.swing"</CODE>. It will lookup short form class names in the set of known packages. Now we can access all classes of that package without a need to provide the full class name. For example, if we now want to access the class <CODE>"javax.swing.JButton"</CODE>, it can be done via the class's short name:
<CODE><PRE>
<CODE><PRE>
java JButton.
java JButton.
Zeile 142: Zeile 145:
The first statement results in a proxy object for the "JFrame" instance (and as a side effect of referring to the class will import the <CODE>"javax.swing"</CODE> package). The second line results in a proxy for a new "JButton" object.
The first statement results in a proxy object for the "JFrame" instance (and as a side effect of referring to the class will import the <CODE>"javax.swing"</CODE> package). The second line results in a proxy for a new "JButton" object.


== Calling Methods ==
== Calling Instance Methods ==


A method call is done by a message send to a proxy object where the message is the method name to call. For example to call the <CODE>"setVisible(boolean isVisible)"</CODE> method on a JFrame object. First instantiate such an object and send the message to that proxy.
A method call is done by a message send to a proxy object, where the message is the method name to call. For example, to call the <CODE>"setVisible(boolean isVisible)"</CODE> method on the above JFrame object, we send the following message to that proxy:
<CODE><PRE>
<CODE><PRE>
frame setVisible:true.
frame setVisible:true.
</PRE></CODE>
</PRE></CODE>


As method naming is different in Smalltalk and Java, a dynamic translation is applied when sending messages from Smalltalk code to a remote Java object. Smalltalk has arguments embedded inside parts of a so called "keyword" message, such as in "receiver foo:arg1 bar:arg2", where "foo:bar:" would be the message name, and "arg1", "arg2" be the arguments.
To call a method with more than one parameter like <CODE>"setSize(int width,int height)"</CODE> on a JFrame we can write this.

In Java, the message name is a single identifier, and arguments are written in an argument list after the message name: "receiver.fooBar(arg1, arg2)".

When message names are translated, only the very first part of the Smalltalk keyword message is taken ("foo" in the above example), and the remaining parts are simply ignored. Thus, any of the Smalltalk messages "foo:bar:", "foo:xxxx:" and "foo:_:" (a single underscore as second part) all translate to the same Java message name "foo()".

Therefore, to call a method with more than one argument, like <CODE>"setSize(int width,int height)"</CODE> on a JFrame instance we can write:
<CODE><PRE>
<CODE><PRE>
frame setSize:300 _:200.
frame setSize:300 _:200.
Zeile 157: Zeile 166:
frame setSize:300 anyWord:200.
frame setSize:300 anyWord:200.
</PRE></CODE>
</PRE></CODE>
or any other selector with "setSize:" as its first component. The selector translation mechanism simply takes the first part as the java selector.
or any other selector with "setSize:" as its first component.
The selector translation mechanism simply takes the first part as the Java selector.
In practice, you would take a reasonably descriptive name, such as: "frame setSize:300 height:200".


In practice, you should take a reasonably descriptive name, such as: "frame setSize:300 height:200" or only the Java name as first part, such as "frame setSize:300 _:200".
Or for a method with 4 parameters it could look like this.

For a call of a method with 4 arguments, we could write:
<CODE><PRE>
<CODE><PRE>
frame setBounds:100 y:50 width:300 height:200.
frame setBounds:100 y:50 width:300 height:200.
</PRE></CODE>
</PRE></CODE>
or:
<CODE><PRE>
frame setBounds:100 _:50 _:300 _:200.
</PRE></CODE>

Also here the <CODE>"y: width: height:"</CODE> can be named as you want, but the first part must be "setBounds:".
Also here the <CODE>"y: width: height:"</CODE> can be named as you want, but the first part must be "setBounds:".


=== Calling Static Methods ===
=== Calling Static Methods ===


Calling a static method on an object is not different from calling non static methods. In most cases you will call a static method not on an object but directly on the class. This is done by just calling the method on the class object. For example we want to call the static method <CODE>"isDefaultLookAndFeelDecorated()"</CODE> of the JFrame class.
Calling a static method on an object is not different from calling non static methods. In most cases you will call a static method not on an object but directly on the class. This is done by using the class object as "receiver" of the message. For example, if we want to call the static method <CODE>"isDefaultLookAndFeelDecorated()"</CODE> of the JFrame class, write:
<CODE><PRE>
<CODE><PRE>
java javax_swing_JFrame isDefaultLookAndFeelDecorated.
java javax_swing_JFrame isDefaultLookAndFeelDecorated.
Zeile 178: Zeile 194:


== Accessing Fields ==
== Accessing Fields ==

Accessing a field of a Java object or class is not different from calling methods. To access a field, send a message where the message is the field name. To access the field of a class the field must be static. For example we want to get the value of the static field <CODE>"EXIT_ON_CLOSE"</CODE> of the JFrame class.
As Smalltalk does not support access of an object's fields from the outside (it is fully encapsulated, and access from outside is ONLY allowed via getters/setters), an additional translation mechanism is provided for field access.
Accessing a field of a Java object or a class's static field uses the same syntax as method calls. To access a field, send a message where the message is the field name. To access the field of a class the field must be static.
For example, to get the value of the static field named <CODE>"EXIT_ON_CLOSE"</CODE> of the "JFrame" class, write
<CODE><PRE>
<CODE><PRE>
value := java javax_swing_JFrame EXIT_ON_CLOSE.
value := java javax_swing_JFrame EXIT_ON_CLOSE.
</PRE></CODE>
</PRE></CODE>
or (using short names):
or if the package is already known:
<CODE><PRE>
<CODE><PRE>
value := java JFrame EXIT_ON_CLOSE.
value := java JFrame EXIT_ON_CLOSE.
Zeile 188: Zeile 208:
The variable "value" now holds the integer value of the <CODE>"EXIT_ON_CLOSE"</CODE> constant.
The variable "value" now holds the integer value of the <CODE>"EXIT_ON_CLOSE"</CODE> constant.


Let us imagine that a JFrame object would have a field named <CODE>"myField"</CODE>. To access this field, had to write something like:
Assuming that a "JFrame" object had a field named <CODE>"myField"</CODE>, to access this field, we'd have to write:
<CODE><PRE>
<CODE><PRE>
value := frame myField.
value := frame myField.
</PRE></CODE>
</PRE></CODE>
and "value" now holding whatever <CODE>"myField"</CODE> returns. This could be another object reference or any primitive value.
and "value" now holding whatever <CODE>"myField"</CODE> returns. This could be another object reference or any primitive value.

=== Setting Fields ===
To set a field, use a setter-like method call:
<CODE><PRE>
frame myField: newValue.
</PRE></CODE>

=== Name Conflicts ===

In very rare situations, a Java object may contain both a field and a method by the same name.
In this case, the Smalltalk code cannot depend on the dynamic translation mechanism (which actually looks for either a field or method name to match), but instead make it explicit, which operation is wanted:
Use:
<CODE><PRE>
frame getFieldByName:'myField'
</PRE></CODE>
to read a field, and:
<CODE><PRE>
frame setFieldByName:'myField' value:123.
</PRE></CODE>
to write the field.

If there are both fields and methods by the same name, and you use the non-explicit call,
the bridge will always assume that you want to call the getter/setter and perform a method call.


== Callbacks from Java ==
== Callbacks from Java ==
Sometimes we want to execute a small piece of smalltalk code during the execution of the Java code. For example, we may want to install a Smalltalk observer to be notified when a button on a Java GUI was pressed. The following code registers a Smalltalk block as a callback for a mouse press event of a button:
Sometimes you may want to execute a piece of Smalltalk code during the execution of the Java code. For example, we may want to install a Smalltalk observer to be notified when a button on a Java GUI was pressed,
or some other callback from a Java framework.

The following code registers a Smalltalk block as a callback for a mouse press event of a button:
<CODE><PRE>
<CODE><PRE>
listener := MouseListener new.
listener := MouseListener new.
listener mousePressed:[ Transcript showCR:'Hello from Java' ].
listener mousePressed:[ Transcript showCR:'Hello from Java' ].
</PRE></CODE>
</PRE></CODE>
This above creates the callback and the listener, which can now be registered on a button:
The above creates the callback and the listener, which can now be registered on a button:
<CODE><PRE>
<CODE><PRE>
button addMouseListener:listener.
button addMouseListener:listener.
</PRE></CODE>
</PRE></CODE>
Now, with the press of the button in the Java GUI, the Smalltalk block will be executed and writes <CODE>"Hello from Java"</CODE> on the Smalltalk console.
Now, with the press of the button in the Java GUI, the Smalltalk block will be executed and writes <CODE>"Hello from Java"</CODE> to the Smalltalk console.
Of course, any other (Smalltalk-)action code can be made to run via this mechanism.

But be aware, that the callback is possibly called later (when the elementary action, which installed the code, has already finished long ago). Also, as the Java code execution is not synchronized with any of your expecco action execution, the callback may also be called at any arbitrary time, even at times when no activity at all is executed on the expecco side. If you forget to cleanup, and the Java object is still alive, it may even be called after you have finished your test run (if you keep the Java Bridge handle around and alive, for example in an expecco environment variable).

So the Smalltalk callback code should not depend on any particular elementary action to be currently running, but instead in most cases write some information into a shared data container, preferably an instance of "SharedQueue", which is thread safe. Then, some other action (an elementary action) would read-wait and read events from that shared queue.


make sure that your test correctly cleans up any such callbacks afterwards. As a last resort, use the "Shutdown Bridge Connection" menu item, which closes the bridge connection, and thereby - as a side effect - removes any leftover callbacks. It does close the connection, and any remaining Java proxy object handles become invalid, though.


Another example, using an observer would look like:
Another example, using an observer could look like:
<CODE><PRE>
<CODE><PRE>
observer := java Observer new.
observer := java Observer new.
observer update:[:sourceObservable :argument|
observer update:[:sourceObservable :argument|
argument notNil ifTrue:[ Transcript showCR:('I was notifyed with: ',argument toString) ]
argument notNil ifTrue:[ Transcript showCR:('I was notified with: ',argument toString) ]
ifFalse:[ Transcript showCR:'I was notifyed and the argument was nil' ].
ifFalse:[ Transcript showCR:'I was notified and the argument was nil' ].
].
].
myObservable addObserver:observer.
myObservable addObserver:observer.
</PRE></CODE>
</PRE></CODE>
When the observable calls <CODE>"notifyObservers"</CODE> the Smalltalk block will be executed.
When the observable calls <CODE>"notifyObservers"</CODE>, the Smalltalk block will be executed.


== Exceptions in Java ==
== Exceptions in Java ==
Zeile 225: Zeile 277:
== Remote Dynamic Code Injection ==
== Remote Dynamic Code Injection ==
Sometimes we might want to execute code without the overhead of many rpc-messages being sent over the bridge, especially if we want to do something time critical, or want to make execution time measurements.
Sometimes we might want to execute code without the overhead of many rpc-messages being sent over the bridge, especially if we want to do something time critical, or want to make execution time measurements.
For this, it is possible to load a class at runtime into the JavaVM. The code of the class will first be sent to the JavaVM, which will compile and load the generated byte code. Then, the class can be accessed via the bridge just like any other preloaded class.
For this, it is possible to load a class at runtime into the Java VM. The code of the class will first be sent to the Java VM, which will compile and load the generated byte code. Then, the class can be accessed via the bridge just like any other preloaded class.


The following example specifies the class code in a smalltalk string and inject the code into the JavaVM. Then an instance of that new class will be instantiated and finally a method of the object instance will be invoked:
The following example specifies the class code in a Smalltalk string and inject the code into the Java VM. Then an instance of that new class will be instantiated and finally a method of the object instance will be invoked:
<CODE><PRE>
<CODE><PRE>
classCode := '
classCode := '
Zeile 324: Zeile 376:


=== Code Sources for Class injection ===
=== Code Sources for Class injection ===
There are 3 possible types of class code sources which we can use to inject the code. In the examples before we directly used a simple <CODE>"String"</CODE> in the smalltalk code as a code source. We also can use a <CODE>"*.java"</CODE> file as source. Just read the content of the file into a string and use it as in the previous examples.
There are 3 possible types of class code sources which we can use to inject the code. In the examples before we directly used a simple <CODE>"String"</CODE> in the Smalltalk code as a code source. We also can use a <CODE>"*.java"</CODE> file as source. Just read the content of the file into a string and use it as in the previous examples.


To inject a <CODE>"*.class"</CODE> file use the following code:
To inject a <CODE>"*.class"</CODE> file use the following code:
Zeile 334: Zeile 386:
== Examples ==
== Examples ==


This example creates a JFrame with one button inside. Then a Mouselistener is created and registered on the button. When the button is pressed, the title of the window changes to <CODE>"onPressed"</CODE> and the Transcript shows the message <CODE>"onPressed"</CODE>. When the button is released, the title of the window is changed to <CODE>"onReleased"</CODE> and the Transcript shows <CODE>"onReleased"</CODE>. If the button lost the mouse focus, the bridge will exit (disconnect), and the Java side is terminated.
This example creates a JFrame with one button inside. Then a MouseListener is created and registered on the button. When the button is pressed, the title of the window changes to <CODE>"onPressed"</CODE> and the Transcript shows the message <CODE>"onPressed"</CODE>. When the button is released, the title of the window is changed to <CODE>"onReleased"</CODE> and the Transcript shows <CODE>"onReleased"</CODE>. If the button lost the mouse focus, the bridge will exit (disconnect), and the Java side is terminated.
<CODE><PRE>
<CODE><PRE>
|java frame button listener|
|java frame button listener|
Zeile 359: Zeile 411:


=== Simple RMI Call ===
=== Simple RMI Call ===
The next example is written in JavaScript syntax. It shows how an RMI host is queried for an RMI object and then the "getHello" method is called on it. The following code is not directly executable: you must replace the path to the compiled MyRemoteObject class by the directory containing the class file, and to replace the RMI host to a real one.
The next example is written in JavaScript syntax. It shows how an RMI host is queried for an RMI object and then the "getHello" method is called on it. The following code is not directly executable: you must replace the path to the compiled MyRemoteObject class with the directory containing the class file, and replace the RMI host name with a real one in your network:
<CODE><PRE>
<CODE><PRE>
var java, reg, myRemoteObject, callResult;
var java, reg, myRemoteObject, callResult;


// Start a local JavaVM and connect the Communication-Bridge to it
// Start a local Java VM and connect the Communication-Bridge to it
java = JAVA::Java.singletonInstance;
java = JAVA::Java.singletonInstance;


Zeile 434: Zeile 486:
java := JAVA::JavaBridge newWithServer.
java := JAVA::JavaBridge newWithServer.


"/defining a java class in a string
"/defining a Java class in a string
packageName := 'myPackage.test'.
packageName := 'myPackage.test'.
className := 'MyExampleClass'.
className := 'MyExampleClass'.
Zeile 479: Zeile 531:
'bindWith:packageName with:className.
'bindWith:packageName with:className.
"/injecting the class into the java vm
"/injecting the class into the Java VM
java RemoteClassInject injectClassCode:packageName className:className classCode:classCode.
java RemoteClassInject injectClassCode:packageName className:className classCode:classCode.


Zeile 490: Zeile 542:
].
].


"/exit the java vm
"/exit the Java VM
java exitJava.
java exitJava.
</PRE></CODE>
</PRE></CODE>




Now the same code but with a callback to smalltalk via an Java observer.
Now the same code but with a callback to Smalltalk via an Java observer.
<CODE><PRE>
<CODE><PRE>
| java packageName className classCode observer |
| java packageName className classCode observer |
Zeile 502: Zeile 554:
java := JAVA::JavaBridge startNew.
java := JAVA::JavaBridge startNew.


"/defining a java class in a string
"/defining a Java class in a string
packageName := 'myPackage.test'.
packageName := 'myPackage.test'.
className := 'MyExampleClass'.
className := 'MyExampleClass'.
Zeile 557: Zeile 609:
'bindWith:packageName with:className.
'bindWith:packageName with:className.


"/injecting the class into the java vm
"/injecting the class into the Java VM
java RemoteClassInject injectClassCode:packageName className:className classCode:classCode.
java RemoteClassInject injectClassCode:packageName className:className classCode:classCode.


Zeile 563: Zeile 615:
java myPackage_test_MyExampleClass main.
java myPackage_test_MyExampleClass main.


"/creating a java observer proxy on in smalltalk
"/creating a Java observer proxy in Smalltalk
observer := java Observer new.
observer := java Observer new.


Zeile 573: Zeile 625:
].
].


"/register the observer to the observable we want to be notifyed from
"/register the observer to the observable we want to be notified from
MyExampleClass anInstanceOfMe addObserver:observer.
MyExampleClass anInstanceOfMe addObserver:observer.
</PRE></CODE>
</PRE></CODE>
Zeile 582: Zeile 634:
====class protocol====
====class protocol====
=====newWithServer=====
=====newWithServer=====
* This will start a local JavaVM, running the JavaBridge, and establishes a connection on a random free port.
* This will start a local Java VM, running the Java Bridge, and establishes a connection on a random free port.
: A new connected instance of JAVA::Java class is returned.
: A new connected instance of JAVA::Java class is returned.


=====newWithServerForJavaPath:aJavaPathFilename=====
=====newWithServerForJavaPath:aJavaPathFilename=====
* This is the same as newWithServer but the path to the java executable can be specified. The JavaVM version must be 1.6 or higher to run the JavaBridge.
* This is the same as newWithServer but the path to the Java executable can be specified. The Java VM version must be 1.6 or higher to run the Java Bridge.
:: '''aJavaPathFilename''' - must be a instance of Filename
:: '''aJavaPathFilename''' - must be a instance of Filename
Smalltalk: JAVA::Java newWithServerForJavaPath:('my\path\to\java.executable'asFilename).
Smalltalk: JAVA::Java newWithServerForJavaPath:('my\path\to\java.executable'asFilename).
JavaScript: JAVA::Java.newWithServerForJavaPath("my\path\to\java.executable".asFilename());
JavaScript: JAVA::Java.newWithServerForJavaPath("my\path\to\java.executable".asFilename());


=====newConnectedTo:aHhostString port:aPortNumber withTimeout:aTimeoutSeconds=====
=====newConnectedTo:aHostString port:aPortNumber withTimeout:aTimeoutSeconds=====
* This is used to connect to a running JavaBridge on the network. The JavaBridge must be started in server mode on the remote host. After connecting a new connected instance of JAVA::Java is returned.
* This is used to connect to a running Java Bridge on the network. The Java Bridge must be started in server mode on the remote host. After connecting a new connected instance of JAVA::Java is returned.
:: '''aHostString''' - the hostname or IP of the remote machine as String
:: '''aHostString''' - the hostname or IP of the remote machine as String
:: '''aPortNumber ''' - the port on which the remote machine is listening as Number
:: '''aPortNumber ''' - the port on which the remote machine is listening as Number
Zeile 600: Zeile 652:


=====newWaitingForConnectOnHost:aListeningAddressString port:aListeningPortNumber withTimeout:aTimeoutSeconds=====
=====newWaitingForConnectOnHost:aListeningAddressString port:aListeningPortNumber withTimeout:aTimeoutSeconds=====
* This is used to wait for incomming connecions of a running JavaBridge on the network. The JavaBridge must be started in client mode on the remote host. After connecting a new connected instance of JAVA::Java is returned.
* This is used to wait for incoming connections of a running Java Bridge on the network. The Java Bridge must be started in client mode on the remote host. After connecting a new connected instance of JAVA::Java is returned.
:: '''deprecated: aListeningAddressString''' - no longer used. Can be nil.
:: '''deprecated: aListeningAddressString''' - no longer used. Can be nil.
:: '''aListeningPortNumber ''' - the port on which to listen for incomming connections as Number
:: '''aListeningPortNumber ''' - the port on which to listen for incoming connections as Number
:: '''aTimeoutSeconds''' - a connect timeout in seconds as Number, If nil it will wait endless.
:: '''aTimeoutSeconds''' - a connect timeout in seconds as Number, If nil it will wait endless.


Zeile 613: Zeile 665:
====instance protocol====
====instance protocol====
=====addJarByPath:aPath=====
=====addJarByPath:aPath=====
* Adds a jar to the class path of the running JavaVM. If the jar depends on other jars or librarys you have to add them too.
* Adds a jar to the class path of the running Java VM. If the jar depends on other jars or libraries you have to add them too.
:: '''aPath''' - the path to the jar file as String.
:: '''aPath''' - the path to the jar file as String.


=====addLibraryByPath:aPath=====
=====addLibraryByPath:aPath=====
* Adds a library to the library path of the running JavaVM. If the library depends on other librarys you have to add them too.
* Adds a library to the library path of the running Java VM. If the library depends on other libraries you have to add them too.
:: '''aPath''' - the path to the library file as String.
:: '''aPath''' - the path to the library file as String.


Zeile 629: Zeile 681:


=====closeBridge=====
=====closeBridge=====
* This will close the bridge connection. Depending on in which mode the JavaBridge was started, the JavaVM is also closed (-keepAlive startparameter not set).
* This will close the bridge connection. Depending on in which mode the Java Bridge was started, the Java VM is also closed (-keepAlive startparameter not set).


=====exit=====
=====exit=====
Zeile 635: Zeile 687:


== See Also==
== See Also==
The [[DOT NET Interface Library| DOTNET Interface Plugin & Library]], which implements a likewise interface for .NET applications/libraries.
The [[DOT NET Interface Library| DOTNET Interface Plugin & Library]], which implements a likewise interface for .NET applications/libraries.<br>
[[Java Interface Library v2 | Version 2 of the Java Interface Library]]


----
<hr>
Back to [[Plugins]]<br>
Back to [[Plugins]]<br>
Back to [[OnlineDocumentation#Library and Plugin Overview|Online Documentation]].
Back to [[Online Documentation#Library and Plugin Overview|Online Documentation]].

[[Category: Plugins/en]]
[[Category: Advanced/en]]

Aktuelle Version vom 18. März 2021, 08:17 Uhr

This Article describes the old, now obsolete Java Bridge V1. Here is the documentation of the new "Java Bridge V2"

Introduction[Bearbeiten]

The Java Interface library ("Java Bridge") is used to interact with Java objects inside an external Java Virtual Machine (JVM).

The access to Java objects, classes and programs is done via a framework called "Java-Bridge", which is similar in operation to the dotNET bridge. This framework implements transparent forwarding of method (virtual function) calls to Java objects, which exist in a local or remote Java Virtual Machine (JVM). Also, return values, callBacks and exception information are passed back from the Java program to expecco. This is done by a proxy-object mechanism, which catches all function calls, wraps the arguments, sends a datagram to the other bridge side, awaits the reply and returns the result to the original caller. Thus, remote procedure calls are almost completely transparent to the Smalltalk/JavaScript code inside expecco. In your elementary code, you can write remote function calls as if they were to local objects.


Notice that this document describes the low level framework, which implements the bridge communication. A much easier to use high level interface (called "Groovy Blocks") exists and should normally be used, if you need access to a Java application's internals during testing. Please take a look at "Groovy Block API" and "Testing Java Applications using Groovy blocks".

Architecture[Bearbeiten]

On the expecco side, the bridge consists of a number of Proxy objects, which behave like regular Smalltalk objects as seen from elementary expecco code. However, instead of performing an action when one of their methods (virtual functions) is called, they send a message over a socket connection to the Java VM (actually: to a bridge software inside the Java application) which decodes the message and sends it to the destination Java object. The same is done in reverse direction with the return value.


+---------------------+     +----------+     +----------------+      +----------------+     +---------+ 
|                     |     |          |     |                |      |                |     |   Java  |
|       expecco       |---->|  Proxy   |---->|      Bridge    |==>>==|      Bridge    |---->|  Object |
|  (elementary code)  |<----|          |<----| (expecco side) |==<<==|   (Java side)  |<----|         |
+---------------------+     +----------+     +----------------+      +----------------+     +---------+


This setup allows for transparent communication with objects inside a local or remote Java VM. This may be either utility functions which happen to be convenient for the test application (for example: file parsing, syntax analysis, protocol implementations or access to specific hardware via driver libraries), or the tested application in the system under test itself.

Especially, it allows for the objects of the tested application to be looked into, manipulated and for functions of it or underlying frameworks to be called.

For expecco code, we tried to make this as transparent as possible, however there are a few exceptions, when function names need to be translated (for example, because the function naming syntax is different) or due to the fact that for some operations no corresponding name exists in Smalltalk (array access, for example).

Of course, multiple such connections can coexist and be served/handled in parallel. This enables an expecco test suite to communicate with both sides of a tested client-server Java application, for example.

Notice that a similar mechanism is used in expecco to communicate with DOTNET, Qt (C++) and C applications.


Initializing / Releasing the Bridge[Bearbeiten]

Before any communication can take place between expecco and any Java object, the Java side of the bridge has to be started, and a communication has to be established. In expecco, all of the bridge classes are found in the JAVA namespace.

The main interface class is "Java", in the "JAVA" namespace:

    java := JAVA::Java newWithServer.

or (in JavaScript):

    java = JAVA::Java.newWithServer();

This starts the Java-side of the bridge (actually executes java as a background command) on the local machine, and establishes a connection to that JVM.

The bridge connection should be closed, if the bridge is no longer needed. Release the bridge with:

    java.closeBridge();

which terminates the connection.

Start and Connect to a Remote Machine[Bearbeiten]

The above started a Java VM and connected to it. Alternatively, you may want to connect to an already running Java program (typically, your system under test). In order for your program to be reachable, it must allow for the bridge to connect to it via a special bridge-connection, which is a socket connection. For this, it must execute the server code found in the "JavaBridge.jar" file. To pass parameters you will typically start it from a command line or a little shell/batch script.

Call (on the shell/cmd level):

   $ java -jar <PATH_TO_JAVABRIDGE.JAR> <PARAMETERS>

The "JavaBridge.jar" file is found in the installation directory of expecco at:

   \exept\expecco\packages\exept\technologyBridge\javaBridge\javaBridge_Server_Client\JavaBridge.jar

The Java Bridge code allows for either side to initiate the connection - i.e. it can be run in server mode, where it awaits an incoming connection, or in client mode, where it actively initiates a connection. After connection establishment, there is no difference in the operation of the bridge, however depending on the setup of your network infrastructure, especially firewalls, either mechanism may be easier to be used.

Assuming that the bridge is already running on the remote machine as server (default), use newConnectedTo:port:withTimeout: to connect to it from the expecco side:

   java := JAVA::Java newConnectedTo:'myHost' port:4567 withTimeout:30.

This will initiate the connection setup from the expecco side.

Alternatively, if started in client mode use newWaitingForConnectOnHost:port:withTimeout::

   java := JAVA::Java newWaitingForConnectOnHost:'localhost' port:4567 withTimeout:30.

which will open a port on the expecco side, and wait until the Java side connects to it. For more details see API

Startup Parameters[Bearbeiten]

You can use any parameter in any order. If no parameter is used then the bridge listens on port 14014 in server mode without keepAlive.

-help
  • Shows the help
-ip <aHostnameOrIP>
  • In client mode this specifies the IP address or the hostname to connect to.
-port <aPortNumber>
  • In client mode this specifies the port to connect to. In server mode this specifies the listening port.
-asClient
  • The bridge will start in client mode. If not set the bridge is started in server mode.
-keepAlive
  • By setting this flag the bridge will not exit after the connection has closed and starts to connect or listen again. Otherwise, it will run for a single connection session only.

Loading Applications (from the expecco side)[Bearbeiten]

Normally, you would start your application with the required command line arguments and include the Java Bridge as jar there. However, in some situations, it may be required to dynamically load other jars into the connection Java VM. By accessing a classloader, additional classes, or applications as contained in JAR files can be loaded from the expecco side.

This can be used to add a JAR file to the class path:

    java addJarByPath:'pathToJarFile'. "/ assuming "java" is a handle as returned from the above connect

be aware, that if the JVM is on a remote machine, you should ensure somehow that the jar file is present on that machine. If required, transfer it to the machine's "tmp" directory, and use that folder as path. (you can use another expecco block for that file transfer, or write a little batch/shell script to do that).

Java Package Import and Class Access[Bearbeiten]

The import (loading) of additional required packages is done automatically in the JVM, when one of the package's classes is accessed for the very first time. In other words, when the Java code references a class for the first time, whose package is not yet loaded, it will search for the package along the class path and load it. Thus the above "addToClassPath:" actually does not yet verify or load the package, but only prepare any future "load on demand". This may be a bit dangerous, as failures may be reported much later, when a missing class is actually loaded (so better double check, that all the class paths are valid, and the corresponding files are present on the system on which the JVM runs).


This following code sample simple references (i.e. accesses) the class "JFrame" from the "javax.swing" package. The fully specified class name in Java would be "javax.swing.JFrame". Note that in Smalltalk code, the dots are replaced by underscores and the full class name is written as a message send to the Java Bridge handle:

    java javax_swing_JFrame. 

After that call, the Java VM has loaded the required package(s) and now knows the package "javax.swing". It will lookup short form class names in the set of known packages. Now we can access all classes of that package without a need to provide the full class name. For example, if we now want to access the class "javax.swing.JButton", it can be done via the class's short name:

    java JButton. 

ATTENTION: If a classes' short form exists in more than one package on the Java side, then you still have to specify the full name of the class. Otherwise, the first matching class will be taken and that's probably not the one you were looking for!

Instantiating a Class[Bearbeiten]

Object instances are created via the "new"-message, sent to a proxy of a Java class. You can get this proxy as described in the previous section. For example, if we want to create a new instance of a "JFrame" and a "JButton", write:

    frame := java javax_swing_JFrame new.
    button := java JButton new. 

The first statement results in a proxy object for the "JFrame" instance (and as a side effect of referring to the class will import the "javax.swing" package). The second line results in a proxy for a new "JButton" object.

Calling Instance Methods[Bearbeiten]

A method call is done by a message send to a proxy object, where the message is the method name to call. For example, to call the "setVisible(boolean isVisible)" method on the above JFrame object, we send the following message to that proxy:

    frame setVisible:true.

As method naming is different in Smalltalk and Java, a dynamic translation is applied when sending messages from Smalltalk code to a remote Java object. Smalltalk has arguments embedded inside parts of a so called "keyword" message, such as in "receiver foo:arg1 bar:arg2", where "foo:bar:" would be the message name, and "arg1", "arg2" be the arguments.

In Java, the message name is a single identifier, and arguments are written in an argument list after the message name: "receiver.fooBar(arg1, arg2)".

When message names are translated, only the very first part of the Smalltalk keyword message is taken ("foo" in the above example), and the remaining parts are simply ignored. Thus, any of the Smalltalk messages "foo:bar:", "foo:xxxx:" and "foo:_:" (a single underscore as second part) all translate to the same Java message name "foo()".

Therefore, to call a method with more than one argument, like "setSize(int width,int height)" on a JFrame instance we can write:

    frame setSize:300 _:200.

but just as well:

    frame setSize:300 anyWord:200.

or any other selector with "setSize:" as its first component. The selector translation mechanism simply takes the first part as the Java selector.

In practice, you should take a reasonably descriptive name, such as: "frame setSize:300 height:200" or only the Java name as first part, such as "frame setSize:300 _:200".

For a call of a method with 4 arguments, we could write:

    frame setBounds:100 y:50 width:300 height:200.

or:

    frame setBounds:100 _:50 _:300 _:200.

Also here the "y: width: height:" can be named as you want, but the first part must be "setBounds:".

Calling Static Methods[Bearbeiten]

Calling a static method on an object is not different from calling non static methods. In most cases you will call a static method not on an object but directly on the class. This is done by using the class object as "receiver" of the message. For example, if we want to call the static method "isDefaultLookAndFeelDecorated()" of the JFrame class, write:

    java javax_swing_JFrame isDefaultLookAndFeelDecorated.

or if the package is already known:

    java JFrame isDefaultLookAndFeelDecorated.

Accessing Fields[Bearbeiten]

As Smalltalk does not support access of an object's fields from the outside (it is fully encapsulated, and access from outside is ONLY allowed via getters/setters), an additional translation mechanism is provided for field access.

Accessing a field of a Java object or a class's static field uses the same syntax as method calls. To access a field, send a message where the message is the field name. To access the field of a class the field must be static. For example, to get the value of the static field named "EXIT_ON_CLOSE" of the "JFrame" class, write

    value := java javax_swing_JFrame EXIT_ON_CLOSE.

or (using short names):

    value := java JFrame EXIT_ON_CLOSE.

The variable "value" now holds the integer value of the "EXIT_ON_CLOSE" constant.

Assuming that a "JFrame" object had a field named "myField", to access this field, we'd have to write:

    value := frame myField.

and "value" now holding whatever "myField" returns. This could be another object reference or any primitive value.

Setting Fields[Bearbeiten]

To set a field, use a setter-like method call:

    frame myField: newValue.

Name Conflicts[Bearbeiten]

In very rare situations, a Java object may contain both a field and a method by the same name. In this case, the Smalltalk code cannot depend on the dynamic translation mechanism (which actually looks for either a field or method name to match), but instead make it explicit, which operation is wanted: Use:

    frame getFieldByName:'myField'

to read a field, and:

    frame setFieldByName:'myField' value:123.

to write the field.

If there are both fields and methods by the same name, and you use the non-explicit call, the bridge will always assume that you want to call the getter/setter and perform a method call.

Callbacks from Java[Bearbeiten]

Sometimes you may want to execute a piece of Smalltalk code during the execution of the Java code. For example, we may want to install a Smalltalk observer to be notified when a button on a Java GUI was pressed, or some other callback from a Java framework.

The following code registers a Smalltalk block as a callback for a mouse press event of a button:

    listener := MouseListener new.
    listener mousePressed:[ Transcript showCR:'Hello from Java' ].

The above creates the callback and the listener, which can now be registered on a button:

    button addMouseListener:listener.

Now, with the press of the button in the Java GUI, the Smalltalk block will be executed and writes "Hello from Java" to the Smalltalk console. Of course, any other (Smalltalk-)action code can be made to run via this mechanism.

But be aware, that the callback is possibly called later (when the elementary action, which installed the code, has already finished long ago). Also, as the Java code execution is not synchronized with any of your expecco action execution, the callback may also be called at any arbitrary time, even at times when no activity at all is executed on the expecco side. If you forget to cleanup, and the Java object is still alive, it may even be called after you have finished your test run (if you keep the Java Bridge handle around and alive, for example in an expecco environment variable).

So the Smalltalk callback code should not depend on any particular elementary action to be currently running, but instead in most cases write some information into a shared data container, preferably an instance of "SharedQueue", which is thread safe. Then, some other action (an elementary action) would read-wait and read events from that shared queue.

make sure that your test correctly cleans up any such callbacks afterwards. As a last resort, use the "Shutdown Bridge Connection" menu item, which closes the bridge connection, and thereby - as a side effect - removes any leftover callbacks. It does close the connection, and any remaining Java proxy object handles become invalid, though.

Another example, using an observer could look like:

    observer := java Observer new.
    observer update:[:sourceObservable :argument| 
        argument notNil ifTrue:[ Transcript showCR:('I was notified with: ',argument toString) ]
        ifFalse:[ Transcript showCR:'I was notified and the argument was nil' ].
    ].
    myObservable addObserver:observer.

When the observable calls "notifyObservers", the Smalltalk block will be executed.

Exceptions in Java[Bearbeiten]

Exceptions on the Java side are signalled back to the Smalltalk side and raise a corresponding exception there. However, on the Java side, the call stack which lead to the exception has already been unwound at that time (Java exceptions are not proceedable). So a proceed in the Smalltalk-side exception handler only affects the Smalltalk caller, but may leave the Java side in an undefined state.


Examples[Bearbeiten]

This example creates a JFrame with one button inside. Then a MouseListener is created and registered on the button. When the button is pressed, the title of the window changes to "onPressed" and the Transcript shows the message "onPressed". When the button is released, the title of the window is changed to "onReleased" and the Transcript shows "onReleased". If the button lost the mouse focus, the bridge will exit (disconnect), and the Java side is terminated.

    |java frame button listener|
 
    "/getting a bridge
    java := JAVA::JavaBridge newWithServer.

    "/creating a new frame and button object
    frame := java javax_swing_JFrame new.
    button := java JButton new:'Click'.

    "/creating a new mouse listener and adding callback blocks
    listener := java MouseListener new.
    listener mousePressed:[ Transcript showCR:'onPress'. frame setTitle:'onPressed' ].
    listener mouseReleased:[ Transcript showCR:'onReleased'. frame setTitle:'onReleased' ].
    listener mouseExited:[ Transcript showCR:'onExited'. java closeBridge. ].

    "/register the mouse listener on the button and make the frame with button visible
    button addMouseListener:listener.
    frame add:button.
    frame setSize:300 y:100.
    frame setVisible: true.

Simple RMI Call[Bearbeiten]

The next example is written in JavaScript syntax. It shows how an RMI host is queried for an RMI object and then the "getHello" method is called on it. The following code is not directly executable: you must replace the path to the compiled MyRemoteObject class with the directory containing the class file, and replace the RMI host name with a real one in your network:

    var java, reg, myRemoteObject, callResult;

    // Start a local Java VM and connect the Communication-Bridge to it
    java = JAVA::Java.singletonInstance;  

    // Add the class path where the description class of the shared RMI object can be found. RMI could also load the class from the server, but then we would need a RMI SecurityManager with download rights
    java.bridgeSide.addClassSearchPath("my\added\class\path"); 

    // java.rmi.registry.LocateRegistry gets us the RMI Registry on the host
    reg = java.java_rmi_registry_LocateRegistry.getRegistry("rmiHost",4567);  

    // get the rmi object
    myRemoteObject = reg.lookup("myObject");   

    // get the hello string that was written by the RMI server into the rmi object
    callResult = myRemoteObject.getHello();

The RMI server written in Java:

RMIServer.java:

    import java.rmi.AlreadyBoundException;
    import java.rmi.RemoteException;
    import java.rmi.registry.LocateRegistry;
    import java.rmi.registry.Registry;

    public class RMIServer {

        public static void 
        main( String[] args ) throws RemoteException, AlreadyBoundException, InterruptedException {
            int port = 4567;

            if(args.length > 0)
                port = Integer.parseInt(args[0]);
                    
            Registry reg = LocateRegistry.createRegistry(port);
            reg.bind("myObject", new MyRemoteObject("Hello from RMIServer: "+port));
            while(true) {
                Thread.sleep(100);
            }
        }
    }

The implementation of the shared RMI object written in Java:

MyRemoteObject.java
    import java.io.Serializable;
    import java.rmi.Remote;

    public class MyRemoteObject implements Remote,Serializable {
            
        private static final long serialVersionUID = 1L;
            
        private String hello;
            
        public MyRemoteObject(String hello) {
            this.hello = hello;
        }

        public String getHello(){
            return hello;
        }
    }


API[Bearbeiten]

JAVA::Java[Bearbeiten]

class protocol[Bearbeiten]

newWithServer[Bearbeiten]
  • This will start a local Java VM, running the Java Bridge, and establishes a connection on a random free port.
A new connected instance of JAVA::Java class is returned.
newWithServerForJavaPath:aJavaPathFilename[Bearbeiten]
  • This is the same as newWithServer but the path to the Java executable can be specified. The Java VM version must be 1.6 or higher to run the Java Bridge.
aJavaPathFilename - must be a instance of Filename
   Smalltalk: JAVA::Java newWithServerForJavaPath:('my\path\to\java.executable'asFilename).
   JavaScript: JAVA::Java.newWithServerForJavaPath("my\path\to\java.executable".asFilename());
newConnectedTo:aHostString port:aPortNumber withTimeout:aTimeoutSeconds[Bearbeiten]
  • This is used to connect to a running Java Bridge on the network. The Java Bridge must be started in server mode on the remote host. After connecting a new connected instance of JAVA::Java is returned.
aHostString - the hostname or IP of the remote machine as String
aPortNumber - the port on which the remote machine is listening as Number
aTimeoutSeconds - a connect timeout in seconds as Number
   Smalltalk: JAVA::Java newConnectedTo:'myHostName' port:4567 withTimeout:30.
   JavaScript: JAVA::Java.newConnectedTo_port_withTimeout("myHostName",4567,30);
newWaitingForConnectOnHost:aListeningAddressString port:aListeningPortNumber withTimeout:aTimeoutSeconds[Bearbeiten]
  • This is used to wait for incoming connections of a running Java Bridge on the network. The Java Bridge must be started in client mode on the remote host. After connecting a new connected instance of JAVA::Java is returned.
deprecated: aListeningAddressString - no longer used. Can be nil.
aListeningPortNumber - the port on which to listen for incoming connections as Number
aTimeoutSeconds - a connect timeout in seconds as Number, If nil it will wait endless.
singletonInstance[Bearbeiten]
  • This will call newWithServer for the first time and then always returns the same connected JAVA::Java instance until the connection was closed, then a new connected instance is returned.
exitAllInstances[Bearbeiten]
  • This will close all instances of JAVA::Java.

instance protocol[Bearbeiten]

addJarByPath:aPath[Bearbeiten]
  • Adds a jar to the class path of the running Java VM. If the jar depends on other jars or libraries you have to add them too.
aPath - the path to the jar file as String.
addLibraryByPath:aPath[Bearbeiten]
  • Adds a library to the library path of the running Java VM. If the library depends on other libraries you have to add them too.
aPath - the path to the library file as String.
isConnected[Bearbeiten]
  • Tests if a connection is still established.
return: - true if the connection is still established, else false.
isAlive[Bearbeiten]
  • Tests if a connection is still responding.
return: - true if the connection is still alive, else false. Does a message round trip.
closeBridge[Bearbeiten]
  • This will close the bridge connection. Depending on in which mode the Java Bridge was started, the Java VM is also closed (-keepAlive startparameter not set).
exit[Bearbeiten]
  • Same as closeBridge.

See Also[Bearbeiten]

The DOTNET Interface Plugin & Library, which implements a likewise interface for .NET applications/libraries.
Version 2 of the Java Interface Library


Back to Plugins
Back to Online Documentation.



Copyright © 2014-2024 eXept Software AG