php.java.bridge
Class JavaBridge

java.lang.Object
  extended by php.java.bridge.JavaBridge
All Implemented Interfaces:
java.lang.Runnable

public class JavaBridge
extends java.lang.Object
implements java.lang.Runnable

This is the main interface of the PHP/Java Bridge. It contains utility methods which can be used by clients.

Author:
Sam Ruby (methods coerce and select), Kai Londenberg, Jost Boekemeier
See Also:
Standalone, PhpJavaServlet

Field Summary
 java.io.InputStream in
          For internal use only.
 java.lang.Throwable lastException
          For PHP4's last_exception_get.
 int logLevel
          For internal use only.
 java.io.OutputStream out
          For internal use only.
 Request request
          For internal use only.
 
Method Summary
 void beginDocument()
          Selects the asynchronous protocol mode.
static ISocketFactory bind(java.lang.String sockname)
          Create a new server socket and return it.
 java.lang.Object cast(java.lang.Object ob, java.lang.Class type)
          Cast a object to a type
 java.lang.Object castToArray(java.lang.Object ob)
          Cast an object to an array
 java.lang.Object castToBoolean(java.lang.Object ob)
          Cast an object to a boolean value
 java.lang.Object castToExact(java.lang.Object ob)
          Cast an object to an exact number
 java.lang.Object castToInexact(java.lang.Object ob)
          Cast an object to a inexact value
 java.lang.Object castToString(java.lang.Exception throwable, java.lang.String trace)
          Cast a throwable to a string
 java.lang.Object castToString(java.lang.Object ob)
          Cast an object to a string
static java.lang.String classDebugDescription(java.lang.Class cls)
          Only for internal use
 void clearLastException()
          Clear the last Exception
 void CreateObject(java.lang.String name, boolean createInstance, java.lang.Object[] args, Response response)
          Create an new instance of a given class, to be called by clients.
 int deserialize(java.lang.String serialID, int timeout)
          Load the object from the session store.
 void endDocument()
          Back to synchronous protocol mode
 java.lang.String getCachedString(byte[] b, int start, int length)
          Return a cached string using the current file encoding (see java_set_file_encoding()).
 java.lang.Object getContext()
          Returns the JSR223 context.
 IJavaBridgeFactory getFactory()
          Return the session/jsr223 factory associated with this bridge
 java.lang.Throwable getLastException()
          Return the first java.lang.RuntimeException/java.lang.Error in a chain or the last java.lang.Exception.
 int getLogLevel()
          Return the log level:
0: log off
1: log fatal
2: log messages/exceptions
3: log verbose
4: log debug
5: log method invocations
 php.java.bridge.Options getOptions()
          Returns the connection options
 php.java.bridge.PhpMap getPhpMap(java.lang.Object value)
          Return map for the value (PHP 5 only)
 ISession getSession(java.lang.String name, short clientIsNew, int timeout)
          Return a session handle shared among all JavaBridge instances.
 void GetSetProp(java.lang.Object object, java.lang.String prop, java.lang.Object[] args, Response response)
          Get or Set a property, to be called by clients.
 java.lang.String getString(byte[] b, int start, int length)
          Return a new string using the current file encoding (see java_set_file_encoding()).
 java.lang.Object getValues(java.lang.Object ob)
          Convert Map or Collection into a PHP array, sends the entire array, Map or Collection to the client.
 void handleRequests(java.io.InputStream in, java.io.OutputStream out)
          Handle requests from the InputStream, write the responses to OutputStream
 void handleRequests(java.io.InputStream in, java.io.OutputStream out, ILogger logger)
          Deprecated. Example:
