Declarativa Declarativa
 

 

Entrada

Produtos

Serviços

Inquiridor
Aplicações internet à medida
Auditoria informática
Subcontratação para I&D

Plataforma de conteúdos

Tecnologia

Web Information Systems
Web Application Maker
InterProlog

A empresa

Apresentação institucional

com.declarativa.interprolog
Class AbstractPrologEngine

java.lang.Object
  extended bycom.declarativa.interprolog.AbstractPrologEngine
All Implemented Interfaces:
PrologEngine
Direct Known Subclasses:
AbstractNativeEngine, SubprocessEngine

public abstract class AbstractPrologEngine
extends Object
implements PrologEngine

The heart of InterProlog; a PrologEngine represents a Prolog machine instance. This is an abstract class; you should use it just to declare variables, but must instantiate only subclasses.


Field Summary
 String firstJavaMessageName
          Name of first message sent to Java
 boolean interrupting
          Prolog is handling an interrupt
static String nl
          Convenience for newline
 String prologBinDirectoryOrCommand
          File path to directory with Prolog machine, or command path, which may have options appended
 
Fields inherited from interface com.declarativa.interprolog.PrologEngine
MAX_INT_VALUE, MIN_INT_VALUE, version
 
Constructor Summary
AbstractPrologEngine(String prologBinDirectoryOrCommand, boolean debug, boolean loadFromJar)
          Create a Prolog executor, possibly spawning it in a different process or loading it into memory, depending on the implementation by our subclass.
 
Method Summary
 void abortTasks()
          Do not invoke this.
static boolean assignableType(Class left, Class right)
          It is OK to assign an expression typed right to a variable typed left.
 boolean command(String s)
          Execute a Prolog "command"
 boolean consultAbsolute(File f)
          Consults a Prolog file
 void consultFromPackage(String filename, Object requester)
          Extracts a Prolog file from the jar file or directory where the requester's class came from, and asks Prolog process to consult it.
 void consultRelative(String filename, Object requester)
          Consults a Prolog file from the directory where the requester's class would come from if it did not come from a jar file.
 boolean deterministicGoal(String G)
          A parameterless goal with no result other than success/failure.
 Object[] deterministicGoal(String G, String RVars)
          Useful when you're constructing objects from Prolog, but don't need to pass any from Java.
 boolean deterministicGoal(String G, String OVar, Object[] objectsP)
          Useful when you want to pass objects to Prolog but don't need objects returned.
 Object[] deterministicGoal(String G, String OVar, Object[] objectsP, String RVars)
          Synchronously calls a Prolog goal.
 TermModel deterministicGoal(TermModel G)
          Useful for inter-Prolog goal calling through Java.
 ResultFromJava doCallback(Object x)
          Execute a Prolog->Java call
 void endAllTasks(Exception e)
          Do not invoke this
static Constructor findConstructor(Class targetClass, Class[] formalArguments)
          Similar to findMethod(), but for constructors rather than regular methods
static Method findMethod(Class targetClass, String name, Class[] formalArguments)
          An utility building on the functionality of getMethod(), to provide the javaMessage predicate with method argument polimorphism.
 void firstJavaMessage()
          Dummy method, whose name is used to start the callback thread
 PrologImplementationPeer getImplementationPeer()
           
 File getJarDirectory()
          Returns the directory containing the jar with the engine class
static File getJarDirectory(Class aClass)
          Returns the directory containing the jar with the given class
 boolean getLoadFromJar()
           
 String getPrologBaseDirectory()
          Returns the installation directory for the Prolog system, without the trailing separator char
 String getPrologNumericVersion()
          Returns the Prolog numeric version for this engine; useful for functionality that depends on features of a particular version.
 String getPrologVersion()
          Returns the Prolog system name and version for this engine
 Object getRealJavaObject(int ID)
          Same as getRealJavaObject(InvisibleObject), but accepts an integer ID as argument instead
 Object getRealJavaObject(InvisibleObject o)
          Get the object referred by the integer in a InvisibleObject wrapper.
 Object getRealJavaObject(Object o)
          Just returns the object, untouched (but "dereferenced" if called from Prolog).
 Object handleCallback(Object x)
          Handling of javaMessages and deterministicGoals.
 void interrupt()
          Interrupt Prolog and make it return to its top level.
 void interruptTasks()
          Do not invoke this.
 boolean isAvailable()
          Present implementation is always available, so this always returns true.
 boolean isDebug()
          Debug messages are being written, both Java and Prolog side, cf. ipIsDebugging/0
 boolean isIdle()
          The engine is doing nothing: no pending Prolog goals nor Java callbacks
