1% BEGIN LICENSE BLOCK
2% Version: CMPL 1.1
3%
4% The contents of this file are subject to the Cisco-style Mozilla Public
5% License Version 1.1 (the "License"); you may not use this file except
6% in compliance with the License.  You may obtain a copy of the License
7% at www.eclipse-clp.org/license.
8% 
9% Software distributed under the License is distributed on an "AS IS"
10% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.  See
11% the License for the specific language governing rights and limitations
12% under the License. 
13% 
14% The Original Code is  The ECLiPSe Constraint Logic Programming System. 
15% The Initial Developer of the Original Code is  Cisco Systems, Inc. 
16% Portions created by the Initial Developer are
17% Copyright (C) 2006 Cisco Systems, Inc.  All Rights Reserved.
18% 
19% Contributor(s): 
20% 
21% END LICENSE BLOCK
22
23\newcommand{\jarlocation}{{\tt /lib/eclipse.jar}}
24\newcommand{\docslocation}{{\tt /doc/javadoc/JavaEclipseInterface/index.html}}
25\newcommand{\exampleslocation}{{\tt /doc/examples/JavaInterface}}
26
27% Index entries
28%
29% classpath
30% EclipseConnection interface
31% EclipseEngine interface
32% EmbeddedEclipse class
33% RemoteEclipse class
34% OutOfProcessEclipse class
35% data types 
36% equals() method
37% rpc() method
38% queues
39% queues, opening
40% queues, closing
41% EXDR
42% QueueListener interface
43
44
45
46
47\chapter{Using the Java-{\eclipse} Interface}
48\label{chapjava}
49%HEVEA\cutdef[1]{section}
50The Java-{\eclipse} Interface is a general-purpose tool for
51interfacing {\eclipse} with Java, Sun's popular object-oriented
52platform-independent programming language. It could be used for
53example to write a Java graphical front-end to an {\eclipse} optimisation
54program or to interface {\eclipse} with a commercial application
55written in Java. This document assumes a moderate level of programming
56in Java (e.g. how to use classes, packages, interfaces etc. and some
57knowledge of the {\it java.util}, {\it java.io} and {\it java.net}
58libraries) and a basic knowledge of how to interact with {\eclipse}
59(e.g.\ how to execute a goal, nondeterminism, what lists are
60etc.). There are also some diagrams in UML notation, but these are not
61crucial to the reader's understanding.
62
63Section \ref{sec:ji-getting-started} is intended to get you started
64quickly by running the example program {\tt QuickTest.java}. Section
65\ref{sec:ji-closer-look} gives a brief overview of the functionality
66of the Java-{\eclipse} interface by taking a closer look at how {\tt
67QuickTest.java} works. In the other sections of the document you will
68learn how to write Java programs which can:
69\begin{itemize}
70
71\item Manipulate {\eclipse} terms and other data in Java (Section
72\ref{sec:ji-terms-in-java}).
73\item Execute goals in {\eclipse} and use the results of this
74computation in Java (Section \ref{sec:ji-calling-goals}).
75\item Transfer data between Java and {\eclipse} using queues\index{queues}.
76(Section \ref{sec:ji-using-queue-streams}).
77\item Initialise and terminate different kinds of connections between {\eclipse} and Java. (Section \ref{sec:ji-managing-eclipse-connections}).
78\end{itemize}
79
80Throughout this document, {\tt <eclipse\_dir>} stands for the root
81location of your {\eclipse} installation. Detailed {\tt
82javadoc}-generated HTML descriptions of the API provided by the {\tt
83com.parctechnologies.eclipse} package can be found at:
84\begin{quote}
85\ahref{../javadoc/JavaEclipseInterface/index.html}{{\tt <eclipse\_dir>}\docslocation}
86\end{quote}
87You may wish to browse the API documentation after reading this
88document to obtain more detailed descriptions of classes and
89interfaces in the package.
90
91\section{Getting Started}
92\label{sec:ji-getting-started}
93At the end of this section you will run the simple Java program {\tt
94QuickTest.java} which uses {\eclipse}. First of all though
95you need to check that your Java SDK version is recent enough and that
96your classpath correctly set up.
97\subsection{Check your Java SDK version}
98Use of the Java-{\eclipse} Interface requires an installation of the
99Java SDK (Standard Developer's Kit) version 1.2.2 or later. If your
100Java SDK installation is an earlier version than this or you do not
101have the Java SDK on your machine, the latest version can be
102downloaded from Sun Microsystems Inc. (\ahrefurl{http://www.sun.com}).
103
104\subsection{Make the {\tt com.parctechnologies.eclipse} package available in your class path}
105The Java-{\eclipse} Interface consists mainly of a Java package which is
106used as a library by the Java programs you will write. This package is
107included as a {\tt .jar} file located within the {\eclipse} distribution at:
108\begin{quote}
109{\tt <eclipse\_dir>}\jarlocation
110\end{quote}
111You are free to copy {\tt eclipse.jar} to a more convenient
112location. However, to compile or run any Java programs which use the
113package you must include the full path of {\tt eclipse.jar} in your
114classpath\index{classpath}. For more information on using the classpath, please consult
115your Java documentation.
116
117% this section no longer needed. 
118
119%\subsection{Ensure that the libraries path is set correctly}
120%During the operation of {\eclipse}, shared libraries/DLLs may need to
121%be loaded dynamically. For this to occur, an environment variable 
122%needs to be altered so that these are available. The details are
123%platform-specific.
124
125%\begin{itemize}
126%\item On UNIX systems, the {\tt LD\_LIBRARY\_PATH}
127%environment variable must include the path:
128%\begin{quote}
129%{\tt <eclipse\_dir>/lib/<architecture\_os>/}
130%\end{quote}
131%where {\tt <architecture\_os>} is for example {\tt i386\_linux} or 
132%{\tt sparc\_sunos5}.
133%\item On Windows operating systems, the {\tt PATH} environment variable must contain the path:
134%\begin{quote}
135%\begin{verbatim}
136%<eclipse_dir>\lib\i386_nt\
137%\end{verbatim}
138%\end{quote}
139%This setting should be made using the Windows Control
140%Panel. Alternatively, the command starting the Java process can alter
141%PATH before starting Java. Another option is to move the {\eclipse}
142%DLLs to a system directory.
143%\end{itemize}
144
145\subsection{Compile and run {\tt QuickTest.java}}
146\label{sec:ji-testing-ji}
147To test that everything is working as it should be, and to see a quick
148example of the Java-{\eclipse} Interface at work, try compiling and
149running the Java program {\tt QuickTest.java}. This starts up an
150{\eclipse} from Java and tells it to write a message to {\tt stdout}. The
151program can be found at
152\begin{quote}
153\ahref{../examples/JavaInterface/QuickTest.java}{{\tt <eclipse\_dir>}\exampleslocation {\tt /QuickTest.java}}
154\end{quote}
155
156After compilation, to run the program, start the Java interpreter as
157you normally would but before the name of the class, supply the
158command line option
159\begin{quote}
160{\tt -Declipse.directory=<eclipse\_dir>}
161\end{quote}
162This tells Java where to find the {\eclipse} installation, so it can run
163{\eclipse}. {\bf You should use this command line options when running
164all other examples in this document}. When you run {\tt
165QuickTest.java}, you should get a single line of output: {\tt hello
166world}. How {\tt QuickTest.java} works is explained in Section
167\ref{sec:ji-closer-look}.
168
169\section{Functionality overview: A closer look at {\tt QuickTest.java}}
170\label{sec:ji-closer-look}
171
172To give a broad overview of how the Java-{\eclipse} Interface works,
173we take a closer look at {\tt QuickTest.java}. Here is the Java source
174code from {\tt QuickTest.java}.
175\begin{verbatim}
176import com.parctechnologies.eclipse.*;
177import java.io.*;
178
179public class QuickTest
180{
181  public static void main(String[] args) throws Exception
182  {
183    // Create some default Eclipse options
184    EclipseEngineOptions eclipseEngineOptions = new EclipseEngineOptions();
185
186    // Object representing the Eclipse engine
187    EclipseEngine eclipse;
188
189    // Connect the Eclipse's standard streams to the JVM's
190    eclipseEngineOptions.setUseQueues(false);
191
192    // Initialise Eclipse
193    eclipse = EmbeddedEclipse.getInstance(eclipseEngineOptions);
194
195    // Write a message
196    eclipse.rpc("write(output, 'hello world'), flush(output)");
197
198    // Destroy the Eclipse engine
199    ((EmbeddedEclipse) eclipse).destroy();
200  }
201}
202
203\end{verbatim}
204
205The structure of the {\tt main} method in {\tt QuickTest.java}
206contains elements which will appear in any Java code which uses the
207Java-{\eclipse} interface. These are as follows:
208
209\subsubsection*{Always import the {\tt com.parctechnologies.eclipse} package}
210Note the first line using {\tt import}. We need to have this in every
211Java source file which uses the Java-{\eclipse} Interface so that it can
212load classes from the package.
213
214\subsubsection*{Declare a reference to an {\it EclipseConnection} or an {\it EclipseEngine}}
215
216{\it EclipseConnection} \index{EclipseConnection interface} and its
217subinterface {\it EclipseEngine} \index{EclipseEngine interface} are Java
218interfaces which contain the methods used when interacting with {\eclipse}.
219
220\subsubsection*{Create an object which implements {\it EclipseConnection} or {\it EclipseEngine}}
221There are a number of classes which implement these interfaces. In the case
222of {\tt QuickTest.java} we use an instance of {\it EmbeddedEclipse}
223\index{EmbeddedEclipse class}. The initialisation of these implementing
224classes varies from class to class. In the case of {\it EmbeddedEclipse}
225initialisation is done by creating and configuring an {\it
226EclipseEngineOptions} object and using this in an invocation of the {\it
227EmbeddedEclipse} class' static method {\tt getInstance}.
228
229\subsubsection*{Interact with {\eclipse} using methods in the {\it EclipseConnection} or {\it EclipseEngine} interface}
230
231We interact with the {\eclipse} engine by invoking methods on the object
232which implements {\it EclipseConnection} \index{EclipseConnection
233interface} or {\it EclipseEngine} \index{EclipseEngine interface}. In the
234case of {\tt QuickTest.java} we invoke the {\tt rpc}\index{rpc() method} method, which causes
235the {\eclipse} to execute a goal, in this case one which simply prints a
236message.
237
238\subsubsection*{Terminate interaction with the {\eclipse}}
239In order to clean up, after the Java program has finished interacting
240with {\eclipse}, the interaction should be terminated. Like
241initialisation, how this termination is done varies among the classes
242which implement the {\it EclipseConnection} and {\it EclipseEngine}
243interfaces.  In the case of {\tt QuickTest.java}, termination is done
244by invoking the {\tt destroy} method on the {\it EmbeddedEclipse}
245object.\index{EmbeddedEclipse class}
246
247\section{Java representation of {\eclipse} data}
248\label{sec:ji-terms-in-java}
249\index{{data types}, {Java}}
250The Java-{\eclipse} Interface uses a set of conventions and Java classes so that data
251types common in {\eclipse} can be represented. Representing {\eclipse} data types is useful for:
252\begin{itemize}
253\item Constructing compound goals to be sent to {\eclipse} for execution.
254\item Deconstructing the results of {\eclipse}'s computation, which are returned as a compound goal.
255\item Communicating compound terms and other data via queues\index{queues}. 
256\end{itemize}
257More details on these tasks will be provided in Sections
258\ref{sec:ji-calling-goals} and \ref{sec:ji-using-queue-streams}, but it is first necessary to understand how {\eclipse} data is represented in Java.
259
260\subsection{General correspondence between {\eclipse} and Java data types}
261\label{sec:ji-type-correspondence}
262Not all {\eclipse} data types are represented: for example, at present
263the {\eclipse} type {\tt rational} has no Java equivalent. However, all
264the most useful {\eclipse} types have a corresponding Java class.  Table
265\ref{tab:ec-java-data} gives the general correspondence between those
266{\eclipse} data types which are supported and the Java classes or
267interfaces which are used to represent them. The {\eclipse} types/Java
268classes which appear in the table are those which map to or from 
269the {\eclipse} external data representation (EXDR)\index{EXDR} definition.
270
271\begin{table}[htbp!]
272\begin{center}
273\begin{tabular}{|l|l|}
274\hline 
275{\eclipse} data type	 	& Java class/interface 		\\
276\hline
277{\tt atom}		& {\it Atom}			\\
278\hline
279{\tt compound} 		& {\it CompoundTerm}		\\
280\hline
281{\tt integer}		& {\it java.lang.Integer}	\\
282			& {\it java.lang.Long}	\\
283\hline
284{\tt list}		& {\it java.util.Collection}	\\
285\hline
286{\tt float}		& {\it java.lang.Double}	\\
287			& {\it java.lang.Float}		\\
288\hline
289{\tt string}		& {\it java.lang.String}	\\
290\hline
291{\tt variable}		& {\it null}	\\
292\hline
293\end{tabular}
294\end{center}
295\caption{\label{tab:ec-java-data}The correspondence between {\eclipse} and Java data types. The Java classes are within the {\tt com.parctechnologies.eclipse} package unless otherwise specified.} 
296\end{table}
297 
298
299The general rule is that you can send data to {\eclipse} by passing
300the relevant method an instance of the Java class corresponding to the
301{\eclipse} data type you want on the {\eclipse} side. When data comes
302back from {\eclipse} it will be an instance of {\it java.lang.Object}
303but this can be cast to the relevant Java class, which must either be
304known beforehand or determined e.g. using the {\tt getClass()} method.
305
306There are also a number of peculiarities for certain cases which we
307now explain.
308
309\subsection{Atoms and compound terms}
310\label{sec:ji-atoms-and-terms}
311Atoms are simple: these are constructed in Java using the constructor
312of the {\it Atom} class: the string parameter of the constructor
313becomes the atom symbol. Although the Java interface {\it CompoundTerm} is
314listed above, compound terms (except lists) are usually constructed
315using the {\it CompoundTermImpl} class, which implements {\it
316CompoundTerm}. Incidentally, {\it Atom} also implements {\it CompoundTerm}, even though strictly speaking {\eclipse} atoms are not compound. Here is an
317example of {\it CompoundTermImpl} at work:
318
319\begin{verbatim}
320  // Construct a term in Java to represent the Eclipse term foo(a, b, 3).
321  private static CompoundTerm construct_term()
322  {
323    Atom a = new Atom("a");
324    Atom b = new Atom("b");
325    Integer numberThree = new Integer(3);
326    CompoundTerm theTerm = new CompoundTermImpl("foo", a, b, numberThree);
327
328    return(theTerm);
329  }
330\end{verbatim}
331This method is taken from the example Java program \ahref{../examples/JavaInterface/DataExample1.java}{{\tt DataExample1.java}}
332which can be found in the examples directory {\tt
333<eclipse\_dir>}\exampleslocation. The rest of the program sends
334{\eclipse} a goal which tells it to write the term created by {\tt
335construct\_term()} to {\tt stdout}.
336
337In this example we use an {\it CompoundTermImpl} constructor whose
338first parameter is a string which becomes the functor of the term. The
339remaining parameters are instances of {\it java.lang.Object}. They may
340be instances of any class or interface which appears in Table
341\ref{tab:ec-java-data}. These become the arguments of the term. {\it
342CompoundTermImpl} has a number of other convenient constructors. See
343the API documentation for details of these.
344
345Note that the object returned by {\tt construct\_term()} is declared
346not as a {\it CompoundTermImpl} but as a {\it
347CompoundTerm}. CompoundTerm is the Java interface for objects
348representing compound terms. Anything which implements CompoundTerm
349can be sent to {\eclipse} as a compound term.
350
351Instead of using {\it CompoundTermImpl}, you may wish to implement
352{\it CompoundTerm} yourself. The benefit of this is that you can pass
353any object implementing {\it CompoundTerm} to an {\tt rpc}\index{rpc() method} invocation, and
354it can supply a functor and arguments without the unnecessary creation
355of another object. To do this you may wish to subclass {\it
356AbstractCompoundTerm}.
357
358\subsection{Lists}
359
360Whenever you want to construct a list for {\eclipse} or deconstruct a
361list coming from {\eclipse}, you use the {\it java.util.Collection}
362interface. Look at the following method, taken from the example Java
363program \ahref{../examples/JavaInterface/DataExample2.java}{{\tt DataExample2.java}} (which can be found in the examples
364directory {\tt <eclipse\_dir>}\exampleslocation).
365
366\begin{verbatim}
367  // Construct a collection in Java to represent the Eclipse 
368  // list [1, foo(3.5), bar].
369  private static Collection construct_collection()
370  {
371      Collection theCollection = new LinkedList();
372
373      theCollection.add(new Integer(1));
374      theCollection.add(new CompoundTermImpl("foo", new Double(3.5)));
375      theCollection.add(new Atom("bar"));
376
377      return(theCollection);
378  }
379\end{verbatim}
380
381If you study, compile and run {\tt DataExample2.java} you will see
382that the collection is indeed translated into the required {\eclipse}
383list. You will also see that order is maintained in the sense that the
384order of elements as they appear in the {\eclipse} list will equal the
385collection's iterator order (the converse is true if the data is
386coming from {\eclipse} to Java).
387
388Also note that the {\eclipse} empty list ({\tt []}) is represented in
389Java by the constant {\it java.util.Collections.EMPTY\_LIST}.
390
391\subsection{Floats and Doubles}
392
393The {\eclipse} data type {\tt float} is always converted to {\it
394java.lang.Double} in Java. However, {\eclipse} can be sent an instance
395of {\it java.lang.Double} or {\it java.lang.Float}: both will be
396converted to {\tt float} in {\eclipse}. One value of {\it
397java.lang.Double} and {\it java.lang.Float} has no counterpart in
398{\eclipse}: the not-a-number (NaN) value. Infinite values can be sent
399in either direction.
400
401\subsection{Integers}
402{\eclipse} can be sent instances of either {\it java.lang.Integer}
403(32-bit integers) or {\it java.lang.Long} (64-bit integers). Both of
404these will be translated to type {\tt integer} on the {\eclipse} side.
405When {\eclipse} sends data to Java, it will decide between the two
406classes depending on the number of bits needed for the integer. So for
407example, if the number is small enough to fit in an Integer, that is
408what will be returned. Note that therefore, the type of number
409coming back from {\eclipse} cannot be relied upon to be of one type or
410the other if it could fall on either side of the 32-/64-bit boundary.
411
412If you require a set of numbers coming from {\eclipse} to be all of
413one Java type e.g. long, then the best approach is to cast the object
414returned by {\eclipse} to an instance of {\it java.lang.Number} and
415then invoke the appropriate conversion method e.g. {\tt longValue()}.
416
417\subsection{Variables}
418\label{sec:ji-variables-null}
419The Java {\it null} token is used to represent any variables being
420sent to {\eclipse}. All variables coming from {\eclipse} will appear as
421{\it null}. The limitations of this are discussed in more detail in
422Section \ref{sec:ji-calling-goals}.
423
424
425\subsection{The {\tt equals()} method}
426The {\tt equals()} method has been overridden for {\it
427AbstractCompoundTerm} and therefore also for {\it Atom} and {\it
428CompoundTermImpl}. The implementation returns {\tt true} iff the
429parameter {\it Object} implements {\it CompoundTerm} and its functor
430and arity are equal to those of the {\it AbstractCompoundTerm}, and
431pairwise invocations of {\tt equals()} return {\tt true} between each
432of the {\it AbstractCompoundTerm}'s arguments and the corresponding
433argument of the parameter object.
434
435
436
437\section{Executing an {\eclipse} goal from Java and processing the result}
438\label{sec:ji-calling-goals}
439The {\it EclipseConnection} \index{EclipseConnection interface} interface
440provides a single method {\tt rpc}\index{rpc() method} (Remote Predicate Call) for executing
441goals in the {\eclipse}. This method takes as a parameter the goal to be
442executed. How to construct this parameter is dealt with in Section
443\ref{sec:ji-rpc-parameter}. Section \ref{sec:ji-rpc-return} explains
444how to deal with the results returned by {\tt rpc}\index{rpc() method}. Finally, some more
445details about the execution of the goal are given in Section
446\ref{sec:ji-goal-execution}. 
447
448\subsection{Passing the goal parameter to {\tt rpc}\index{rpc() method}}
449\label{sec:ji-rpc-parameter}
450There are main two variants of {\tt rpc}\index{rpc() method} which differ in the class of the
451goal parameter.
452
453The simplest way to use {\tt rpc}\index{rpc() method} is to pass it an instance of {\it
454java.lang.String} which should be the goal as it would be typed into
455the {\eclipse} command line. Just like with the {\eclipse} command line,
456the goal can be a conjunction of several subgoals. An example of this
457is the use of {\tt rpc}\index{rpc() method} in the example program {\tt
458QuickTest.java}. Also please note a full stop is not necessary.
459
460The string-parameter {\tt rpc}\index{rpc() method} variant is somewhat inefficient and it
461is also inflexible because creating goals dynamically, or goals
462involving strings is tricky. It should really only be used for short
463simple goals. A more flexible and efficient alternative is to invoke
464{\tt rpc}\index{rpc() method}, passing it a parameter object which implements the {\it
465CompoundTerm} interface (discussed in Section
466\ref{sec:ji-atoms-and-terms}). In this case the term becomes the
467goal. Here is an example of using this version of {\tt rpc}\index{rpc() method}, taken
468from
469\ahref{../examples/JavaInterface/DataExample1.java}{{\tt DataExample1.java}}.
470
471\begin{verbatim}
472    CompoundTerm a_term = construct_term();
473
474    // Get Eclipse to write the term to stdout and flush 
475    eclipse.rpc(
476                new CompoundTermImpl(",",
477                              new CompoundTermImpl("write", 
478                                            new Atom("output"), a_term),
479                              new CompoundTermImpl("flush", new Atom("output"))
480                              )
481                );
482\end{verbatim}
483Using this variant is a bit more cumbersome (e.g.\ the creation of a
484new {\it CompoundTermImpl} for the conjunction of goals in the above
485example) but it would be useful for large goals constructed
486dynamically. There are also a number of ``convenience'' {\tt rpc}\index{rpc() method}
487methods, where instead of providing a {\it CompoundTerm}, you provide
488the objects from which the term is made. See the API documentation for
489more details of these variants.
490
491\subsection*{Note: \bipref{yield/2}{../bips/kernel/externals/yield-2.html}, \bipref{remote_yield/1}{../bips/kernel/externals/remote_yield-1.html} and {\tt rpc}\index{rpc() method}}
492
493The builtins \bipref{yield/2}{../bips/kernel/externals/yield-2.html} and \bipref{remote_yield/1}{../bips/kernel/externals/remote_yield-1.html} should not be
494executed anywhere within an {\tt rpc}\index{rpc() method} goal, as they will cause the
495goal to return prematurely.
496
497\subsection{Retrieving the results of an {\tt rpc}\index{rpc() method} goal execution}
498\label{sec:ji-rpc-return}
499
500The {\tt rpc}\index{rpc() method} method returns an object which implements {\it
501CompoundTerm}. This object is the Java representation of the goal term, with
502the solution substitution applied to its variables. 
503
504The solution substitution can be deconstructed using the returned {\it
505CompoundTerm}'s {\tt arg} method. This method takes an integer (the argument
506position) and returns an Object which is the Java representation of
507the {\eclipse} argument at that position.
508
509In the returned {\it CompoundTerm} instantiated variables are replaced
510with their instantiations. Hence even if the variable was named in the
511initial goal, its instantiation is identified in the returned goal by
512its {\it position} rather than its name. Uninstantiated variables in
513the returned {\it CompoundTerm} are represented using the Java {\it null}
514token.
515
516If a variable in the {\tt rpc} goal becomes instantiated to an {\eclipse}
517data type which does not have an equivalent EXDR type (such as breal), then
518in the returned {\it CompoundTerm} it will appear as the Java {\it null}
519token.
520
521The following Java code is an example of how the returned {\it CompoundTerm}
522can be deconstructed to extract the variable substitutions.
523\begin{verbatim}
524...
525    CompoundTerm result = eclipse.rpc("X = Q, Y is 2.1 + 7");
526
527    // The top-level functor of the goal term is ",". 
528    // The first and second arguments of the goal term are the two subgoals
529    // and we can safely cast these as CompoundTerms.
530    CompoundTerm firstGoal = (CompoundTerm) result.arg(1);
531    CompoundTerm secondGoal = (CompoundTerm) result.arg(2);
532    // X is the first argument of the first goal.
533    Object firstGoalFirstArg = firstGoal.arg(1);
534    // Y is the first argument of the second goal.
535    Object secondGoalFirstArg = secondGoal.arg(1);
536
537    System.out.println("X = "+firstGoalFirstArg);
538    System.out.println("Y = "+secondGoalFirstArg);
539...
540\end{verbatim}
541The output will be:
542\begin{verbatim}
543X = null
544Y = 9.1
545\end{verbatim}
546\subsubsection*{Other ways an {\tt rpc}\index{rpc() method} invocation can terminate}
547Apart from succeeding and returning a {\it CompoundTerm}, {\tt rpc}\index{rpc() method} can throw
548exceptions. If the goal fails, an instance of {\it Fail} is
549thrown. So to test for failure you must catch this exception.  An
550instance of {\it Throw} is thrown if {\eclipse} itself throws an
551error.
552
553
554\subsection{More details about {\tt rpc}\index{rpc() method} goal execution}
555\label{sec:ji-goal-execution}
556\subsubsection*{Variables}
557As explained in Section \ref{sec:ji-variables-null}, {\eclipse}
558variables are always represented by the {\it null} token, when {\tt
559rpc}\index{rpc() method} is invoked with a {\it CompoundTerm} parameter. When used in an
560{\tt rpc}\index{rpc() method} goal, each {\it null} token represents a different
561variable. Using {\it CompoundTerm} you cannot represent a goal with
562multiple occurrences of a single variable. So, for example the
563following Java code will output {\tt q(b, b)} for the first {\tt rpc}\index{rpc() method}
564invocation and {\tt q(a, b)} for the second.
565
566\begin{verbatim}
567...
568
569  eclipse.rpc("assert(q(a, b))");
570  eclipse.rpc("assert(q(b, b))");
571
572  System.out.println(eclipse.rpc("q(X, X)"));
573  System.out.println(eclipse.rpc(new CompoundTermImpl("q", null, null)));
574
575...
576\end{verbatim}
577
578\subsubsection*{Nondeterminism}
579
580The {\tt rpc}\index{rpc() method} feature does not support the handling of nondeterminism
581in the execution of the {\eclipse} goal. If the goal succeeds, control
582is returned to Java immediately after the first solution to the goal
583is found in {\eclipse}. All choice-points thereafter are ignored. So,
584for example, although the first {\eclipse} goal below would leave
585choice-points, it would be equal in effect to the second.
586\begin{verbatim}
587...
588result = eclipse.rpc("member(X, [1, 2, 3, 4, 5])");
589...
590result = eclipse.rpc("member(X, [1])");
591\end{verbatim}
592This is not a practical problem. It merely implies that if you are
593using nondeterminism to generate multiple solutions, you should
594collect these on the {\eclipse} side using a meta-level built-in
595predicate such as {\tt findall/3} and then return the result to Java.
596
597\subsubsection*{Concurrent invocations of {\tt rpc}\index{rpc() method}}
598
599Note that the {\tt rpc}\index{rpc() method} method is {\tt synchronized}. Therefore if,
600while one Java thread is currently executing an {\tt rpc}\index{rpc() method} invocation,
601a second Java thread tries to invoke the {\tt rpc}\index{rpc() method} method of the same
602{\it EclipseConnection}, the second thread will block until the first
603thread's {\tt rpc}\index{rpc() method} invocation returns.
604
605\subsubsection*{Nested invocations of {\tt rpc}\index{rpc() method}}
606
607During the execution of the {\tt rpc}\index{rpc() method} method, control
608 is transferred to {\eclipse}. Due to the {\it QueueListener} feature
609 \index{QueueListener interface} which is discussed in Section
610 \ref{sec:ji-using-queue-streams}, control is sometimes temporarily
611 returned to Java before the {\eclipse} execution has finished. It is
612 possible for this Java code itself to invoke {\tt rpc}\index{rpc()
613 method}, thus leading to nested {\tt rpc}\index{rpc() method}
614 invocations. Nested {\tt rpc}\index{rpc() method} invocations should not
615 cause any problems.
616
617\section{Communicating between Java and {\eclipse} using queues\index{queues}} 
618\label{sec:ji-using-queue-streams}
619
620In the Java-{\eclipse} Interface, {\it queues} are one-way data
621streams used for communication between {\eclipse} and Java. These are
622represented on the {\eclipse} side using ``peer queues'', which are 
623I/O streams. The Java-{\eclipse} Interface includes the classes {\it
624FromEclipseQueue} and {\it ToEclipseQueue} which represent these
625queues on the Java side. {\it FromEclipseQueue} represents a queue
626which can be written to in {\eclipse} and read from in Java. A {\it
627ToEclipseQueue} is a queue which can be written to in Java and read
628from in {\eclipse}.
629
630Section \ref{sec:ji-open-close} discusses how queues are opened,
631\index{queues, opening}referenced and closed\index{queues, closing} from either the Java 
632or {\eclipse} sides. We also discuss here how to transfer byte data in both
633directions. However, the programmer need not be concerned with low-level
634data operations on queues: whole terms can be written and read using the
635{\it EXDRInputStream} and {\it EXDROutputStream} classes discussed in
636Section
637\ref{sec:ji-formatting-queue-data}.
638
639Via the {\it QueueListener} feature\index{QueueListener interface}, Java
640code can be invoked (in a sense) from within {\eclipse}. The use of this
641feature is discussed in Section \ref{sec:ji-queue-listeners}. In some
642cases, the standard streams ({\tt stdin}, {\tt stdout} and {\tt stderr}) of
643the {\eclipse} engine will be visible to Java as queues. How to use these
644is discussed in Section \ref{sec:ji-standard-streams}.
645
646\subsection{Opening, using and closing queues\index{queues}}
647\label{sec:ji-open-close}
648\index{queues, opening}
649\index{queues, closing}
650We now explain the standard sequence of events for using
651queues. Opening and closing, can be performed in a single step from
652either the Java or the {\eclipse} side.
653
654\subsubsection*{Opening a queue using Java methods}
655
656{\it FromEclipseQueue} and {\it ToEclipseQueue} do not have public
657constructors. Instead, we invoke {\tt getFromEclipseQueue} or {\tt
658getToEclipseQueue}. This asks the {\it EclipseConnection} object for a
659reference to a {\it FromEclipseQueue} or {\it ToEclipseQueue} instance
660which represents a new queue. To specify the stream for later
661reference, we supply the method with a string which will equal to the
662atom by which the queue is referred to as a stream in {\eclipse}. For
663example the following code creates two queues\index{queues}, one in each direction:
664\begin{verbatim}
665...
666  ToEclipseQueue java_to_eclipse = 
667    eclipse.getToEclipseQueue("java_to_eclipse");
668  FromEclipseQueue eclipse_to_java = 
669    eclipse.getFromEclipseQueue("eclipse_to_java");
670...
671\end{verbatim}
672These methods will create and return new {\it FromEclipseQueue} or
673{\it ToEclipseQueue} objects, and will also open streams with the
674specified names on the {\eclipse} side. No stream in {\eclipse} should
675exist with the specified name. If a stream exists which has this name
676and is not a queue between the Java object and {\eclipse}, the Java
677method throws an exception. If the name is used by a pre-existing
678queue, it is returned, so the {\tt getFromEclipseQueue} and {\tt
679getToEclipseQueue} methods can also be used to retrieve the queue
680objects by name once if they have already been created.
681
682\subsection*{Opening a queue using {\eclipse} predicates}
683\index{queues, opening}
684You can use the {\eclipse} builtin \bipref{peer_queue_create/5}{../bips/kernel/externals/peer_queue_create-5.html} to open a
685queue. Used correctly, these have the same effect as the Java methods
686explained above. For the peer name, you should use the atom returned
687by the {\tt getPeerName()} method of the relevant {\it
688EclipseConnection} instance. The direction should be {\tt fromec} for
689a {\it FromEclipseQueue} and {\tt toec} for a {\it
690ToEclipseQueue}. The queue type should always be {\tt sync}
691(for asynchronous queues, refer to section \ref{ji-async-queue-steams}).
692
693\subsubsection*{Transferring data using Java methods}
694
695On the Java side, once a {\it FromEclipseQueue} has been established,
696you can treat it as you would any instance of {\it
697java.io.InputStream}, of which {\it FromEclipseQueue} is a
698subclass. Similarly, {\it ToEclipseQueue} is a subclass of {\it
699java.io.OutputStream}. The only visible difference is that {\it
700FromEclipseQueue} and {\it ToEclipseQueue} instances may have {\it
701QueueListeners} attached, as is discussed in Section
702\ref{sec:ji-queue-listeners}\index{QueueListener interface}. 
703
704\subsubsection*{Transferring data using {\eclipse} predicates}
705
706On the {\eclipse} side, there are built-in predicates for writing to,
707reading from and otherwise interacting with streams. Any of these may
708be used. Perhaps most useful are \bipref{read_exdr/2}{../bips/kernel/ioterm/read_exdr-2.html} and \bipref{write_exdr/2}{../bips/kernel/ioterm/write_exdr-2.html}; these are explained in Section
709\ref{sec:ji-formatting-queue-data}\index{EXDR}. For the stream ID, you may either use the stream name, or the stream number, obtained for example using \bipref{peer_get_property/3}{../bips/kernel/externals/peer_get_property-3.html}.
710
711\subsubsection*{Note: {\bf always} flush}
712
713When communicating between Java and {\eclipse} using queues\index{queues}, you
714should always invoke the {\tt flush()} method of the Java {\it
715OutputStream} which you have written to, whether it be a {\it
716ToEclipseQueue} or an {\it EXDROutputStream}. Similarly, on the
717{\eclipse} side, {\tt flush/1} should always be executed after
718writing. Although in some cases reading of the data is possible
719without a flush, flushing guarantees the transfer of data.
720% \footnote{Note that in extreme cases, even flushing a {\it
721% ToEclipseQueue} does not guarantee that the data has been fully
722% transferred to {\eclipse}: see Section \ref{sec:ji-toeclipse-remote}}
723
724\subsubsection*{Closing a queue using Java methods}
725
726This is done simply by calling the {\tt close()}\index{queues, closing} method on the {\it
727FromEclipseQueue} or {\it ToEclipseQueue} instance.
728
729\subsubsection*{Closing a queue using {\eclipse} predicates}
730\index{queues, closing}
731This is done by executing the builtin \bipref{peer_queue_close/1}{../bips/kernel/externals/peer_queue_close-1.html}. Note
732that the builtin {\tt close/1} should not be used in this situation,
733as it will not terminate the Java end of the queue.
734
735\subsection{Writing and reading {\eclipse} terms on queues\index{queues}}
736\label{sec:ji-formatting-queue-data}
737Rather than dealing with low-level data I/O instructions such as reading
738and writing bytes, the Java-{\eclipse} Interface provides classes for
739reading and writing whole terms. In the underlying implementation of these
740classes, the EXDR ({\eclipse} eXternal Data Representation) format is
741used\index{EXDR}. This allows {\eclipse} to communicate with other
742languages using a common data type. However, it is not necessary for the
743API user to know about EXDR in detail to use the Java-{\eclipse} Interface
744features discussed in this section.
745
746{\it EXDRInputStream} is a subclass of {\it
747java.io.DataInputStream} which can read EXDR format. {\it
748EXDROutputStream} is a subclass of {\it
749java.io.FilterOutputStream} which can write EXDR format.
750
751\subsubsection*{Initialising {\it EXDRInputStream} and {\it EXDROutputStream}}
752\index{EXDR}
753The constructor for {\it EXDRInputStream} takes an instance of {\it
754java.io.InputStream} as a parameter. This parameter stream is the
755source of the EXDR data for the new stream. If data has been written
756to the {\it InputStream} in EXDR format, you can access it by invoking
757the {\tt readTerm} method of the new {\it EXDRInputStream}. This
758will read the data from the {\it InputStream} and translate the EXDR
759format into the Java representation of the data, which is then
760returned by {\tt readTerm}.
761
762Similarly, the constructor for {\it EXDROutputStream} takes an
763instance of {\it java.io.OutputStream} as a parameter. This parameter
764stream is the destination of the data written to the new stream. You
765write data by invoking the {\tt write} method of the stream. The
766parameter of this method is a Java object representing the piece of
767data to be written. The class of this object can be any of the Java
768classes mentioned in Table \ref{tab:ec-java-data}. The object gets
769translated into EXDR format and this is written to the destination
770{\it OutputStream}.
771
772\subsubsection*{{\it EXDRInputStream} and {\it EXDROutputStream} at work}
773\index{EXDR}
774Although the underlying stream could be any kind of stream (e.g. a
775file stream), the most common use of {\it EXDRInputStream} and {\it
776EXDROutputStream} is to read data from and write data to queues\index{queues} in
777EXDR format. In other words, we usually wrap these classes around {\it
778FromEclipseQueue} and {\it ToEclipseQueue} classes. We now look at an
779example which does just this.
780
781The example is in these two files: 
782\begin{quote}
783\ahref{../examples/JavaInterface/QueueExample1.java}{{\tt <eclipse\_dir>}\exampleslocation {\tt /QueueExample1.java}}\\
784\ahref{../examples/JavaInterface/queue\_example\_1.pl}{{\tt <eclipse\_dir>}\exampleslocation {\tt /queue\_example\_1.pl}}
785\end{quote}
786The Java program's first relevant action is to invoke the {\tt
787compile} method of the {\it EclipseEngine}. This causes the {\eclipse}
788program to be loaded by {\eclipse} engine. After {\tt compile}
789completes, the Java program creates a {\it ToEclipseQueue} and a {\it
790FromEclipseQueue}, with the following lines:
791\begin{verbatim}
792    // Create the two queues
793    java_to_eclipse = eclipse.getToEclipseQueue("java_to_eclipse");
794    eclipse_to_java = eclipse.getFromEclipseQueue("eclipse_to_java");
795\end{verbatim}
796Then in the next two lines we create an {\it EXDROutputStream} to
797format data going to {\tt java\_to\_eclipse} and an {\it
798EXDRInputStream} to format data coming from {\tt
799eclipse\_to\_java}.
800\begin{verbatim}
801    // Set up the two formatting streams
802    java_to_eclipse_formatted = new EXDROutputStream(java_to_eclipse);
803    eclipse_to_java_formatted = new EXDRInputStream(eclipse_to_java);
804\end{verbatim}
805The Java program writes two atoms to {\tt
806java\_to\_eclipse\_formatted}, and then flushes the stream. This
807causes each atom to be translated into EXDR format and the translation
808to then be written on to {\tt java_to_eclipse}. The Java program then
809makes an {\tt rpc}\index{rpc() method} invocation to the {\eclipse} program's only predicate
810{\tt read_2_write_1/0}, which is defined as follows:
811\begin{verbatim}
812read_2_write_1:-
813        read_exdr(java_to_eclipse, Term1),
814        read_exdr(java_to_eclipse, Term2),
815        write_exdr(eclipse_to_java, pair(Term1, Term2)),
816        flush(eclipse_to_java).
817\end{verbatim}
818The built-in \bipref{read_exdr/2}{../bips/kernel/ioterm/read_exdr-2.html} reads a term's worth of data from the
819stream supplied and instantiates it to the second argument. So {\tt
820read\_2\_write\_1/0} reads the two terms from the stream. They are
821then written on to the {\tt eclipse\_to\_java} stream within a {\tt
822pair(...)} functor using the built-in \bipref{write_exdr/2}{../bips/kernel/ioterm/write_exdr-2.html}, and the
823stream is flushed. When the predicate succeeds, the {\tt rpc}\index{rpc() method} invocation
824returns and the term data is on {\tt eclipse\_to\_java} in EXDR
825format. The next step of the java program is the following:
826\begin{verbatim}
827    System.out.println(eclipse_to_java_formatted.readTerm());
828\end{verbatim}
829Since {\tt eclipse\_to\_java} was the {\it FromEclipseQueue} passed as a
830parameter when {\tt eclipse\_to\_java\_formatted} was initialised, the
831{\tt readTerm} method of this object reads the EXDR data which is on
832{\tt eclipse\_to\_java} and converts it into the appropriate Object to
833represent the piece of data, in this case a {\tt CompoundTerm}. This Object is
834then returned by {\tt readTerm}. Hence the output of the program is
835{\tt pair(a,b)}.
836
837\subsection{Using the {\it QueueListener} interface}
838\label{sec:ji-queue-listeners}
839\index{QueueListener interface}
840It may sometimes be useful to have Java react automatically to data
841arriving on a queue from {\eclipse}. An example of this would
842be where a Java program has a graphical display monitoring the state
843of search in {\eclipse}. We would like {\eclipse} to be able to send a
844message along a queue every time an element of the search state
845updates, and have Java react with some appropriate graphical action
846according to the message.
847
848Similarly, {\eclipse} may require information from a Java database at
849some point during its operation. Again we could use a queue to
850transfer this information. If {\eclipse} tries to read from this queue
851when it is empty, we would like Java to step in and supply the next
852piece of data. 
853
854The {\it QueueListener} interface is the means by which handlers are
855attached to queues\index{queues} on the Java side so that Java reacts
856automatically to {\eclipse}'s interaction with the queue.
857
858Any object which implements the {\it QueueListener} interface can be
859attached to either a {\it FromEclipseQueue} or a {\it ToEclipseQueue}, using
860the {\tt setListener} method. The {\it QueueListener} can be removed
861using {\tt removeListener}. Queues\index{Queues} can only have one Java
862listener at any one time. 
863
864The {\it QueueListener} interface has two methods: {\tt dataAvailable}
865and {\tt dataRequest}. 
866
867\begin{description}
868\item[{\tt dataAvailable}] is invoked only if the {\it QueueListener} is 
869  attached to a {\it FromEclipseQueue}. It is invoked when the queue is 
870  flushed on the {\eclipse} side.
871\item[{\tt dataRequest}] is invoked only if the {\it QueueListener} is 
872  attached to a {\it ToEclipseQueue}. It is invoked when {\eclipse} tries
873  to read from the queue when it is empty\footnote{Note that this invocation occurs only if the {\eclipse} side of the queue is empty. If you have written data to the queue on the Java side, but not flushed it, the {\eclipse} side may still be empty, in which case the {\tt dataRequest} method of the listener will be invoked.}.
874\end{description}
875
876Both methods have a single {\it Object} parameter named {\tt
877source}. When they are invoked this parameter is the {\it FromEclipseQueue}
878or {\it ToEclipseQueue} on which the flush or read happened.
879
880There is an example Java program {\tt QueueExample2.java} with an
881accompanying example {\eclipse} program {\tt queue\_example\_2.pl}
882which use {\it QueueListeners} attached to queues going in both
883directions.
884\begin{quote}
885\ahref{../examples/JavaInterface/QueueExample2.java}{{\tt <eclipse\_dir>}\exampleslocation {\tt /QueueExample2.java}}\\
886\ahref{../examples/JavaInterface/queue\_example\_2.pl}{{\tt <eclipse\_dir>}\exampleslocation {\tt /queue\_example\_2.pl}}
887\end{quote}
888After the queues streams are set up on both sides, the Java program
889attaches as listeners a {\it TermProducer} to the {\it ToEclipseQueue}
890and a {\it TermConsumer} to the {\it FromEclipseQueue}. These are both
891locally defined classes which implement {\it QueueListener}. The {\it
892TermProducer}, each time its {\tt dataRequest} method is invoked, sends
893one of five different atoms down its queue in EXDR format\index{EXDR}. The
894{\it TermConsumer}, when its {\tt dataAvailable} method is invoked,
895reads some EXDR data from its queue and translates it into the
896appropriate Java object. It then writes this object out to stdout.
897
898Next, the Java program, using {\tt rpc}\index{rpc() method}, executes the only predicate
899in the {\eclipse} program: {\tt read\_5\_write\_5/0}. This repeats the
900following operation five times: read in a term in EXDR format from the
901relevant incoming stream, write it out in EXDR format with an
902extra functor to the relevant outgoing stream, and flush the
903outgoing stream.
904
905\subsection{Access to {\eclipse}'s standard streams}
906\label{sec:ji-standard-streams}
907If the object representing the {\eclipse} implements the {\it
908EclipseEngine} \index{EclipseEngine interface} interface, then the API user
909may have access to the {\eclipse}'s standard streams (see Section
910\ref{sec:ji-use-queues-flag}). These are returned as {\it
911FromEclipseQueue}s and {\it ToEclipseQueue}s by the methods {\tt
912getEclipseStdin}, {\tt getEclipseStdout} and {\tt getEclipseStderr}.
913
914%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
915\section{Asynchronous Communicating between Java and {\eclipse}\index{queues, asynchronous}} 
916\label{sec:ji-async-queue-streams}
917
918Starting with release 5.9, the {\it OutOfProcessEclipse}
919and {\it RemoteEclipse} variants of the Java-{\eclipse} Interface also support
920asynchronous queues through the class {\it AsyncEclipseQueue}\index{AsyncEclipseQueue}.
921These are essentially socket connections between {\eclipse} and Java, which
922can be used independently of which side has control. 
923
924An {\it AsyncEclipseQueue} queue is opened and closed in the same way as 
925a {\it FromEclipseQueue} or {\it ToEclipseQueue}, but the following
926differences exist:
927\begin{itemize}
928\item an asynchronous queue can be read/written from the Java side
929even while the ECLiPSe side has control, e.g. during an RPC.  This
930obviously has to happen from a different thread than the one that
931executes the RPC.
932\item I/O operations on asynchronous queues can block, they should
933therefore be done from a dedicated thread.
934\item the AsyncEclipseQueue class does not extend InputStream or
935OutputStream and can therefore not be used for I/O directly.  Instead,
936a standard Java InputStream can be obtained from it via the
937getInputStream() method, and an OutputStream via the getOutputStream()
938method.
939\item on the ECLiPSe side, an event can (and should) be raised when
940data arrives from the Java side.  If the ECLiPSe side has control at
941that time, it will handle the event.  Otherwise, the event handling
942may be deferred until ECLiPSe has control back.
943\end{itemize}
944
945\subsection{Opening and closing asynchronous queues}
946\label{sec:ji-async-open-close}
947\index{queues, opening}
948\index{queues, closing}
949Opening and closing can be performed in a single step from
950either the Java or the {\eclipse} side.
951
952\subsubsection*{Opening an asychronous queue using Java methods}
953
954The {\it AsyncEclipseQueue} does not have public
955constructors. Instead, we invoke {\tt getAsyncEclipseQueue}.
956This asks the {\it EclipseConnection} object for a
957reference to an {\it AsyncEclipseQueue} instance
958which represents a new queue. To specify the stream for later
959reference, we supply the method with a string which will equal to the
960atom by which the queue is referred to as a stream in {\eclipse}. For
961example the following code creates such a queue\index{queues}:
962\begin{verbatim} ...
963  AsyncEclipseQueue java_eclipse_async = 
964    eclipse.getAsyncEclipseQueue("java_eclipse_async");
965...
966\end{verbatim}
967Note that this method will only work when the {\tt eclipse} object is
968an {\it OutOfProcessEclipse} or {\it RemoteEclipse}.
969Teh method will create and return a new {\it AsyncEclipseQueue}
970object, and will also open a stream with the
971specified names on the {\eclipse} side. No stream in {\eclipse} should
972exist with the specified name. If a stream exists which has this name
973and is not a queue between the Java object and {\eclipse}, the Java
974method throws an exception. If the name is used by a pre-existing
975queue, it is returned, so the {\tt getAsyncEclipseQueue}
976methods can also be used to retrieve the queue
977objects by name once they have already been created.
978
979\subsection*{Opening an asychronous queue using {\eclipse} predicates}
980\index{queues, opening}
981You can use the {\eclipse} builtin \bipref{peer_queue_create/5}{../bips/kernel/externals/peer_queue_create-5.html} to open a
982queue. Used correctly, these have the same effect as the Java methods
983explained above. For the peer name, you should use the atom returned
984by the {\tt getPeerName()} method of the relevant {\it
985EclipseConnection} instance. The direction should be {\tt bidirect},
986and the queue type should be specified as {\tt async}.
987
988\subsubsection*{Transferring data using Java methods}
989
990Once an {\it AsyncEclipseQueue} has been created, a standard Java
991InputStream can be obtained from it via the getInputStream() method,
992and an OutputStream via the getOutputStream() method.
993These Java streams can be used as you would any instance of {\it
994java.io.InputStream} or {\it java.io.OutputStream}.
995Unlike the synchronous {\it FromEclipseQueue} and {\it ToEclipseQueue},
996I/O on these streams can block, and should therefore be handled by dedicated
997threads. For this reason, the listener-feature is not supported on
998asynchronous queues.
999
1000\subsubsection*{Transferring data using {\eclipse} predicates}
1001
1002On the {\eclipse} side, there are built-in predicates for writing to,
1003reading from and otherwise interacting with streams. Any of these may
1004be used. Perhaps most useful are \bipref{read_exdr/2}{../bips/kernel/ioterm/read_exdr-2.html} and \bipref{write_exdr/2}{../bips/kernel/ioterm/write_exdr-2.html}; these are explained in Section
1005\ref{sec:ji-formatting-queue-data}\index{EXDR}. For the stream ID, you may either use the stream name, or the stream number, obtained for example using \bipref{peer_get_property/3}{../bips/kernel/externals/peer_get_property-3.html}.
1006
1007Since the {\eclipse} side does not support threads, it should only write to
1008an asynchronous queue when there is an active thread on the Java side to
1009read the data. Otherwise, the write-operation may block, and control will
1010never be transferred back from {\eclipse} to Java.
1011
1012For reading from an asynchronous queue, the {\eclipse} side should
1013typically set up an event handler. The handler will be invoked whenever
1014new data arrives on a previously empty queue.
1015\begin{verbatim}
1016my_async_queue_handler(Stream) :-
1017    ( select([Stream], 0, [_]) ->
1018        read_exdr(Stream, Data),
1019        process(Data),
1020        my_async_queue_handler(Stream)
1021    ;
1022        events_nodefer
1023    ).
1024
1025setup_async_queue_with_handler :-
1026    event_create(my_async_queue_handler(my_async_queue), [defers], Event),
1027    peer_queue_create(my_async_queue, host, async, bidirect, Event).
1028\end{verbatim}
1029Note that execution of the handler is only guaranteed when the {\eclipse}
1030side has control.
1031
1032When communicating between Java and {\eclipse} using queues\index{queues}, you
1033should always invoke the {\tt flush()} method of the Java {\it
1034OutputStream} which you have written to, whether it be a {\it
1035ToEclipseQueue} or an {\it EXDROutputStream}. Similarly, on the
1036{\eclipse} side, {\tt flush/1} should always be executed after
1037writing. Although in some cases reading of the data is possible
1038without a flush, flushing guarantees the transfer of data.
1039% \footnote{Note that in extreme cases, even flushing a {\it
1040% ToEclipseQueue} does not guarantee that the data has been fully
1041% transferred to {\eclipse}: see Section \ref{sec:ji-toeclipse-remote}}
1042
1043\subsubsection*{Closing a queue using Java methods}
1044
1045This is done simply by calling the {\tt close()}\index{queues, closing} method on the {\it
1046AsyncEclipseQueue} instance.
1047
1048\subsubsection*{Closing a queue using {\eclipse} predicates}
1049\index{queues, closing}
1050This is done by executing the builtin \bipref{peer_queue_close/1}{../bips/kernel/externals/peer_queue_close-1.html}. Note
1051that the builtin {\tt close/1} should not be used in this situation,
1052as it will not terminate the Java end of the queue.
1053
1054\subsection{Writing and reading {\eclipse} terms on queues\index{queues}}
1055See the corresponding section for synchronous queues, 
1056\ref{sec:ji-formatting-queue-data}.
1057
1058%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1059
1060\section{Managing connections to {\eclipse}}
1061\label{sec:ji-managing-eclipse-connections}
1062As of {\eclipse} 5.3 and later, there are three Java classes which can be
1063used to provide interaction with {\eclipse}. These are {\it
1064EmbeddedEclipse}\index{EmbeddedEclipse class}, {\it OutOfProcessEclipse}\index{OutOfProcessEclipse class}
1065and {\it RemoteEclipse}\index{RemoteEclipse class}. Although the three
1066classes all implement the {\it EclipseConnection} \index{EclipseConnection
1067interface} interface, there are some important differences in
1068initialisation, termination and use which are explained in this section. On
1069the {\eclipse} side, as of version 5.3 and later, there is a unified
1070interface for interaction with Java, based around the concept of a
1071`peer'. This is explained in Section
1072\ref{sec:ji-peer-concept}. Section
1073\ref{sec:ji-creating-eclipse-engines} discusses how to create an
1074{\eclipse} engine from within Java (this covers both {\it
1075EmbeddedEclipse} and {\it OutOfProcessEclipse}\index{OutOfProcessEclipse class}). Section
1076\ref{sec:ji-connecting-existing} discusses the {\it RemoteEclipse}
1077class, which allows Java to connect to an existing {\eclipse}
1078engine. Finally, Section \ref{sec:ji-compare-connection-classes}
1079compares the three connection classes, assessing the advantages and
1080disadvantages of each.
1081
1082\subsection{A unified {\eclipse}-side interface to Java : the `peer' concept}
1083\label{sec:ji-peer-concept}
1084
1085To allow {\eclipse} code to be independent of the way it is
1086interfacing with Java, there is a unified technique in {\eclipse} for
1087interfacing to Java and other non-{\eclipse} programs, based on the
1088concept of a {\it peer}. A peer is a computation environment which is
1089external to {\eclipse}, either in the sense of being a different
1090computer language or being a different process, possibly on a
1091different machine. When {\eclipse} is communicating with one or more
1092Java virtual machines using the Java-{\eclipse} interface (including
1093cases where {\eclipse} is embedded), it stores some global information
1094to keep track of each peer.
1095
1096Each peer of the {\eclipse} engine is indexed within {\eclipse}
1097by a unique {\it peer name} which is an atom. This is set during the
1098initialisation of the connection between {\eclipse} and Java; the
1099details vary according to the Java class used to make the connection.
1100
1101The peer name is used in those {\eclipse} predicate calls related to the
1102peer connection. In particular, those related to the opening and closing of
1103peer queues (see Section \ref{sec:ji-open-close}). The {\it
1104EclipseConnection} \index{EclipseConnection interface} interface includes
1105the method {\tt getPeerName()} which can be used to retrieve this name on
1106the Java side.
1107
1108\subsection{Creating and managing {\eclipse} engines from Java}
1109\label{sec:ji-creating-eclipse-engines}
1110
1111There are at present two options for creating an {\eclipse} engine from
1112Java. With {\it EmbeddedEclipse}\index{EmbeddedEclipse class}, the engine
1113takes the form of a dynamically loaded shared library within the Java
1114virtual machine. With {\it OutOfProcessEclipse}\index{OutOfProcessEclipse class} it is a separate, child
1115process of the Java virtual machine. These two options have in common that
1116they are both initialised using an {\it EclipseEngineOptions} object and
1117that both classes implement {\it EclipseEngine} \index{EclipseEngine
1118interface}.
1119
1120\subsubsection{Configuring an {\it EclipseEngineOptions} object}
1121\label{sec:ji-eclipse-engine-options}
1122Before an {\eclipse} engine is created using either option, an {\it
1123EclipseEngineOptions} object must be created and configured. An
1124instance of the {\it EclipseEngineOptions} class represents our
1125configuration choices for a new {\eclipse} engine. 
1126
1127The options can be specified by either looking them up in a {\it
1128java.util.Properties} instance or by calling ``set'' methods on the
1129{\it EclipseEngineOptions} instance.
1130
1131In the first case you can either specify system properties (by passing
1132{\tt -D} command line options to the JVM) or you can use an {\it
1133EclipseEngineOptions} constructor which takes a {\it Properties}
1134parameter. Each option has a standard property name detailed below.
1135
1136Once the {\it EclipseEngineOptions} object is created, there are
1137also ``set'' methods we can invoke on it to set the different options.
1138
1139\begin{description}
1140\item [The {\eclipse} installation directory ({\tt
1141eclipse.directory})] This must be the correct path of an {\eclipse}
1142installation so that Java can find the files it needs to start
1143{\eclipse}. If an {\it EclipseEngineOptions} constructor is invoked
1144without a directory having been set, either using a constructor
1145parameter or as a property, an exception will be thrown.
1146
1147\item [The default module ({\tt eclipse.default-module})] is the
1148default {\eclipse} module where goals are executed. If no setting is
1149made, then the default module will be ``eclipse''.
1150
1151\item [Local and global size ({\tt eclipse.local-size} and {\tt eclipse.global-size})]
1152are the maximum size of the local stack and the global stack
1153respectively. In each case the option is an integer representing the
1154required size in megabytes. If no setting is made, the sizes default
1155to the {\eclipse} defaults.
1156
1157\begin{description} 
1158\item [Local size] is the maximum combined size of the local 
1159  stack and the control stack. Roughly speaking, the local stack is
1160  the {\eclipse} equivalent of the call/return stack in procedural
1161  languages. The control stack is used to store the choicepoints which
1162  occur in the execution of non-deterministic code. You may therefore
1163  need to increase this limit if your search tree is exceptionally
1164  deep or if there is a lot of non-determinism. You can use the {\eclipse} goal
1165  {\tt get_flag(max_local_control, X)} to find out the current
1166  setting. For more details, see the section on ``Memory Organisation
1167  and Garbage Collection'' in the {\eclipse} User Manual.
1168\item [Global size] is the maximum combined size of the global 
1169  stack and the trail stack. The global stack is used to store data
1170  structures. The trail stack is used to store backtracking
1171  information and is therefore closely related to the control
1172  stack. You may need to increase this limit if you are creating large
1173  data structures in {\eclipse}, or if there is a lot of
1174  non-determinism. You can use the {\eclipse} goal {\tt
1175  get_flag(max_global_trail, X)} to find out the current
1176  setting. Again, see the section in the {\eclipse} User Manual for
1177  more details.
1178\end{description}
1179
1180\item [The ``use queues'' flag ({\tt eclipse.use-queues})]
1181\label{sec:ji-use-queues-flag} If {\tt false} (the default case), the
1182{\eclipse} engine's standard streams ({\tt stdin}, {\tt stdout} and
1183{\tt stderr}) will be connected to the standard streams of the JVM. So
1184for example if, as in {\tt QuickTest.java}, a message is written to
1185{\tt stdout} from within {\eclipse}, this will appear on the {\tt
1186stdout} stream of the JVM. Similarly, if {\eclipse} requests input
1187from the {\tt stdin} stream, input will be requested from the {\tt
1188stdin} stream of the JVM. If the flag is set {\tt true}, {\it
1189FromEclipseQueue} and {\it ToEclipseQueue} objects are used to
1190represent the {\eclipse}'s standard streams.
1191
1192\item [The peer name ({\tt eclipse.peer-name})] is the peer name by
1193which the Java side can be referenced within {\eclipse}, for example when
1194queues are created from the {\eclipse} side. By default the peer name for
1195the Java side when using an {\it EmbeddedEclipse}\index{EmbeddedEclipse
1196class} or an {\it OutOfProcessEclipse}\index{OutOfProcessEclipse class} is ``host''.
1197
1198\end{description}
1199
1200\subsubsection{Using {\it EmbeddedEclipse}}
1201
1202\index{EmbeddedEclipse class}This section discusses issues specific to using the {\it
1203EmbeddedEclipse} class. With {\it EmbeddedEclipse}, the {\eclipse} engine
1204is a dynamically loaded native library in the Java virtual machine. Figure
1205\ref{fig:ji-embedded-deployment} shows this deployment model in UML
1206notation. The important consequences of this deployment model are:
1207
1208\begin{itemize}
1209\item The {\eclipse} engine shares memory and other resources with Java. 
1210\item Only one such engine can exist in a Java virtual machine at any one time.
1211\item Communication between Java and {\eclipse} is very efficient.
1212\end{itemize}
1213
1214
1215
1216% Now put the EPS file (generated from the original GIF file) into a figure
1217
1218\begin{center}
1219  \begin{figure}[htb]
1220    \begin{center}
1221        \includegraphics{embjava-diagrams/embedded-deployment.eps}
1222    \end{center}
1223    \caption{\label{fig:ji-embedded-deployment}UML deployment diagram for {\it EmbeddedEclipse}}
1224  \end{figure}
1225\end{center}
1226
1227
1228
1229\paragraph{Initialising an {\it EmbeddedEclipse}}
1230
1231The embedded {\eclipse} which runs within the JVM and shares its
1232resources, can be started and ended only once during the lifetime of
1233the JVM. There is no public constructor method for {\it
1234EmbeddedEclipse}. Initialisation of the embedded {\eclipse} is done
1235using the static {\tt getInstance} method of class {\it
1236EmbeddedEclipse} which takes an {\it EclipseEngineOptions} instance as
1237a parameter. The method uses this to configure and set up {\eclipse}
1238and then returns an object of type {\it EmbeddedEclipse}. There may
1239only ever be one instance of {\it EmbeddedEclipse} in a JVM. If the
1240embedded {\eclipse} has already been set up or if it has been set up
1241and terminated, subsequent invocations of {\tt getEclipse} with an
1242{\it EclipseEngineOptions} will throw exceptions. However during the
1243lifetime of the embedded {\eclipse}, a reference to the unique {\it
1244EmbeddedEclipse} object can be obtained using the parameterless static
1245{\tt getEclipse} method.
1246
1247\paragraph{Termination of an {\it EmbeddedEclipse}}
1248
1249The {\tt destroy} method which appears in the {\it EmbeddedEclipse}
1250class will shut the embedded {\eclipse} down. Once the {\tt destroy}
1251method has been invoked, the invocation of any methods which require
1252use of the {\eclipse} engine will result in an {\it
1253EclipseTerminatedException} being thrown. The {\tt destroy} method
1254should free all the resources of the JVM process which were being used
1255by the embedded {\eclipse}.
1256
1257Once the {\it EmbeddedEclipse} has been destroyed, {\tt getEclipse}
1258can no longer be used during the lifetime of the JVM to initialise an
1259embedded {\eclipse} engine. In other words, by invoking {\tt destroy},
1260one removes the ability to use embedded {\eclipse} engines within the
1261current instance of the JVM.
1262
1263\subsubsection{Using {\it OutOfProcessEclipse}\index{OutOfProcessEclipse class}}
1264
1265This section discusses issues specific to the {\it
1266OutOfProcessEclipse}\index{OutOfProcessEclipse class} class.  With {\it OutOfProcessEclipse}, the
1267{\eclipse} engine is a child process of the Java virtual
1268machine. Figure \ref{fig:ji-outOfProcess-deployment} shows this deployment
1269model in UML notation. The important consequences of this deployment
1270model are:
1271
1272\begin{itemize}
1273\item The {\eclipse} engine uses separate memory and other resources, 
1274depending on how the operating system allocates these between processes. 
1275\item Several instances of {\it OutOfProcessEclipse}\index{OutOfProcessEclipse class} can exist in a Java 
1276virtual machine at any one time.
1277\item Communication between Java and {\eclipse} is less efficient.
1278\end{itemize}
1279
1280\begin{center}
1281  \begin{figure}[htb] 
1282  \begin{center} 
1283    \includegraphics{embjava-diagrams/outOfProcess-deployment.eps}
1284  \end{center}
1285  \caption{\label{fig:ji-outOfProcess-deployment}UML deployment
1286    diagram for {\it OutOfProcessEclipse}} \end{figure}
1287\end{center}
1288
1289
1290\paragraph{Initialisation of an {\it OutOfProcessEclipse}\index{OutOfProcessEclipse class}}
1291
1292{\it OutOfProcessEclipse}\index{OutOfProcessEclipse class} has a single constructor which takes an {\it
1293EclipseEngineOptions} object as its only parameter. See Section
1294\ref{sec:ji-eclipse-engine-options} for details of how to create and
1295configure this object. Unlike {\it EmbeddedEclipse}, multiple {\it
1296OutOfProcessEclipse}\index{OutOfProcessEclipse class} instances are allowed.
1297
1298\paragraph{Termination of an {\it OutOfProcessEclipse}}
1299
1300We invoke the instance method {\tt destroy()} in {\it
1301OutOfProcessEclipse}\index{OutOfProcessEclipse class} to terminate both the child {\eclipse} process
1302and our association with it. Once the {\tt destroy} method has been
1303invoked, the invocation of any methods on the destroyed {\it
1304OutOfProcessEclipse} object which require use of the {\eclipse} engine will
1305throw an {\it EclipseTerminatedException}. Unlike {\it
1306EmbeddedEclipse}, invoking {\tt destroy()} on an {\it
1307OutOfProcessEclipse} does not affect our ability to create new {\it
1308OutOfProcessEclipse} instances during the lifetime of the Java virtual
1309machine.
1310
1311If the child process {\eclipse} crashes or is killed while {\eclipse}
1312has control, the Java thread which handed control to {\eclipse} should
1313throw an {\it EclipseTerminatedException}. If this happens while Java
1314has control, usually the next invocation of a method on the {\it
1315OutOfProcesEclipse} should throw an {\it EclipseTerminatedException},
1316although it is possible that some operations will throw a different
1317class of {\it IOException}. If this should happen it is worth calling
1318the {\tt destroy} method to do a final clean-up.
1319
1320\subsection{Connecting to an existing {\eclipse} engine using {\it RemoteEclipse}\index{RemoteEclipse class}}
1321\label{sec:ji-connecting-existing}
1322
1323In some applications, for example where Java is used to visualise
1324search in {\eclipse}, the life of the {\eclipse} engine may begin
1325before the connection with Java is initialised or end after the
1326connection with Java is terminated. Furthermore, it may also be useful
1327for the eclipse engine and the Java virtual machine to be running on
1328physically separate computers, for example if the {\eclipse} tasks are
1329being executed on a compute server, but the Java program is to be run
1330on a workstation. The {\it RemoteEclipse}\index{RemoteEclipse class} class can be used to connect
1331Java to {\eclipse} in these two scenarios. The deployment model is
1332that the {\it RemoteEclipse}\index{RemoteEclipse class} Java object is a ``Proxy'' for the
1333{\eclipse} engine which is running on the remote machine, as shown in
1334UML notation in Figure \ref{fig:ji-remote-deployment}.
1335
1336
1337\begin{center}
1338  \begin{figure}[htb]
1339    \begin{center}
1340        \includegraphics{embjava-diagrams/remote-deployment.eps}
1341    \end{center}
1342    \caption{\label{fig:ji-remote-deployment}UML deployment diagram for {\it RemoteEclipse}}
1343  \end{figure}
1344\end{center}
1345
1346The key consequences of this deployment model are:
1347\begin{itemize}
1348\item {\eclipse} and Java can run on different machines and the two machines may have a different architecture/OS.  
1349\item {\eclipse} can connect to multiple Java processes using this model.
1350\item The lifetime of the {\eclipse} engine need not necessarily be a sub-duration of the lifetime of the JVM. 
1351\end{itemize}
1352
1353
1354\subsubsection{Initialisation of a {\it RemoteEclipse}\index{RemoteEclipse class} connection}
1355\label{sec:ji-remote-init}
1356
1357Connecting Java to {\eclipse} using {\it RemoteEclipse} requires the
1358{\eclipse} engine to be primed so that it is ready to accept the
1359connection.  By the time it connects, the Java program must have the
1360IP address of the machine hosting the {\eclipse} engine (the server)
1361and the port number being used for the connection. The attachment
1362protocol also optionally allows for a password to be used by the Java
1363side and checked against one specified on the {\eclipse} side. Also
1364the server must be configured to allow TCP/IP socket servers which can
1365be connected to by the machine hosting Java. Initialising a connection
1366using {\it RemoteEclipse}\index{RemoteEclipse class} therefore requires some coordination between
1367the {\eclipse} code and the Java code. The Java code always consists
1368of a single {\it RemoteEclipse} constructor invocation, although the
1369constructor parameters may vary. 
1370
1371The {\eclipse} side of the code uses certain builtins. Refer to the
1372relevant documentation of these for precise details of usage. On the
1373{\eclipse} side, the code can be structured in two different ways; one
1374simpler and the other allowing more flexibility. We outline here the
1375sequence of actions in each case.
1376
1377\paragraph{Basic connection sequence}
1378This can be used in situations where no password is to be used and
1379where the port number is specified in advance, rather than generated
1380dynamically by {\eclipse}, and is known by the Java side.
1381\begin{enumerate}
1382  \item The {\eclipse} side executes the builtin \bipref{remote_connect/3}{../bips/kernel/externals/remote_connect-3.html}, specifying the port number in advance. This
1383	builtin will block until the connection is established.  
1384
1385  \item The Java side then invokes one of the {\it RemoteEclipse}\index{RemoteEclipse class}
1386	constructors which has no password parameter. This should
1387	immediately complete or throw an exception if the connection
1388	is unsuccessful.
1389
1390\end{enumerate}
1391\paragraph{Advanced connection sequence}
1392This more complicated sequence uses a password and optionally allows
1393the port number to be generated dynamically and then communicated to
1394the Java side.
1395\begin{enumerate}
1396  \item The {\eclipse} side executes the builtin \bipref{remote_connect_setup/3}{../bips/kernel/externals/remote_connect_setup-3.html}, specifying the password and either
1397	specifying the port number or allowing it to be generated
1398	dynamically.
1399
1400  \item The port number must be communicated to the Java side somehow,
1401  	e.g. manually, or via a file.
1402
1403  \item The Java side then invokes one of the {\it RemoteEclipse}\index{RemoteEclipse class}
1404	constructors with a password parameter. This either blocks
1405	until the connection is successful or throws an exception.
1406
1407  \item The {\eclipse} side executes the builtin \bipref{remote_connect_accept/6}{../bips/kernel/externals/remote_connect_accept-6.html}, specifying the password which the
1408  	Java should supply.
1409
1410  \item The Java constructor invocation then completes, or throws an
1411	exception if the connection could not be made.
1412\end{enumerate}
1413
1414% something about localhost
1415If left as a free variable, the {\tt Host} argument of either the \bipref{remote_connect/3}{../bips/kernel/externals/remote_connect-3.html} or \bipref{remote_connect_setup/3}{../bips/kernel/externals/remote_connect_setup-3.html} goal will become
1416instantiated to the IP address of the machine hosting
1417{\eclipse}. Another possibility is to call the goal with this argument
1418already instantiated to the atom {\tt localhost}. This will mean that
1419only client connections made by processes on the same machine and
1420using the loopback address will be accepted. With this usage, on the
1421Java side you should use invoke {\tt
1422InetAddress.getHostByName("localhost")}. Note that {\tt
1423InetAddress.getLocalHost()} will not work in this situation.
1424
1425In both connection sequences, the peer name indexing the connection is
1426either specified or generated dynamically on the {\eclipse} side in
1427the \bipref{remote_connect/3}{../bips/kernel/externals/remote_connect-3.html} or \bipref{remote_connect_setup/3}{../bips/kernel/externals/remote_connect_setup-3.html} goal.
1428
1429Once the connection has been established by one of the above
1430sequences, control initially rests with the Java side. Therefore the
1431{\eclipse} code which called the \bipref{remote_connect/3}{../bips/kernel/externals/remote_connect-3.html} goal or the
1432\bipref{remote_connect_accept/6}{../bips/kernel/externals/remote_connect_accept-6.html} goal blocks until the Java side
1433explicitly transfers control to {\eclipse} or disconnects.
1434
1435\subsubsection{Explicit transfer of control between {\eclipse} and Java}
1436\label{sec:ji-remote-control-transfer}
1437
1438As mentioned above, after the initial connection has been established,
1439Java has control by default. However, this may not be convenient. For
1440example, in the case of search visualisation, after the initialisation
1441of the visualisation client, we may prefer {\eclipse} to have control
1442by default, allowing control to pass to Java only on certain
1443occasions. Control can be explicitly passed from Java to {\eclipse} by
1444invoking the {\tt resume()} method on a {\it RemoteEclipse}\index{RemoteEclipse class}. In this
1445case the {\eclipse} code will resume execution after the last point where
1446it passed control to Java. For example, if {\tt resume()} is invoked
1447immediately after the {\it RemoteEclipse}\index{RemoteEclipse class} constructor completes,
1448{\eclipse} execution will resume at the point just after the call to
1449the \bipref{remote_connect/3}{../bips/kernel/externals/remote_connect-3.html} goal or the \bipref{remote_connect_accept/6}{../bips/kernel/externals/remote_connect_accept-6.html}
1450goal.
1451
1452Control can be transferred to a Java peer using the \bipref{remote_yield/1}{../bips/kernel/externals/remote_yield-1.html}
1453builtin. In this case the Java thread which passed execution to
1454{\eclipse} will resume execution at the point where it blocked.
1455
1456The {\tt resume()} method and the \bipref{remote_yield/1}{../bips/kernel/externals/remote_yield-1.html} builtin should be
1457used with care. An invocation of {\tt resume()} should be paired with
1458an execution of a \bipref{remote_yield/1}{../bips/kernel/externals/remote_yield-1.html} goal in most cases. In addition,
1459\bipref{remote_yield/1}{../bips/kernel/externals/remote_yield-1.html} should not be executed in any code executed as a
1460result of an {\tt rpc}\index{rpc() method} invocation and {\tt resume()} should not be
1461executed within the {\it QueueListener} methods {\tt dataAvailable()}
1462or {\tt dataRequest()}.
1463
1464The {\tt resume()} method and the \bipref{remote_yield/1}{../bips/kernel/externals/remote_yield-1.html} builtin should
1465only be used when other techniques such as {\tt rpc}\index{rpc() method} are not suitable.
1466
1467% section not required: the only situation where there are problems can
1468% never occur, since you cannot read from a closed stream.
1469
1470
1471% \subsubsection{Using {\it ToEclipseQueue} objects with a {\it RemoteEclipse}}
1472% \label{sec:ji-toeclipse-remote}
1473% 
1474% The {\it java.io} API documentation specifies that the contract of the
1475% {\tt flush()} method of an {\it OutputStream} is to indicate to the
1476% stream that, if there are any buffered bytes they should ``immediately
1477% be written to their destination''. Since {\it ToEclipseQueue} is a
1478% subclass of {\it OutputStream}, ideally the completion of the {\tt
1479% flush()} method should guarantee that the bytes have been transferred
1480% to the {\eclipse} side of the connection. 
1481% 
1482% Unfortunately, there is an {\eclipse} limitation preventing this: the
1483% {\eclipse} side has a limited and fixed buffer size. So, in the case
1484% of {\it RemoteEclipse}, if a large enough number of bytes are written
1485% to a {\it ToEclipseQueue} the {\tt flush()} method cannot guarantee
1486% that the bytes have been transferred. However, it makes a lesser
1487% guarantee, that the bytes will be transferred as soon as possible when
1488% space becomes available in the {\eclipse}-side buffer. This will
1489% happen when a read of the queue is executed on the {\eclipse}
1490% side. Meanwhile the bytes are buffered on the Java side. When it
1491% becomes possible, the transfer is done automatically in a separate
1492% Java thread from the one which invoked {\tt flush}, so the API user
1493% does not normally need to worry about this.
1494% 
1495% The only situation where this potentially causes a problem is where a
1496% large number of bytes have been written to the {\it ToEclipseQueue}
1497% which is then flushed and closed before a corresponding read is
1498% executed on the {\eclipse} side. Since closing the queue does not wait
1499% for all the bytes to be transferred, these bytes may be lost. This may
1500% be avoided simply by ensuring that the last {\eclipse}-side read
1501% occurs before the queue is closed.
1502%
1503 
1504\subsubsection{Termination of a {\it RemoteEclipse} connection}
1505\label{sec:ji-remote-disconnect}
1506
1507A {\it RemoteEclipse}\index{RemoteEclipse class} connection between {\eclipse} and Java may be
1508terminated in different ways. Firstly, disconnection may be initiated
1509by either side. Secondly the disconnection may be either {\it
1510multilateral} or {\it unilateral}. Multilateral disconnection, the
1511preferred method, is where the side which has control initiates
1512disconnection. Unilateral disconnection is where the side which
1513initiates disconnection does not have control, and should only take
1514place as a clean-up routine when one side is forced to terminate the
1515connection because of an unexpected event.
1516
1517
1518\begin{description}
1519 \item[Java-initiated multilateral disconnect] is performed by
1520 invoking the {\tt disconnect} method on the {\it RemoteEclipse}\index{RemoteEclipse class}
1521 instance while the Java side has control.
1522
1523 \item[Java-initiated unilateral disconnect] is performed by
1524 invoking the {\tt unilateralDisconnect} method on the {\it
1525 RemoteEclipse}\index{RemoteEclipse class} instance while Java does not have control.
1526
1527 \item[{\eclipse}-initiated multilateral disconnect] is performed on
1528 the {\eclipse} side by executing a \bipref{remote_disconnect/1}{../bips/kernel/externals/remote_disconnect-1.html} goal
1529 while {\eclipse} has control, identifying the connection to be closed
1530 by supplying the peer name.
1531
1532 \item[{\eclipse}-initiated unilateral disconnect] cannot be
1533 executed by the user, since {\eclipse} is not
1534 multi-threaded. However, it may occur in certain urgent situations
1535 e.g. if the {\eclipse} process is killed while {\eclipse} does not
1536 have control.
1537\end{description}
1538If an {\eclipse}-initiated disconnect occurs, or the connection is
1539lost for whatever reason while {\eclipse} has control, the Java thread
1540which handed control to {\eclipse} should throw an {\it
1541EclipseTerminatedException}. If either of these happens while Java has
1542control, the next invocation of a method on the {\it
1543RemoteEclipse}\index{RemoteEclipse class} should throw an {\it EclipseTerminatedException},
1544although it is possible that some operations will throw a different
1545class of {\it IOException}. If this should happen it is worth invoking
1546the {\tt unilateralDisconnect()} method to do a final clean-up.
1547
1548\subsection{Comparison of different Java-{\eclipse} connection techniques}
1549\label{sec:ji-compare-connection-classes}
1550This section should give you some idea of when it is most appropriate
1551to use each connection class. Figure \ref{fig:ji-connection-classes}
1552is a UML class diagram showing the most important relationships and
1553operations of the principal classes and interfaces. 
1554
1555All three classes implement {\it EclipseConnection}
1556\index{EclipseConnection interface}, which provides all the functionality
1557you would expect during a ``session'' with {\eclipse}. The {\it
1558EclipseEngine} interface \index{EclipseEngine interface} is implemented
1559when the JVM ``owns'' the {\eclipse} engine, and so provides the methods to
1560access the standard I/O streams. Note that the termination methods are not
1561in either of the interfaces, but are specific to each class. Furthermore,
1562the {\tt resume()} method allows {\it RemoteEclipse}\index{RemoteEclipse class} to explicitly hand
1563control to {\eclipse}, but this operation is not supported by the other two
1564classes.
1565
1566To summarise the advantages and disadvantages Table
1567\ref{tab:ji-feature-comparison} gives an at-a-glance comparison of the
1568different features of the different connection
1569classes.\index{EclipseConnection interface}\index{EclipseEngine interface}
1570
1571\begin{center}
1572  \begin{figure}[htb]
1573    \begin{center}
1574        \includegraphics{embjava-diagrams/connection-classes.eps}
1575    \end{center}
1576    \caption{\label{fig:ji-connection-classes}UML class diagram for different classes connecting Java and {\eclipse}. Some convenience methods from {\it EclipseConnection} have been omitted.}
1577  \end{figure}
1578\end{center}
1579
1580
1581\begin{table}
1582\begin{center}
1583\begin{tabular}{|l|c|c|c|}
1584\hline
1585Feature			&\multicolumn{3}{|c|}{Java-{\eclipse} connection class}\\
1586\cline{2-4}
1587			&{\it Embedded}&{\it OutOfProcess}	&{\it Remote}\\
1588\hline
1589Implements {\it EclipseConnection} interface \ohtml{(allowing {\tt rpc}\index{rpc() method} and queues)}& $\bullet$ & $\bullet$ & $\bullet$\\
1590\olatex{(allowing {\tt rpc}\index{rpc() method} and queues) & & &\\}
1591\hline
1592Implements {\it EclipseEngine} interface \ohtml{(allowing access to {\eclipse} stdio streams)} & $\bullet$ & $\bullet$ & --\\
1593\olatex{(allowing access to {\eclipse} stdio streams) & & &\\}
1594\hline
1595{\eclipse} is in a separate process \ohtml{(with separate memory heap/stack)} & -- & $\bullet$ & $\bullet$ \\
1596\olatex{(with separate memory heap/stack) & & &\\}
1597\hline
1598{\eclipse} can be on a separate \ohtml{machine from Java}  & -- & -- & $\bullet$ \\
1599\olatex{machine from Java & & &\\}
1600\hline
1601{\eclipse} engine can start before/ \ohtml{end after Java virtual machine}  & -- & -- & $\bullet$ \\
1602\olatex{end after Java virtual machine & & &\\}
1603\hline
1604{\eclipse} engine created/ \ohtml{destroyed from Java}  & $\bullet$ & $\bullet$ & -- \\
1605\olatex{destroyed from Java & & &\\}
1606\hline
1607Efficient transfer of data on \ohtml{queues and {\tt rpc} invocations}  & $\bullet$ & -- & -- \\
1608\olatex{queues and {\tt rpc} invocations & & &\\}
1609\hline
1610One {\eclipse} can connect to many \ohtml{Java virtual machines using this}  & -- & -- & $\bullet$ \\
1611\olatex{Java virtual machines using this & & &\\}
1612\hline
1613One Java virtual machine can connect \ohtml{to many {\eclipse} engines using this}  & -- & $\bullet$ & $\bullet$ \\
1614\olatex{to many {\eclipse} engines using this & & &\\}
1615\hline
1616\end{tabular}
1617\end{center}
1618\caption{\label{tab:ji-feature-comparison} Feature comparison table for different {\eclipse} connection classes}
1619\end{table}
1620
1621%HEVEA\cutend
1622 
1623
1624
1625