protected void doPut (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
  IContextFactory ctx = new RemoteHttpServletContextFactory(this, getServletContext(), req, req, resr);
  res.setHeader("X_JAVABRIDGE_CONTEXT", ctx.getId());
  res.setHeader("Pragma", "no-cache");
  res.setHeader("Cache-Control", "no-cache");
  try { ctx.getBridge().handleRequests(req.getInputStream(), res.getOutputStream(), myLogge); } finally { ctx.destroy(); }
}
static void init(java.lang.String[] s)
          Global init.
 java.lang.String inspect(java.lang.Object object)
          For internal use only.
 boolean InstanceOf(java.lang.Object ob, java.lang.Object claz)
          Check if object is an instance of class.
 void Invoke(java.lang.Object object, java.lang.String method, java.lang.Object[] args, Response response)
          Invoke a method on a given object, to be called by clients.
 void logDebug(java.lang.String msg)
          Write a debug message
 void logError(java.lang.String msg)
          Write an error message.
 void logFatal(java.lang.String msg)
          Write a fatal message
 void logMessage(java.lang.String msg)
          Write a notice.
static void main(java.lang.String[] s)
          Start the PHP/Java Bridge.
 java.lang.Object makeClosure(long object)
          Create a dynamic proxy proxy for calling PHP code.
Example:
java_closure();
java_closure($this);
 java.lang.Object makeClosure(long object, java.util.Map names)
          Create a dynamic proxy proxy for calling PHP code.
Example:
java_closure($this, $map);
 java.lang.Object makeClosure(long object, java.util.Map names, java.lang.Class iface)
          Create a dynamic proxy proxy for calling PHP code.
Example:
java_closure($this, $map, $interfaces);
 java.lang.Object makeClosure(long object, java.util.Map names, java.lang.Class[] interfaces)
          Create a dynamic proxy proxy for calling PHP code.
Example:
java_closure($this, $map, $interfaces);
 java.lang.Object makeClosure(long object, java.lang.String name)
          Create a dynamic proxy proxy for calling PHP code.
Example:
java_closure($this, "clickMe");
 java.lang.Object makeClosure(long object, java.lang.String name, java.lang.Class iface)
          Create a dynamic proxy proxy for calling PHP code.
Example:
java_closure($this, $map, $interfaces);
 java.lang.Object makeClosure(long object, java.lang.String name, java.lang.Class[] interfaces)
          Create a dynamic proxy proxy for calling PHP code.
Example:
java_closure($this, "clickMe", $interfaces);
static java.lang.String objectDebugDescription(java.lang.Object ob)
          Only for internal use
 java.lang.Object ObjectToString(java.lang.Boolean ob)
          Returns a string representation of the object
 java.lang.Object ObjectToString(byte[] ob)
          Returns a string representation of the object
 java.lang.Object ObjectToString(java.lang.Object ob)
          Returns a string representation of the object
 java.lang.Object ObjectToString(java.lang.String ob)
          Returns a string representation of the object
 java.lang.Object ObjectToString(java.lang.Throwable ob, java.lang.String trace)
          Returns a string representation of the object
 boolean offsetExists(java.lang.Object table, java.lang.Object off)
          Checks if a given position exists.
 java.lang.Object offsetGet(java.lang.Object table, java.lang.Object off)
          Returns the object at the posisition.
 void offsetSet(java.lang.Object table, java.lang.Object off, java.lang.Object val)
          Set an object at position.
 void offsetUnset(java.lang.Object table, java.lang.Object off)
          Remove an object from the position.
 void printStackTrace(java.lang.Throwable t)
          Print a stack trace to the log file.
 void recycle()
          Re-initialize the current bridge for keep-alive See php.ini option java.persistent_connections
 void run()
          Communication with client in a new thread
 java.lang.String serialize(java.lang.Object obj, int timeout)
          Store the object in the session store and return the serial id.
 void setFileEncoding(java.lang.String fileEncoding)
          Set a new file encoding, used to code and decode strings.
 boolean typeExists(java.lang.String name)
          Check if a given class exists.
 long unwrapClosure(java.lang.Object closure)
          Returns the PHP object associated with a closure
 void warn(java.lang.String msg)
          Write a warning.
 
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