static boolean isMacOS()
           
 boolean isShutingDown()
          The engine is in the process of shuting down
static boolean isWindowsOS()
           
 void load_dynRelative(String filename, Object requester)
           
 Object makeInvisible(Object x)
          Register an object with this Engine, so it later can be referred from Prolog without serializing it, and returns an InvisibleObject encapsulating the reference.
static void printBindings(Object[] b)
          Convenience for debugging deterministicGoal() messages
 void progressMessage(String s)
          Debugging aid
 String prologBinToBaseDirectory(String binDirectoryOrStartCommand)
          Computes the installation directory for the Prolog system, without the trailing separator char
abstract  boolean realCommand(String s)
          Implementation of a simple parameterless Prolog goal; does not support recursive nor multithreaded operation, use command instead
 int registerJavaObject(Object x)
          Register an object with this Engine, so it later can be referred from Prolog without serializing it.
 void setDebug(boolean d)
          Show (or hide) debug messages, both Java and Prolog side, cf. ipIsDebugging/0.
 void setThreadedCallbacks(boolean yes)
          If true, the Java execution of javaMessage predicates will happen in new threads (default); if false, execution will be under the thread of the deterministicGoal currently executing in Prolog
static String shortClassName(Class c)
          Returns just the name of the class, with no package information.
 void shutdown()
          Release Prolog engine resources, making it unusable
 boolean teachMoreObjects(Object[] examples)
          Same as #teachMoreObjects(ObjectExamplePair[]), but example pairs are constructed with (2) repeated examples for each object
 boolean teachMoreObjects(ObjectExamplePair example)
           
 boolean teachMoreObjects(ObjectExamplePair[] examples)
          Send an array of object example pairs to Prolog and generate ipObjectSpec facts.
 boolean teachOneObject(Object example)
          Same as #teachMoreObjects(ObjectExamplePair[]), but the single example pair is constructed repeating the object
 String unescapedFilePath(String p)
          Some Prologs use '\' as an escape character in atoms, which can affect file paths under Windows.
 boolean unregisterJavaObject(int ID)
          Removes reference to the object from the registry.
 boolean unregisterJavaObject(Object obj)
          Removes reference to the object from the registry.
 boolean unregisterJavaObjects(Class cls)
          Removes references to objects of class cls from the registry.
 void waitUntilAvailable()
          This method blocks until isAvailable() returns true.
 void waitUntilIdle()
          Sleeps the current Java thread until this engine is idle.
 
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

prologBinDirectoryOrCommand

public String prologBinDirectoryOrCommand
File path to directory with Prolog machine, or command path, which may have options appended


nl

public static final String nl
Convenience for newline


interrupting

public boolean interrupting
Prolog is handling an interrupt


firstJavaMessageName

public final String firstJavaMessageName
Name of first message sent to Java

See Also:
Constant Field Values
Constructor Detail

AbstractPrologEngine

public AbstractPrologEngine(String prologBinDirectoryOrCommand,
                            boolean debug,
                            boolean loadFromJar)
Create a Prolog executor, possibly spawning it in a different process or loading it into memory, depending on the implementation by our subclass.

Parameters:
prologBinDirectoryOrCommand - File path to Prolog machine, see subclass docs for precise semantics
debug - if true, print progress messages to aid debugging
loadFromJar - if true, startup files should be loaded from the jar file, rather than directly from the file system

IF prologBinDirectoryOrCommand is null then InterProlog needs to find values for one or more properties, XSB_BIN_DIRECTORY and/or SWI_BIN_DIRECTORY, depending on which Prolog(s) you're using.

