org.less4j
Class Actor

java.lang.Object
  extended by org.less4j.Actor

public class Actor
extends java.lang.Object

The Actor provides a rich state and a flat "full-stack" API to develop complex entreprise Web 2.0 controllers of SQL databases and LDAP directories.

Table of Content

The actor members and methods are grouped by aspects of its applications as follow:

Environment: test, configuration, logOut, logInfo, logError. logAudit,
Test or production environment, standard output and error. No fancy logging formats and long stack traces, the bare minimum for all actor: STDOUT and STDERR, a compact exception trace and unconstrained logging categories for information.
IRTD2: salts, identity, rights, time, digest, digested, irtd2Digest, irtd2Digested,
Identification, authorization and audit of the user agent, without the woes of HttpServletSession. A practical implementation of a simple protocol based on HTTP cookies and SHA1 digest, cross plateform and designed to let the weight of persistent sessions be distributed on the clients. Eventually, it also provides an effective audit follow the multiple paths of interactions of a single user and detect fraud attemps.
HTTP: url, about, context, request, response, httpError, http200Ok, http302Redirect,
...
Regular JSON: json, jsonGET, jsonPOST, jsonDigest, jsonResponse,
...
SQL: sql, sqlOpenJ2EE, sqlOpenJDBC, sqlClose, sqlQuery, sqlTable, sqlObject, sqlObjects, sqlCollection, sqlRelations, sqlUpdate, sqlBatch.
Enough SQL conveniences to declare, update and query a database, including support for all the Object Relational Mapping you will ever need in a JSON application: table, relations, collection and object(s).
LDAP: ldap, ldapOpen, ldapClose, ldapResolve, ldapUpdate, ldapCreate
...

Copyright © 2006 Laurent A.V. Szyster

Version:
0.30

Field Summary
 java.lang.String about
          A usefull copy of request.getPathInfo() to quickly dispatch the request's through simple String tests.
 JSON.Object configuration
          A copy of the servlet controller's configuration, mapping all options listed in the servlet's XML configuration file and whose name start with "less4j".
 java.lang.String context
          A usefull copy of request.getContextPath() to build dispatch the URL or redirect relatively to this servlet's context.
 java.lang.String digest
          The authentication and audit digest of this response, as set from the HTTP request's IRTD2 cookie by a call to the notAuthorized or Authorize method.
 java.lang.String digested
          The authentication and audit digest of the previous request, as set from the HTTP request's IRTD2 cookie by a call to the notAuthorized or Authorize method.
 java.lang.String identity
          The authenticated identity of this Actor's web user, as set from the HTTP request's IRTD2 cookie by a call to the notAuthorized or Authorize method.
 java.lang.String irtd2
          The IRDT2 state for this actor's actions as an US ASCII string.
 JSON.Object json
          The JSON object associated with the Actor's request and response.
 javax.naming.directory.InitialDirContext ldap
          An open LDAP connection or null.
 javax.servlet.http.HttpServletRequest request
          The HttpServletRequest handled by this Actor instance.
 javax.servlet.http.HttpServletResponse response
          The HttpServletResponse completed by this Actor instance.
 java.lang.String rights
          The authenticated rights of this Actor's web user, as set from the HTTP request's IRTD2 cookie by a call to the notAuthorized or the Authorize method.
 byte[][] salts
          The IRTD2 salts, encoded as 8-bit bytes
 java.sql.Connection sql
          An open JDBC connection or null.
 boolean test
          A boolean that indicates wether the Actor runtime environment is a test or a production one.
 int time
          The time of this Actor's, in seconds since epoch (ie: 01/01/1970), as an java int value
 java.lang.String url
          A usefull copy of request.getRequestURL().toString() to quickly dispatch the request's through simple String tests.
 
Constructor Summary
Actor(JSON.Object conf)
          Initialize a new Actor to test a controller servlet's configuration when it is initialized.
Actor(JSON.Object conf, javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse res)
          Initialize a new Actor to handle an HTTP request and response, set the Actor's audit digest salt and eventually load ...
 