lastException

public java.lang.Throwable lastException
For PHP4's last_exception_get.


in

public java.io.InputStream in
For internal use only. The input stream for the current channel.


out

public java.io.OutputStream out
For internal use only. The output stream for the current channel.


logLevel

public int logLevel
For internal use only. The request log level.


request

public Request request
For internal use only. The current request (if any)

Method Detail

getLogLevel

public int getLogLevel()
Return the log level:
0: log off
1: log fatal
2: log messages/exceptions
3: log verbose
4: log debug
5: log method invocations

Returns:
The request log level.

handleRequests

public void handleRequests(java.io.InputStream in,
                           java.io.OutputStream out,
                           ILogger logger)
                    throws java.io.IOException
Deprecated. Example:
protected void doPut (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
  IContextFactory ctx = new RemoteHttpServletContextFactory(this, getServletContext(), req, req, resr);
  res.setHeader("X_JAVABRIDGE_CONTEXT", ctx.getId());
  res.setHeader("Pragma", "no-cache");
  res.setHeader("Cache-Control", "no-cache");
  try { ctx.getBridge().handleRequests(req.getInputStream(), res.getOutputStream(), myLogge); } finally { ctx.destroy(); }
}

Handle requests from the InputStream, write the responses to OutputStream

Parameters:
in - the InputStream
out - the OutputStream
logger - the default logger can be obtained via getServletContext().getAttribute(ContextLoaderListener.LOGGER)
Throws:
java.io.IOException

handleRequests

public void handleRequests(java.io.InputStream in,
                           java.io.OutputStream out)
                    throws java.io.IOException
Handle requests from the InputStream, write the responses to OutputStream

Parameters:
in - the InputStream
out - the OutputStream
Throws:
java.io.IOException - Example:
protected void doPut (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
  IContextFactory ctx = new RemoteHttpServletContextFactory(this, getServletContext(), req, req, resr);
  res.setHeader("X_JAVABRIDGE_CONTEXT", ctx.getId());
  res.setHeader("Pragma", "no-cache");
  res.setHeader("Cache-Control", "no-cache");
  try { ctx.getBridge().handleRequests(req.getInputStream(), res.getOutputStream(), myLogge); } finally { ctx.destroy(); }
}

getFactory

public IJavaBridgeFactory getFactory()
Return the session/jsr223 factory associated with this bridge

Returns:
The session/jsr223 factory

getOptions

public php.java.bridge.Options getOptions()
Returns the connection options

Returns:
The Options.

run

public void run()
Communication with client in a new thread

Specified by:
run in interface java.lang.Runnable

bind

public static ISocketFactory bind(java.lang.String sockname)
                           throws java.io.IOException
Create a new server socket and return it.

Parameters:
sockname - the socket name
Returns:
the server socket
Throws:
java.io.IOException

init

public static void init(java.lang.String[] s)
Global init. Redirects System.out and System.err to the server log file(s) or to System.err and creates and opens the communcation channel. Note: Do not write anything to System.out, this stream is connected with a pipe which waits for the channel name.

Parameters:
s - an array of [socketname, level, logFile]

main

public static void main(java.lang.String[] s)
Start the PHP/Java Bridge.
Example:
java -Djava.awt.headless=true -jar JavaBridge.jar INET:9656 5 /var/log/php-java-bridge.log
Note: Do not write anything to System.out, this stream is connected with a pipe which waits for the channel name.

Parameters:
s - an array of [socketname, level, logFile] Use Standalone.main()
See Also:
Standalone.main(String[])

printStackTrace

public void printStackTrace(java.lang.Throwable t)
Print a stack trace to the log file.

Parameters:
t - the throwable

logDebug

public void logDebug(java.lang.String msg)
Write a debug message

Parameters:
msg - The message

logFatal

public void logFatal(java.lang.String msg)
Write a fatal message

Parameters:
msg - The message

logError

public void logError(java.lang.String msg)
Write an error message.