First it looks for an 'interprolog.defs' file (a Properties file in the format described in http://java.sun.com/j2se/1.4.2/docs/api/java/util/Properties.html, in the directory where the jar file containing the InterProlog classes is).
If 'interprolog.defs' does not exist, an attempt is made to get the property through System.getProperties(); in this scenario you can define the property by using the -D java (command) switch

Method Detail

getImplementationPeer

public PrologImplementationPeer getImplementationPeer()
Specified by:
getImplementationPeer in interface PrologEngine

getPrologVersion

public String getPrologVersion()
Returns the Prolog system name and version for this engine

Specified by:
getPrologVersion in interface PrologEngine

getPrologNumericVersion

public String getPrologNumericVersion()
Returns the Prolog numeric version for this engine; useful for functionality that depends on features of a particular version. It is requested to Prolog dynamically, but only once. Should not be used only after the engine objects is initialized (constructed).


getPrologBaseDirectory

public String getPrologBaseDirectory()
Returns the installation directory for the Prolog system, without the trailing separator char

Specified by:
getPrologBaseDirectory in interface PrologEngine

prologBinToBaseDirectory

public String prologBinToBaseDirectory(String binDirectoryOrStartCommand)
Computes the installation directory for the Prolog system, without the trailing separator char


isWindowsOS

public static boolean isWindowsOS()

isMacOS

public static boolean isMacOS()

shutdown

public void shutdown()
Release Prolog engine resources, making it unusable

Specified by:
shutdown in interface PrologEngine

isShutingDown

public boolean isShutingDown()
The engine is in the process of shuting down


getJarDirectory

public File getJarDirectory()
Returns the directory containing the jar with the engine class


getJarDirectory

public static File getJarDirectory(Class aClass)
Returns the directory containing the jar with the given class


unescapedFilePath

public String unescapedFilePath(String p)
Some Prologs use '\' as an escape character in atoms, which can affect file paths under Windows. Use this method to preprocess all file paths passed to Prolog.


consultFromPackage

public void consultFromPackage(String filename,
                               Object requester)
Extracts a Prolog file from the jar file or directory where the requester's class came from, and asks Prolog process to consult it. You should use this method only after your program is stable. The Prolog file is extracted into a temporary file, that is automatically deleted on exiting the application.

Specified by:
consultFromPackage in interface PrologEngine
Parameters:
filename - The Prolog file name, including extension; if it has no extension, the Prolog file extensions are appended in turn until a file is found
requester - Defines where the Prolog file resides
See Also:
consultRelative(String, Object), load_dynRelative(String, Object)

consultAbsolute

public boolean consultAbsolute(File f)
Consults a Prolog file

Specified by:
consultAbsolute in interface PrologEngine

consultRelative

public void consultRelative(String filename,
                            Object requester)
Consults a Prolog file from the directory where the requester's class would come from if it did not come from a jar file. Adds that directory to the library_directory relation, so modules can be found there

Specified by:
consultRelative in interface PrologEngine
Parameters:
filename - The Prolog file name, including suffix; if a path it should use '/' as the separator, independently of the OS
requester - Defines where the Prolog file resides

load_dynRelative

public void load_dynRelative(String filename,
                             Object requester)
Specified by:
load_dynRelative in interface PrologEngine

interrupt

public void interrupt()
Interrupt Prolog and make it return to its top level. This is the equivalent to performing a ctrl+c or similar command when using Prolog under a standard console shell.

Specified by:
interrupt in interface PrologEngine

command

public boolean command(String s)
Execute a Prolog "command"

Specified by:
command in interface PrologEngine

realCommand

public abstract boolean realCommand(String s)
Implementation of a simple parameterless Prolog goal; does not support recursive nor multithreaded operation, use command instead

See Also:
command(String)

progressMessage

public void progressMessage(String s)
Debugging aid


isDebug

public boolean isDebug()
Debug messages are being written, both Java and Prolog side, cf. ipIsDebugging/0

Specified by:
isDebug in interface PrologEngine

setDebug

public void setDebug(boolean d)
Show (or hide) debug messages, both Java and Prolog side, cf. ipIsDebugging/0. Beware that this may try to assert/retract a flag (ipIsDebugging/0) on the Prolog side, be sure to invoke this method sooner rather than later as it may get "stuck" if there are problems communicating with the Prolog engine

Specified by:
setDebug in interface PrologEngine

getLoadFromJar

public boolean getLoadFromJar()

printBindings

public static void printBindings(Object[] b)
Convenience for debugging deterministicGoal() messages


teachOneObject

public boolean teachOneObject(Object example)
Same as #teachMoreObjects(ObjectExamplePair[]), but the single example pair is constructed repeating the object

Specified by:
teachOneObject in interface PrologEngine
See Also:
teachMoreObjects(ObjectExamplePair[])

teachMoreObjects

public boolean teachMoreObjects(Object[] examples)
Same as #teachMoreObjects(ObjectExamplePair[]), but example pairs are constructed with (2) repeated examples for each object

Specified by:
teachMoreObjects in interface PrologEngine
See Also:
teachMoreObjects(ObjectExamplePair[])

teachMoreObjects

public boolean teachMoreObjects(ObjectExamplePair[] examples)
Send an array of object example pairs to Prolog and generate ipObjectSpec facts. Returns true if this succeeds, false otherwise.

Specified by:
teachMoreObjects in interface PrologEngine
Parameters:
examples - The examples
See Also:
ObjectExamplePair

teachMoreObjects

public boolean teachMoreObjects(ObjectExamplePair example)

deterministicGoal

public Object[] deterministicGoal(String G,
                                  String OVar,
                                  Object[] objectsP,
                                  String RVars)
Synchronously calls a Prolog goal. Only the first solution is considered. G should contain a syntactically correct Prolog term, without the trailing dot (.). Throws an IPAbortedException if a Prolog abort happens, and an IPInterruptedException if the interrupt() method was invoked.

Specified by:
deterministicGoal in interface PrologEngine
Parameters:
G - Prolog goal term
OVar - Prolog variable that will be bound to objectsP array
objectsP - Array of Java objects to pass to Prolog goal
RVars - Prolog list with object specifications, typically containing variables occurring in g. If null a single binding will be returned, containing a TermModel object representing the goal term solution
Returns:
a new array containing an object for each term in the rVars list, or null if goal fails
See Also:
deterministicGoal(String), deterministicGoal(String,String), deterministicGoal(String,String,Object[])

deterministicGoal

public boolean deterministicGoal(String G)
A parameterless goal with no result other than success/failure. Same as deterministicGoal(G, null,null,"[]")

Specified by:
deterministicGoal in interface PrologEngine

deterministicGoal

public Object[] deterministicGoal(String G,
                                  String RVars)
Useful when you're constructing objects from Prolog, but don't need to pass any from Java. Same as deterministicGoal(G,null,null,RVars)

Specified by:
deterministicGoal in interface PrologEngine

deterministicGoal

public boolean deterministicGoal(String G,
                                 String OVar,
                                 Object[] objectsP)
Useful when you want to pass objects to Prolog but don't need objects returned. Same as deterministicGoal(G, OVar,objectsP,"[]")

Specified by:
deterministicGoal in interface PrologEngine

deterministicGoal

public TermModel deterministicGoal(TermModel G)
Useful for inter-Prolog goal calling through Java. For example, to call a goal G in another PrologEngine E: buildTermModel(G,GM), javaMessage(E,SM,deterministicGoal(GM)), recoverTermModel(SM,Solution)

Specified by:
deterministicGoal in interface PrologEngine

isIdle

public boolean isIdle()
The engine is doing nothing: no pending Prolog goals nor Java callbacks

Specified by:
isIdle in interface PrologEngine

endAllTasks

public void endAllTasks(Exception e)
Do not invoke this


abortTasks

public void abortTasks()
Do not invoke this. Due to the use of several Java packages in InterProlog this method must be qualified as public


interruptTasks

public void interruptTasks()
Do not invoke this. Due to the use of several Java packages in InterProlog this method must be qualified as public


isAvailable

public boolean isAvailable()
Present implementation is always available, so this always returns true. Subclass implementations should return false if the Prolog engine is not available for work, e.g. prompt was not yet recognized in a subprocess (socket) engine

Specified by:
isAvailable in interface PrologEngine

waitUntilAvailable

public void waitUntilAvailable()
Description copied from interface: PrologEngine
This method blocks until isAvailable() returns true.

Specified by:
waitUntilAvailable in interface PrologEngine

waitUntilIdle

public void waitUntilIdle()
Sleeps the current Java thread until this engine is idle. If this never happens, we're in trouble.

Specified by:
waitUntilIdle in interface PrologEngine

handleCallback

public Object handleCallback(Object x)
Handling of javaMessages and deterministicGoals. This is where most things happen.

Parameters:
x - Argument of the callback predicate

firstJavaMessage

public final void firstJavaMessage()
Dummy method, whose name is used to start the callback thread


doCallback

public ResultFromJava doCallback(Object x)
Execute a Prolog->Java call


findMethod

public static Method findMethod(Class targetClass,
                                String name,
                                Class[] formalArguments)
                         throws NoSuchMethodException
An utility building on the functionality of getMethod(), to provide the javaMessage predicate with method argument polimorphism. If the type signatures do not match exactly, searches all method signatures to see if their arguments are type-compatible.

Throws:
NoSuchMethodException

findConstructor

public static Constructor findConstructor(Class targetClass,
                                          Class[] formalArguments)
                                   throws NoSuchMethodException
Similar to findMethod(), but for constructors rather than regular methods

Throws:
NoSuchMethodException

assignableType

public static boolean assignableType(Class left,
                                     Class right)
It is OK to assign an expression typed right to a variable typed left. Delegates on isAssignableFrom


shortClassName

public static String shortClassName(Class c)
Returns just the name of the class, with no package information. That is, if foo.bar.Mumble were the class passed in, the string "Mumble" would be returned. Similarly, if the class that is passed in is a.b.Class$InnerClass the string returned would be InnerClass.


registerJavaObject

public int registerJavaObject(Object x)
Register an object with this Engine, so it later can be referred from Prolog without serializing it.

Specified by:
registerJavaObject in interface PrologEngine
Parameters:
x - Object to be registered
Returns:
Integer denoting the object. In Prolog one can then refer to it by using the InvisibleObject class.
See Also:
InvisibleObject

makeInvisible

public Object makeInvisible(Object x)
Register an object with this Engine, so it later can be referred from Prolog without serializing it, and returns an InvisibleObject encapsulating the reference.

Specified by:
makeInvisible in interface PrologEngine
Parameters:
x - Object to be registered
Returns:
InvisibleObject denoting the object. In Prolog one can then refer to it by using the InvisibleObject class.
See Also:
InvisibleObject

getRealJavaObject

public Object getRealJavaObject(InvisibleObject o)
Get the object referred by the integer in a InvisibleObject wrapper.

Specified by:
getRealJavaObject in interface PrologEngine
Parameters:
o - An InvisibleObject
Returns:
The real object denoted by o in the context of this engine
See Also:
InvisibleObject

getRealJavaObject

public Object getRealJavaObject(int ID)
Same as getRealJavaObject(InvisibleObject), but accepts an integer ID as argument instead

Specified by:
getRealJavaObject in interface PrologEngine

getRealJavaObject

public Object getRealJavaObject(Object o)
Just returns the object, untouched (but "dereferenced" if called from Prolog). This serves the need to get objects in javaMessage because of the way CallbackHandler.doCallback works. For example: ipPrologEngine(_E), stringArraytoList(_O,[miguel,calejo]), javaMessage(_E,_R,getRealJavaObject(_O)),stringArraytoList(_R,List). ... will bind List to [miguel,calejo] and not to an InvisibleObject specification as ordinarly would happen

Specified by:
getRealJavaObject in interface PrologEngine

unregisterJavaObject

public boolean unregisterJavaObject(int ID)
Removes reference to the object from the registry. This method should be used with extreme caution since any further prolog calls to the object by means of reference to it in the registry might result in unpredictable behaviour.

Specified by:
unregisterJavaObject in interface PrologEngine

unregisterJavaObject

public boolean unregisterJavaObject(Object obj)
Removes reference to the object from the registry. This method should be used with extreme caution since any further prolog calls to the object by means of reference to it in the registry might result in unpredictable behaviour.

Specified by:
unregisterJavaObject in interface PrologEngine

unregisterJavaObjects

public boolean unregisterJavaObjects(Class cls)
Removes references to objects of class cls from the registry. This method should be used with extreme caution since any further prolog calls to the unregistered objects by means of reference to them in the registry might result in unpredictable behaviour.

Specified by:
unregisterJavaObjects in interface PrologEngine

setThreadedCallbacks

public void setThreadedCallbacks(boolean yes)
If true, the Java execution of javaMessage predicates will happen in new threads (default); if false, execution will be under the thread of the deterministicGoal currently executing in Prolog

Specified by:
setThreadedCallbacks in interface PrologEngine



 Declarativa - Serviços de Informática, Lda.
  www.declarativa.com, info@declarativa.com  fax: +351-22-030-1511  tel: +351-22-030-1580
UPTEC - Parque de Ciência e Tecnologia da Universidade do Porto (GoogleMap)
Rua Actor Ferreira da Silva 100 4200-298 Porto Portugal