Method Summary
 void html200Ok(java.lang.String body)
          Send a 200 Ok HTTP response with the appropriate headers for an HTML string using the UTF-8 character set encoding.
 void http302Redirect(java.lang.String location)
          Try to send a 302 HTTP Redirect response to the a relative or absolute location with the XML string <rest302Redirect/> as body.
 void httpError(int code)
          Try to send an HTTP error response, rely on the J2EE implementation to produce headers and body.
 java.lang.String httpLocation(java.lang.String location)
          A convenience to validate a location as an absolute URL.
 byte[] httpPOST(int limit)
          ...
 void httpResponse(int code, byte[] body, java.lang.String type, java.lang.String charset)
          Try to send an HTTP response with the appropriate headers for an arbitrary bytes string as body, a given content type and charset.
 void httpResponse(int code, java.lang.String body, java.lang.String type, java.lang.String charset)
          Send an HTTP response with the appropriate headers for a UNICODE string as body, a given content type and charset.
 void irtd2Digest()
          Literally "digest a cookie", transform the IRTD2 cookie sent with the request into a new cookie bearing the Actor's time, to be sent with the response.
 boolean irtd2Digested(int timeout)
          Try to collect a IRTD2 cookie in the request and test its digest against the secret(s) set by configuration for this actor's controller, digest a new cookie only if a the digested cookie is still valid in time and bears the signature of this servlet, return false otherwise.
 void jsonDigest(java.lang.String digestedName, java.lang.String digestName)
           
 boolean jsonDigested(java.lang.String digestedName, java.lang.String digestName)
           
 boolean jsonGET(int containers, int iterations)
           
 boolean jsonGET(int containers, int iterations, JSONR.Type type)
           
 boolean jsonPOST(int limit, int containers, int iterations)
          Try to read and parse the body of a POST request, assuming it contains a content of type application/json encoded in UTF-8 and fitting in a limited buffer.
 boolean jsonPOST(int limit, int containers, int iterations, JSONR.Type type)
           
 void jsonResponse(int code)
          Try to complete an HTTP/1.X response code with the actor's JSON object encoded in UTF-8 as body and audit the response, or log an error.
 void jsonResponse(int code, byte[] body)
          Try to complete an HTTP/1.X response code with a byte string as body and audit the response, or log an error.
 void jsonResponse(int code, java.lang.String body)
          Try to complete an HTTP/1.X response code with a string encoded in UTF-8 as body and audit the response, or log an error.
 void ldapClose()
          Try to close the current LDAP connection.
 boolean ldapCreate(java.lang.String dn, JSON.Object object, java.util.Iterator names)
          Try to create an LDAP context with attributes values from a JSON.O object for the given attribute names, return true if the context was created, false otherwise.
 boolean ldapOpen(java.lang.String url)
          Try to open a new anonymous connection to the LDAP server configured, given principal and credentials.
 boolean ldapOpen(java.lang.String url, java.lang.Object principal, java.lang.Object credentials)
          Try to open a new connection (establish a new "initial directory context" in j-speak) to the LDAP server configured, using a given principal and credentials.
 boolean ldapResolve(java.lang.String dn, java.util.Map map, java.util.Iterator names)
          Try to resolve an LDAP context and update a Map with the attributes named by the names iterator either as null, strings or JSON.Array of strings, then return true if the context's name was resolved, false otherwise.
 boolean ldapUpdate(java.lang.String dn, JSON.Object object, java.util.Iterator names)
           
 void logAudit(int status)
          Log an audit of this HTTP request and response in one line.
 void logError(java.lang.Throwable error)
          Write a compact stack trace to STDERR in the "StackTrace" category, in one line, like: StackTrace: 34|thrower.called 12|catcher.calling Also, if test is false, log the JSON object of this actor.
 void logInfo(java.lang.String message, java.lang.String category)
          Write a categorized message to STDERR, as: category: message Again, you should use a log-posprocessor to add audit information to your logs.
 void logOut(java.lang.String message)
          Write a message to STDOUT, as one line: message If you cannot apply Resin's excellent configuration of STDOUT for your web applications: http://wiki.caucho.com/Stdout-log use multilog or any other log post-processor to add timestamp and other usefull audit information, from outside your application where it belong.
 java.lang.Integer sqlBatch(java.lang.String statement, java.util.Iterator params)
          Try to execute a prepared UPDATE, INSERT, DELETE or DDL statement with many arguments iterator, close the JDBC/DataSource statement and returns the number of rows updated.
 void sqlClose()
          Try to rollback any pending transaction and then close the current JDBC connection.
 JSON.Array sqlCollection(java.lang.String statement, java.lang.String[] arguments, int fetch)
          Try to query the sql JDBC connection with an SQL statement and argument names, returns a JSON.Array as a collection for the first row in the result set or null if the result set was empty.
 JSON.Object sqlDictionary(java.lang.String statement, java.lang.String[] arguments, int fetch)
          Try to query the sql JDBC connection with an SQL statement and argument names, returns a JSON.Object that maps the first column of the result set to the second or null if the result set was empty.
 JSON.Object sqlObject(java.lang.String statement, java.lang.String[] arguments, int fetch)
          try { $.json.put("object", ($.
 JSON.Array sqlObjects(java.lang.String statement, java.lang.String[] arguments, int fetch)
          Synopsis try { $.json.put("objects", ($.
 boolean sqlOpenJ2EE(java.lang.String datasource)
          Try to open a J2EE datasource and disable AutoCommit, return true and if in "test" mode, log information, or return false and log error.
 boolean sqlOpenJDBC(java.lang.String dburl, java.lang.String username, java.lang.String password)
          Try to open a JDBC connection from its URL, with the given username and password, disable AutoCommit.
 java.lang.Object sqlQuery(java.lang.String statement, java.util.Iterator args, int fetch, SQL.ORM collector)
          Try to query the sql JDBC connection with an SQL statement and an argument values iterator, use an ORM to return a JSON.Array, a JSON.Object or null if the result set was empty.
 JSON.Array sqlRelations(java.lang.String statement, java.lang.String[] arguments, int fetch)
          Try to query the sql JDBC connection with an SQL statement and an argument names, return a JSON.Array of JSON.Arrays as relations or null if the result set was empty.
 JSON.Object sqlTable(java.lang.String statement, java.lang.String[] arguments, int fetch)
          Try to query the sql JDBC connection with an SQL statement and an argument names, return a JSON.Object with the obvious "columns" and "rows" members, or null if the result set was empty.
 java.lang.Integer sqlUpdate(java.lang.String statement)
          Try to execute and UPDATE, INSERT, DELETE or DDL statement, close the JDBC/DataSource statement, return the number of rows updated.
 java.lang.Integer sqlUpdate(java.lang.String statement, java.util.Iterator args)
          Try to execute a prepared UPDATE, INSERT, DELETE or DDL statement with an arguments iterator, close the JDBC/DataSource statement and return the number of rows updated.
 java.lang.StringBuffer strb(java.lang.StringBuffer sb)
          Serialize this Actor's public state to a JSON StringBuffer
 java.lang.String toString()
          Return a JSON String of this Actor's public state.
 
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

about

public java.lang.String about
A usefull copy of request.getPathInfo() to quickly dispatch the request's through simple String tests.


configuration

public JSON.Object configuration
A copy of the servlet controller's configuration, mapping all options listed in the servlet's XML configuration file and whose name start with "less4j".


context

public java.lang.String context
A usefull copy of request.getContextPath() to build dispatch the URL or redirect relatively to this servlet's context.


digest

public java.lang.String digest
The authentication and audit digest of this response, as set from the HTTP request's IRTD2 cookie by a call to the notAuthorized or Authorize method.


digested

public java.lang.String digested
The authentication and audit digest of the previous request, as set from the HTTP request's IRTD2 cookie by a call to the notAuthorized or Authorize method.


identity

public java.lang.String identity
The authenticated identity of this Actor's web user, as set from the HTTP request's IRTD2 cookie by a call to the notAuthorized or Authorize method.


irtd2

public java.lang.String irtd2
The IRDT2 state for this actor's actions as an US ASCII string.


json

public JSON.Object json
The JSON object associated with the Actor's request and response.


ldap

public javax.naming.directory.InitialDirContext ldap
An open LDAP connection or null.


request

public javax.servlet.http.HttpServletRequest request
The HttpServletRequest handled by this Actor instance.


response

public javax.servlet.http.HttpServletResponse response
The HttpServletResponse completed by this Actor instance.


rights

public java.lang.String rights
The authenticated rights of this Actor's web user, as set from the HTTP request's IRTD2 cookie by a call to the notAuthorized or the Authorize method.


salts

public byte[][] salts
The IRTD2 salts, encoded as 8-bit bytes


sql

public java.sql.Connection sql
An open JDBC connection or null.


test

public boolean test
A boolean that indicates wether the Actor runtime environment is a test or a production one. It is set to false by defautlt.


time

public int time
The time of this Actor's, in seconds since epoch (ie: 01/01/1970), as an java int value


url

public java.lang.String url
A usefull copy of request.getRequestURL().toString() to quickly dispatch the request's through simple String tests.

Constructor Detail

Actor

public Actor(JSON.Object conf)
Initialize a new Actor to test a controller servlet's configuration when it is initialized.

Parameters:
conf - the controller's configuration HashMap

Actor

public Actor(JSON.Object conf,
             javax.servlet.http.HttpServletRequest req,
             javax.servlet.http.HttpServletResponse res)
Initialize a new Actor to handle an HTTP request and response, set the Actor's audit digest salt and eventually load ...

Parameters:
conf - the controller's configuration HashMap
req - the HTTP request to handle
res - the HTTP response to complete
Method Detail

html200Ok

public void html200Ok(java.lang.String body)
Send a 200 Ok HTTP response with the appropriate headers for an HTML string using the UTF-8 character set encoding. Audit a successfull response or log an error.

Synopsis

$.html200Ok("<hello-world/>")
where $ is an Actor instance.

Parameters:
body - a string

http302Redirect

public void http302Redirect(java.lang.String location)

Try to send a 302 HTTP Redirect response to the a relative or absolute location with the XML string

<rest302Redirect/>
as body.

Synopsis

$.http302Redirect("/resource?action")
Note that this method does not apply the sendRedirect method of HttpServletResponse in order to send its own response body. Instead it uses the URL convenience to validate a location as an absolute URL.

Parameters:
location - to redirect to

httpError

public void httpError(int code)

Try to send an HTTP error response, rely on the J2EE implementation to produce headers and body. Audit a successfull response or log an error.

Synopsis

Parameters:
code - HTTP error to send

httpLocation

public java.lang.String httpLocation(java.lang.String location)
A convenience to validate a location as an absolute URL.

Synopsis

Eventually complete a relative location to this Actor's requested resource

?action
relative to its application's domain
/resource
to the resource context path
resource
to produce a n absolute URL like
http://domain/resource?action
something quite usefull for redirection in a RESTfull controller.

Parameters:
location - a relative web location
Returns:
an absolute web URL

httpPOST

public byte[] httpPOST(int limit)
...

Synopsis

Parameters:
limit -
Returns:

httpResponse

public void httpResponse(int code,
                         byte[] body,
                         java.lang.String type,
                         java.lang.String charset)

Try to send an HTTP response with the appropriate headers for an arbitrary bytes string as body, a given content type and charset. Audit a successfull response or log an error.

Synopsis

Parameters:
code - the HTTP response code
body - a byte string
type - the response body content type
charset - the character set encoding used (eg: "ASCII")

httpResponse

public void httpResponse(int code,
                         java.lang.String body,
                         java.lang.String type,
                         java.lang.String charset)

Send an HTTP response with the appropriate headers for a UNICODE string as body, a given content type and charset. This method catches any UnsupportedEncodingException and uses the plateform default character set if the given encoding is not supported. Audit a successfull response or log an error.

Synopsis

$.httpResponse(200, "<hello-world/>", "text/xml", "ASCII")
where $ is an Actor instance.

Parameters:
body - a string
type - the resource content type
charset - the character set encoding used (eg: "UTF-8")

irtd2Digest

public void irtd2Digest()
Literally "digest a cookie", transform the IRTD2 cookie sent with the request into a new cookie bearing the Actor's time, to be sent with the response.

Synopis

The cookie value is a formatted string made as follow:

Cookie: IRTD2=identity roles time digested digest; 

where identity and roles are respectively Public Names and netstrings of 7-bit ASCII characters only, followed by the controller's time representation and two SHA1 hex digests: the client's last digest for this cookie and the one computed from the byte string that precedes it.

This method is usefull in authorization controllers, like user identification or roles attribution services.


irtd2Digested

public boolean irtd2Digested(int timeout)
Try to collect a IRTD2 cookie in the request and test its digest against the secret(s) set by configuration for this actor's controller, digest a new cookie only if a the digested cookie is still valid in time and bears the signature of this servlet, return false otherwise.

Synopsis

This method is expected to be called by the Actor's Controller before it handles the request, so it should not be called by less4j's applications.

Nevertheless, application developpers should understand what this method does and why it is so usefull for web controllers.

There are four benefits to expect from IRTD2 cookies for J2EE public applications:

  1. Remove the weight of statefull sessions in the J2EE container.
  2. Distribute the load of authorization on a cluster of servers without adding more contention and latency.
  3. Trace identifed and authorized interactions in sequence.
  4. Audit impersonation exploit by a man-in-the-middle.

Note that it does not prevent cookie theft but it does the only next-best actually possible for a public network application: detect and report fraudulent actions.

Parameters:
timeout - the limit of an IRTD2 cookie's age, in seconds
Returns:
true if the request failed to be authenticated

jsonDigest

public void jsonDigest(java.lang.String digestedName,
                       java.lang.String digestName)
Parameters:
digestedName -
digestName -

jsonDigested

public boolean jsonDigested(java.lang.String digestedName,
                            java.lang.String digestName)
Parameters:
digestedName -
digestName -
Returns:

jsonGET

public boolean jsonGET(int containers,
                       int iterations)
Parameters:
containers -
iterations -
Returns:

jsonGET

public boolean jsonGET(int containers,
                       int iterations,
                       JSONR.Type type)
Parameters:
containers -
iterations -
type -
Returns:

jsonPOST

public boolean jsonPOST(int limit,
                        int containers,
                        int iterations)

Try to read and parse the body of a POST request, assuming it contains a content of type application/json encoded in UTF-8 and fitting in a limited buffer. Return true on success or log an error and return false.

This is a controller's actor and less4j is a framework for entreprise web interfaces: there is no reason to accept JSON objects larger than the limit that fits its application.

Using a the servlet getReader method directly is not an option if the application controller must enforce reasonable input limits per request. Here's a good place to do it once for all JSON applications.

Returns:
true if successfull, false otherwise

jsonPOST

public boolean jsonPOST(int limit,
                        int containers,
                        int iterations,
                        JSONR.Type type)
Parameters:
limit -
containers -
iterations -
type -
Returns:

jsonResponse

public void jsonResponse(int code)

Try to complete an HTTP/1.X response code with the actor's JSON object encoded in UTF-8 as body and audit the response, or log an error.


jsonResponse

public void jsonResponse(int code,
                         byte[] body)

Try to complete an HTTP/1.X response code with a byte string as body and audit the response, or log an error.


jsonResponse

public void jsonResponse(int code,
                         java.lang.String body)

Try to complete an HTTP/1.X response code with a string encoded in UTF-8 as body and audit the response, or log an error.


ldapClose

public void ldapClose()
Try to close the current LDAP connection. Catch and log error any JNDI exception, log success in test mode.


ldapCreate

public boolean ldapCreate(java.lang.String dn,
                          JSON.Object object,
                          java.util.Iterator names)
Try to create an LDAP context with attributes values from a JSON.O object for the given attribute names, return true if the context was created, false otherwise.

Parameters:
dn - the distinguished name of the context created
object - the JSON.O object from which to set the attribute values
names - of the attributes to create
Returns:
true, false

ldapOpen

public boolean ldapOpen(java.lang.String url)
Try to open a new anonymous connection to the LDAP server configured, given principal and credentials. Catch any JNDI exception, return true on success and false otherwise, log an information message in test mode.

Returns:
true if the connection was successfull, false otherwise

ldapOpen

public boolean ldapOpen(java.lang.String url,
                        java.lang.Object principal,
                        java.lang.Object credentials)
Try to open a new connection (establish a new "initial directory context" in j-speak) to the LDAP server configured, using a given principal and credentials. Catch any JNDI exception, return true on success and false otherwise, log an information message in test mode.

Parameters:
principal - an LDAP user name
credentials - the associated password
Returns:
true if the connection was successfull, false otherwise

ldapResolve

public boolean ldapResolve(java.lang.String dn,
                           java.util.Map map,
                           java.util.Iterator names)
Try to resolve an LDAP context and update a Map with the attributes named by the names iterator either as null, strings or JSON.Array of strings, then return true if the context's name was resolved, false otherwise.

Synopsis

if ($.ldapOpen("ldap://host:port", "user", "pass")) try {
    JSON.Object attributes = new JSON.Object();
    if ($.ldapResolve(
        "uid=lszyster,ou=People,...", attributes, Simple.iterator(
            new String[]{"cn", "mail", "homeDirectory"}
            ) 
        ))
        ...
} catch (Exception e) {
    $.logError(e);
} finally {
    $.ldapClose();
}

The purpose of this method is to allow applications not to worry about the specialized types and the API details of JNDI. Instead they can use Map, List and String.

Note that if the Base instance's test is true, then values of the attributes resolved will be logged as one information message.

Parameters:
dn - the distinguished name to resolve
map - the Map to update
names - of the attribute values to get
Returns:
true if the name was resolved, false otherwise

ldapUpdate

public boolean ldapUpdate(java.lang.String dn,
                          JSON.Object object,
                          java.util.Iterator names)
Parameters:
dn - the distinguished name of the context created
object - the JSON.O object from which to set the attribute values
names - of the attributes to update
Returns:
true, false

logAudit

public void logAudit(int status)
Log an audit of this HTTP request and response in one line.

For instance:

LESS4J: identity roles time digested digest GET url HTTP/1.1 200
using by convention strings without whitespace for the identity and the enumeration of the rights granted. Practically, that fits email addresses or names that users allready use as principals.

Role names don't *need* whitespaces, they are pretty much constants defined at the network level (for instance products of an ASP or rigths over contents in a CMS, etc ...).

Note that digested is the digest of the previous request, the backlink to chain a session step by step ... and detect fraud.


logError

public void logError(java.lang.Throwable error)

Write a compact stack trace to STDERR in the "StackTrace" category, in one line, like:

StackTrace: 34|thrower.called 12|catcher.calling
Also, if test is false, log the JSON object of this actor.

Usage:

try {...} catch (Exception e) {logError (e);}

The purpose is to give debuggers a usefull "slice" of the stack trace: which error, where it occurred and what caused it. In its context, amongst other log lines, not spread all over the screen.

Without an error message, because developers need a stack trace of *unexpected* exception only. In such case any attempt to explicit it with a message would be ludicrous. Again, it's the meaning of the log context around that do give debuggers the most relevant information to understand why an error conditions was not handled by the application and how to fix it.

In production (not testing), what you need to audit errors is an image of the application context without confidential information: the entire JSON object model but none of the server's configuration.

StackTrace: error 34|thrower.called 12|catcher.calling {...}
This is what the helpdesk needs and it still fits on one line.

Parameters:
error - the throwable instance catched

logInfo

public void logInfo(java.lang.String message,
                    java.lang.String category)

Write a categorized message to STDERR, as:

category: message

Again, you should use a log-posprocessor to add audit information to your logs. Or apply Resin:

http://wiki.caucho.com/Stderr-log
Audit logs may inform about a completed transaction, an aborted action, a authorization failure or any hazardous event for which a trace is legaly required.

Categorization is unpredictable, it should not be restricted to levels of debugging which are usefull to programmers only.

Parameters:
message -
category -

logOut

public void logOut(java.lang.String message)

Write a message to STDOUT, as one line:

message
If you cannot apply Resin's excellent configuration of STDOUT for your web applications:
http://wiki.caucho.com/Stdout-log
use multilog or any other log post-processor to add timestamp and other usefull audit information, from outside your application where it belong.

Parameters:
message - the string logged to STDOUT

sqlBatch

public java.lang.Integer sqlBatch(java.lang.String statement,
                                  java.util.Iterator params)
                           throws java.sql.SQLException
Try to execute a prepared UPDATE, INSERT, DELETE or DDL statement with many arguments iterator, close the JDBC/DataSource statement and returns the number of rows updated.

Parameters:
statement - the SQL statement to execute
params - an Iterator of JSON.Arrays
Returns:
an Integer
Throws:
SQLException
java.sql.SQLException

sqlClose

public void sqlClose()
Try to rollback any pending transaction and then close the current JDBC connection. Allways log error and log success only in test mode.


sqlCollection

public JSON.Array sqlCollection(java.lang.String statement,
                                java.lang.String[] arguments,
                                int fetch)
                         throws java.sql.SQLException
Try to query the sql JDBC connection with an SQL statement and argument names, returns a JSON.Array as a collection for the first row in the result set or null if the result set was empty.

Synopsis

try {
    $.json.put("collection", ($.sqlCollection(
        "select COLUMN from TABLE where KEY=?", 
        new String[]{"key"},
        100
        ));
} catch (SQLException e) {
    $.logError(e);
}

Parameters:
statement - to prepare and execute as a query
arguments - an array of String[]
fetch - the number of rows to fetch
Returns:
a JSON.Array as collection or null
Throws:
an - SQLException
java.sql.SQLException

sqlDictionary

public JSON.Object sqlDictionary(java.lang.String statement,
                                 java.lang.String[] arguments,
                                 int fetch)
                          throws java.sql.SQLException
Try to query the sql JDBC connection with an SQL statement and argument names, returns a JSON.Object that maps the first column of the result set to the second or null if the result set was empty.

Synopsis

try {
    $.json.put("dictionary", ($.sqlDictionary(
        "select KEY, VALUE from TABLE where VALUE > ?", 
        new String[]{"value"},
        100
        ));
} catch (SQLException e) {
    $.logError(e);
}

Parameters:
statement - to prepare and execute as a query
arguments - an array of String[]
fetch - the number of rows to fetch
Returns:
a JSON.Object as dictionnary or null
Throws:
java.sql.SQLException

sqlObject

public JSON.Object sqlObject(java.lang.String statement,
                             java.lang.String[] arguments,
                             int fetch)
                      throws java.sql.SQLException
try {
    $.json.put("object", ($.sqlObject(
        "select * from TABLE where VALUE = ?", 
        new String[]{"value"}
        ));
} catch (SQLException e) {
    $.logError(e);
}

Parameters:
statement - to prepare and execute as a query
arguments - an array of String[]
Returns:
a JSON.Object or null
Throws:
an - SQLException
java.sql.SQLException

sqlObjects

public JSON.Array sqlObjects(java.lang.String statement,
                             java.lang.String[] arguments,
                             int fetch)
                      throws java.sql.SQLException

Synopsis

try {
    $.json.put("objects", ($.sqlObjects(
        "select * from TABLE where VALUE > ?", 
        new String[]{"value"},
        100
        ));
} catch (SQLException e) {
    $.logError(e);
}

Parameters:
statement - to prepare and execute as a query
arguments - an array of String[]
Returns:
a JSON.Array of JSON.Objects or null
Throws:
an - SQLException
java.sql.SQLException

sqlOpenJ2EE

public boolean sqlOpenJ2EE(java.lang.String datasource)
Try to open a J2EE datasource and disable AutoCommit, return true and if in "test" mode, log information, or return false and log error.

Returns:
true if the connection was successfull, false otherwise

sqlOpenJDBC

public boolean sqlOpenJDBC(java.lang.String dburl,
                           java.lang.String username,
                           java.lang.String password)
Try to open a JDBC connection from its URL, with the given username and password, disable AutoCommit. Allways log error, log success only in test mode.

Returns:
true if the connection was successfull, false otherwise

sqlQuery

public java.lang.Object sqlQuery(java.lang.String statement,
                                 java.util.Iterator args,
                                 int fetch,
                                 SQL.ORM collector)
                          throws java.sql.SQLException
Try to query the sql JDBC connection with an SQL statement and an argument values iterator, use an ORM to return a JSON.Array, a JSON.Object or null if the result set was empty.

Synopsis

try {
    JSON.Array relations = (JSON.Array) $.sqlQuery(
        "select * from TABLE where KEY = ? and VALUE > ?", 
        Simple.iterator (new Object[]{"key", new Integer(10)}),
        100, SQL.relations
        );
} catch (SQLException e) {
    $.logError(e);
}

Parameters:
statement - to prepare and execute as a query
args - an iterator through arguments
fetch - the number of rows to fetch
collector - the ORM used to map the result set
Returns:
a JSON.Array, a JSON.Object or null
Throws:
java.sql.SQLException

sqlRelations

public JSON.Array sqlRelations(java.lang.String statement,
                               java.lang.String[] arguments,
                               int fetch)
                        throws java.sql.SQLException
Try to query the sql JDBC connection with an SQL statement and an argument names, return a JSON.Array of JSON.Arrays as relations or null if the result set was empty.

Synopsis

try {
    $.json.put("relations", $.sqlRelations(
        "select * from TABLE where KEY=?", 
        new String[]{"key"},
        100
        ))
} catch (SQLException e) {
    $.logError(e);
}

Parameters:
statement - to prepare and execute as a query
arguments - an array of String[]
fetch - the number of rows to fetch
Returns:
a JSON.Array of relations or null
Throws:
an - SQLException
java.sql.SQLException

sqlTable

public JSON.Object sqlTable(java.lang.String statement,
                            java.lang.String[] arguments,
                            int fetch)
                     throws java.sql.SQLException
Try to query the sql JDBC connection with an SQL statement and an argument names, return a JSON.Object with the obvious "columns" and "rows" members, or null if the result set was empty.

Synopsis

try {
    $.json.put("table", $.sqlTable(
        "select * from TABLE where KEY=?", 
        new String[]{"key"},
        100
        ))
} catch (SQLException e) {
    $.logError(e);
}

Parameters:
statement - to prepare and execute as a query
arguments - an array of String[]
fetch - the number of rows to fetch
Returns:
a JSON.Object or null
Throws:
java.sql.SQLException

sqlUpdate

public java.lang.Integer sqlUpdate(java.lang.String statement)
                            throws java.sql.SQLException
Try to execute and UPDATE, INSERT, DELETE or DDL statement, close the JDBC/DataSource statement, return the number of rows updated.

Parameters:
statement - the SQL statement to execute
Returns:
-1 if the statement failed, 0 if no row update took place, or the numbers of rows updated, deleted or inserted.
Throws:
java.sql.SQLException

sqlUpdate

public java.lang.Integer sqlUpdate(java.lang.String statement,
                                   java.util.Iterator args)
                            throws java.sql.SQLException
Try to execute a prepared UPDATE, INSERT, DELETE or DDL statement with an arguments iterator, close the JDBC/DataSource statement and return the number of rows updated.

Parameters:
statement - the SQL statement to execute
args - an Iterator of arguments
Returns:
-1 if the statement failed, 0 if no row update took place, or the numbers of rows updated, deleted or inserted.
Throws:
java.sql.SQLException

strb

public java.lang.StringBuffer strb(java.lang.StringBuffer sb)
Serialize this Actor's public state to a JSON StringBuffer


toString

public java.lang.String toString()
Return a JSON String of this Actor's public state.

Synopsis

$.json200Ok ($.toString());

The string returned matches this JSONR pattern:

{
    "identity": "$[0-9a-zA-Z]+^", 
    "rights": "$[0-9a-zA-Z]+^",
    "time": 0, 
    "digest": "[0-9a-f]{20}",
    "digested": "[0-9a-f]{20}",
    "about": [""],
    "json": null
}

Note that it does not include the controller's private part of its state: configuration, salt, salted, sql or ldap.

Overrides:
toString in class java.lang.Object