Parameters:
msg - The message

logMessage

public void logMessage(java.lang.String msg)
Write a notice.

Parameters:
msg - The message

warn

public void warn(java.lang.String msg)
Write a warning.

Parameters:
msg - The warning.

CreateObject

public void CreateObject(java.lang.String name,
                         boolean createInstance,
                         java.lang.Object[] args,
                         Response response)
Create an new instance of a given class, to be called by clients.

Parameters:
name - The class name
createInstance - true if we should create an instance, false otherwise
args - The argument array
response - The response writer

Invoke

public void Invoke(java.lang.Object object,
                   java.lang.String method,
                   java.lang.Object[] args,
                   Response response)
Invoke a method on a given object, to be called by clients.

Parameters:
object - The object
method - The method of the object
args - The argument array
response - The response writer
Throws:
java.lang.NullPointerException - If the object was null

objectDebugDescription

public static java.lang.String objectDebugDescription(java.lang.Object ob)
Only for internal use

Parameters:
ob - The object
Returns:
A debug description.

classDebugDescription

public static java.lang.String classDebugDescription(java.lang.Class cls)
Only for internal use

Parameters:
cls - The class
Returns:
A debug description.

GetSetProp

public void GetSetProp(java.lang.Object object,
                       java.lang.String prop,
                       java.lang.Object[] args,
                       Response response)
                throws java.lang.NullPointerException
Get or Set a property, to be called by clients.

Parameters:
object - The object
prop - The object property
args - The argument array
response - The response writer
Throws:
java.lang.NullPointerException - If the object is null

getValues

public java.lang.Object getValues(java.lang.Object ob)
Convert Map or Collection into a PHP array, sends the entire array, Map or Collection to the client. This is much more efficient than generating round-trips while iterating over the values of an array, Map or Collection.

Parameters:
ob - - The object to expand
Returns:
The passed ob, will be expanded by the appropriate writer.

unwrapClosure

public long unwrapClosure(java.lang.Object closure)
                   throws java.lang.IllegalArgumentException
Returns the PHP object associated with a closure

Parameters:
closure - The closure
Returns:
The php object
Throws:
java.lang.IllegalArgumentException

cast

public java.lang.Object cast(java.lang.Object ob,
                             java.lang.Class type)
Cast a object to a type

Parameters:
ob - - The object to cast
type - - The target type
Returns:
The passed ob, will be coerced by the appropriate writer.

castToString

public java.lang.Object castToString(java.lang.Object ob)
Cast an object to a string

Parameters:
ob - - The object to cast
Returns:
The passed ob, will be coerced by the appropriate writer.

castToString

public java.lang.Object castToString(java.lang.Exception throwable,
                                     java.lang.String trace)
Cast a throwable to a string

Parameters:
throwable - The throwable to cast
trace - The PHP stack trace
Returns:
The result String object, will be coerced by the appropriate writer.

castToExact

public java.lang.Object castToExact(java.lang.Object ob)
Cast an object to an exact number

Parameters:
ob - - The object to cast
Returns:
The passed ob, will be coerced by the appropriate writer.

castToBoolean

public java.lang.Object castToBoolean(java.lang.Object ob)
Cast an object to a boolean value

Parameters:
ob - - The object to cast
Returns:
The passed ob, will be coerced by the appropriate writer.

castToInexact

public java.lang.Object castToInexact(java.lang.Object ob)
Cast an object to a inexact value

Parameters:
ob - - The object to cast
Returns:
The passed ob, will be coerced by the appropriate writer.

castToArray

public java.lang.Object castToArray(java.lang.Object ob)
Cast an object to an array

Parameters:
ob - - The object to cast
Returns:
The passed ob, will be coerced by the appropriate writer.

getPhpMap

public php.java.bridge.PhpMap getPhpMap(java.lang.Object value)
Return map for the value (PHP 5 only)

Parameters:
value - - The value which must be an array or implement Map or Collection.
Returns:
The PHP map.
See Also:
PhpMap

inspect

public java.lang.String inspect(java.lang.Object object)
For internal use only.

Parameters:
object - The java object
Returns:
A list of all visible constructors, methods, fields and inner classes.

setFileEncoding

public void setFileEncoding(java.lang.String fileEncoding)
Set a new file encoding, used to code and decode strings. Example: setFileEncoding("UTF-8")

Parameters:
fileEncoding - The file encoding.

InstanceOf

public boolean InstanceOf(java.lang.Object ob,
                          java.lang.Object claz)
Check if object is an instance of class.

Parameters:
ob - The object
claz - The class or an instance of a class
Returns:
true if ob is an instance of class, false otherwise.

ObjectToString

public java.lang.Object ObjectToString(java.lang.Object ob)
Returns a string representation of the object

Parameters:
ob - The object
Returns:
A string representation.

ObjectToString

public java.lang.Object ObjectToString(java.lang.Boolean ob)
Returns a string representation of the object

Parameters:
ob - The object
Returns:
A string representation.

ObjectToString

public java.lang.Object ObjectToString(java.lang.String ob)
Returns a string representation of the object

Parameters:
ob - The object
Returns:
A string representation.

ObjectToString

public java.lang.Object ObjectToString(byte[] ob)
Returns a string representation of the object

Parameters:
ob - The object
Returns:
A string representation.

ObjectToString

public java.lang.Object ObjectToString(java.lang.Throwable ob,
                                       java.lang.String trace)
Returns a string representation of the object

Parameters:
ob - The Throwable
trace - The stack trace
Returns:
A string representation.

getContext

public java.lang.Object getContext()
Returns the JSR223 context.

Returns:
The JSR223 context.

getSession

public ISession getSession(java.lang.String name,
                           short clientIsNew,
                           int timeout)
                    throws java.lang.Exception
Return a session handle shared among all JavaBridge instances. If it is a HTTP session, the session is shared with the servlet or jsp.

Parameters:
name - The session name, if any
clientIsNew - true, if the client wants a new session
timeout - session timeout in seconds. If timeout is <= 0, the session will never expire
Returns:
The session context.
Throws:
java.lang.Exception
See Also:
ISession

makeClosure

public java.lang.Object makeClosure(long object,
                                    java.util.Map names)
Create a dynamic proxy proxy for calling PHP code.
Example:
java_closure($this, $map);

Parameters:
object - the PHP environment (the php instance)
names - maps java to php names
Returns:
the proxy

makeClosure

public java.lang.Object makeClosure(long object,
                                    java.util.Map names,
                                    java.lang.Class[] interfaces)
Create a dynamic proxy proxy for calling PHP code.
Example:
java_closure($this, $map, $interfaces);

Parameters:
object - the PHP environment (the php instance)
names - maps java to php names
interfaces - list of interfaces which the PHP environment must implement
Returns:
the proxy

makeClosure

public java.lang.Object makeClosure(long object,
                                    java.lang.String name,
                                    java.lang.Class iface)
Create a dynamic proxy proxy for calling PHP code.
Example:
java_closure($this, $map, $interfaces);

Parameters:
object - the PHP environment (the php instance)
name - maps all java names to this php name
iface - interface which the PHP environment must implement
Returns:
the proxy

makeClosure

public java.lang.Object makeClosure(long object,
                                    java.util.Map names,
                                    java.lang.Class iface)
Create a dynamic proxy proxy for calling PHP code.
Example:
java_closure($this, $map, $interfaces);

Parameters:
object - the PHP environment (the php instance)
names - maps java to php names
iface - interface which the PHP environment must implement
Returns:
the proxy

makeClosure

public java.lang.Object makeClosure(long object,
                                    java.lang.String name)
Create a dynamic proxy proxy for calling PHP code.
Example:
java_closure($this, "clickMe");

Parameters:
object - the PHP environment (the php instance)
name - maps all java names to this php name
Returns:
the proxy

makeClosure

public java.lang.Object makeClosure(long object,
                                    java.lang.String name,
                                    java.lang.Class[] interfaces)
Create a dynamic proxy proxy for calling PHP code.
Example:
java_closure($this, "clickMe", $interfaces);

Parameters:
object - the PHP environment (the php instance)
name - maps all java names to this php name
interfaces - list of interfaces which the PHP environment must implement
Returns:
the proxy

makeClosure

public java.lang.Object makeClosure(long object)
Create a dynamic proxy proxy for calling PHP code.
Example:
java_closure();
java_closure($this);

Parameters:
object - the PHP environment (the php instance)
Returns:
the proxy

deserialize

public int deserialize(java.lang.String serialID,
                       int timeout)
                throws java.lang.IllegalArgumentException
Load the object from the session store. The C code requires that this method is called "deserialize" even though it doesn't deserialize anything. See the JSessionAdapter in the php_java_lib folder. For real serialization/deserialization see the JPersistenceAdapter in the php_java_lib folder.

Parameters:
serialID - The key
timeout - The timeout, usually 1400 seconds.
Returns:
the new object identity.
Throws:
java.lang.IllegalArgumentException - if serialID does not exist anymore.

serialize

public java.lang.String serialize(java.lang.Object obj,
                                  int timeout)
                           throws java.lang.IllegalArgumentException
Store the object in the session store and return the serial id. The C code requires that this method is called "serialize" even though it doesn't serialize anything. See the JSessionAdapter in the php_java_lib folder. For real serialization/deserialization see the JPersistenceAdapter in the php_java_lib folder.

Parameters:
obj - The object
timeout - The timeout, usually 1400 seconds
Returns:
the serialID
Throws:
java.lang.IllegalArgumentException

offsetExists

public boolean offsetExists(java.lang.Object table,
                            java.lang.Object off)
Checks if a given position exists.

Parameters:
table - The table.
off - The offset
Returns:
true if an element exists at this position, false otherwise.

offsetGet

public java.lang.Object offsetGet(java.lang.Object table,
                                  java.lang.Object off)
Returns the object at the posisition.

Parameters:
table - The table.
off - The offset.
Returns:
The object at the given position.

beginDocument

public void beginDocument()
Selects the asynchronous protocol mode.


endDocument

public void endDocument()
                 throws java.lang.Throwable
Back to synchronous protocol mode

Throws:
java.lang.Throwable

offsetSet

public void offsetSet(java.lang.Object table,
                      java.lang.Object off,
                      java.lang.Object val)
Set an object at position.

Parameters:
table - The table
off - The offset.
val - The value

offsetUnset

public void offsetUnset(java.lang.Object table,
                        java.lang.Object off)
Remove an object from the position.

Parameters:
table - The table.
off - The offset.

recycle

public void recycle()
Re-initialize the current bridge for keep-alive See php.ini option java.persistent_connections


getString

public java.lang.String getString(byte[] b,
                                  int start,
                                  int length)
Return a new string using the current file encoding (see java_set_file_encoding()).

Parameters:
b - The byte array
start - The start index
length - The number of bytes to encode.
Returns:
The encoded string.

getCachedString

public java.lang.String getCachedString(byte[] b,
                                        int start,
                                        int length)
Return a cached string using the current file encoding (see java_set_file_encoding()).

Parameters:
b - The byte array
start - The start index
length - The number of bytes to encode.
Returns:
The encoded string.

typeExists

public boolean typeExists(java.lang.String name)
Check if a given class exists.

Parameters:
name - The class name
Returns:
true if the type exists, false otherwise

getLastException

public java.lang.Throwable getLastException()
Return the first java.lang.RuntimeException/java.lang.Error in a chain or the last java.lang.Exception.

Returns:
the last stored exception or null

clearLastException

public void clearLastException()
Clear the last Exception