coliver 2003/12/26 23:30:42
Modified: lib jars.xml
src/java/org/apache/cocoon/components/flow/javascript/fom
FOM_JavaScriptInterpreter.java
src/documentation/xdocs/userdocs/flow api.xml book.xml
Added: lib/core javacApi.jar javacImpl.jar
src/java/org/apache/cocoon/components/flow/javascript/fom
CompilingClassLoader.java
src/documentation/xdocs/userdocs/flow java.xml
Log:
Added support for dynamic compilation of Java classes to flow component
Revision Changes Path
1.141 +17 -1 cocoon-2.1/lib/jars.xml
Index: jars.xml
===================================================================
RCS file: /home/cvs/cocoon-2.1/lib/jars.xml,v
retrieving revision 1.140
retrieving revision 1.141
diff -u -r1.140 -r1.141
--- jars.xml 12 Dec 2003 15:21:09 -0000 1.140
+++ jars.xml 27 Dec 2003 07:30:41 -0000 1.141
@@ -621,6 +621,22 @@
</file>
<file>
+ <title>JavacAPI</title>
+ <description>Embedded Java Compiler API</description>
+ <used-by>Control flow</used-by>
+ <lib>core/javacApi.jar</lib>
+ <homepage>ftp://ftp.primaryinterface.com/pub/javacAPI</homepage>
+ </file>
+
+ <file>
+ <title>JavacAPI Eclipse Implementation</title>
+ <description>Embedded Java Compiler API implemented with Eclipse JDT
Core</description>
+ <used-by>Control flow</used-by>
+ <lib>core/javacImpl.jar</lib>
+ <homepage>ftp://ftp.primaryinterface.com/pub/javacAPI</homepage>
+ </file>
+
+ <file>
<title>Spark</title>
<description>
Spark is a Java library that converts data in Macromedias SWF ("Flash")
1.1 cocoon-2.1/lib/core/javacApi.jar
<<Binary file>>
1.1 cocoon-2.1/lib/core/javacImpl.jar
<<Binary file>>
1.14 +154 -20
cocoon-2.1/src/java/org/apache/cocoon/components/flow/javascript/fom/FOM_JavaScriptInterpreter.java
Index: FOM_JavaScriptInterpreter.java
===================================================================
RCS file:
/home/cvs/cocoon-2.1/src/java/org/apache/cocoon/components/flow/javascript/fom/FOM_JavaScriptInterpreter.java,v
retrieving revision 1.13
retrieving revision 1.14
diff -u -r1.13 -r1.14
--- FOM_JavaScriptInterpreter.java 20 Nov 2003 15:31:29 -0000 1.13
+++ FOM_JavaScriptInterpreter.java 27 Dec 2003 07:30:42 -0000 1.14
@@ -56,6 +56,8 @@
import java.io.OutputStream;
import java.io.Reader;
import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.StringTokenizer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -81,10 +83,14 @@
import org.apache.commons.jxpath.JXPathIntrospector;
import org.apache.commons.jxpath.ri.JXPathContextReferenceImpl;
import org.apache.excalibur.source.Source;
+import org.apache.excalibur.source.SourceResolver;
+import org.apache.excalibur.source.SourceValidity;
import org.mozilla.javascript.*;
import org.mozilla.javascript.continuations.Continuation;
+import org.mozilla.javascript.NativeJavaPackage;
import org.mozilla.javascript.tools.ToolErrorReporter;
import org.mozilla.javascript.tools.shell.Global;
+import org.apache.excalibur.source.SourceResolver;
/**
* Interface with the JavaScript interpreter.
@@ -127,6 +133,9 @@
*/
Global scope;
+ CompilingClassLoader classLoader;
+ Map javaSource = new HashMap();
+ String[] javaSourcePath;
/**
* List of <code>String</code> objects that represent files to be
@@ -182,6 +191,26 @@
if ("enabled".equalsIgnoreCase(debugger)) {
enableDebugger = true;
}
+
+ if (reloadScripts) {
+ String classPath
+ = config.getChild("classpath").getValue(null);
+ synchronized (javaSource) {
+ if (classPath == null) {
+ javaSourcePath = new String[]{""};
+ } else {
+ StringTokenizer izer =
+ new StringTokenizer(classPath, ";");
+ int i = 0;
+ javaSourcePath = new String[izer.countTokens()+ 1];
+ javaSourcePath[javaSourcePath.length - 1] = "";
+ while (izer.hasMoreTokens()) {
+ javaSourcePath[i++] = izer.nextToken();
+ }
+ }
+ updateSourcePath();
+ }
+ }
}
public void initialize()
@@ -214,6 +243,68 @@
}
}
+ private ClassLoader getClassLoader(boolean needsRefresh)
+ throws Exception {
+ if (!reloadScripts) {
+ return Thread.currentThread().getContextClassLoader();
+ }
+ synchronized (javaSource) {
+ SourceResolver sourceResolver = (SourceResolver)
+ manager.lookup(SourceResolver.ROLE);
+ boolean reload = needsRefresh || classLoader == null;
+ if (needsRefresh && classLoader != null) {
+ reload = false;
+ Iterator iter = javaSource.entrySet().iterator();
+ while (iter.hasNext()) {
+ Map.Entry e = (Map.Entry)iter.next();
+ String uri = (String)e.getKey();
+ SourceValidity validity =
+ (SourceValidity)e.getValue();
+ int valid = validity.isValid();
+ if (valid == SourceValidity.UNKNOWN) {
+ Source newSrc =
+ sourceResolver.resolveURI(uri);
+ valid = newSrc.getValidity().isValid(validity);
+ sourceResolver.release(newSrc);
+ }
+ if (valid != SourceValidity.VALID) {
+ reload = true;
+ javaSource.clear();
+ break;
+ }
+ }
+ }
+ if (reload) {
+ classLoader =
+ new
CompilingClassLoader(Thread.currentThread().getContextClassLoader(),
+ sourceResolver);
+ classLoader.addSourceListener(new
CompilingClassLoader.SourceListener() {
+ public void sourceCompiled(Source src) {
+ synchronized (javaSource) {
+ javaSource.put(src.getURI(),
+ src.getValidity());
+ }
+ }
+
+ public void sourceCompilationError(Source src,
+ String errMsg) {
+ throw
org.mozilla.javascript.Context.reportRuntimeError(ToolErrorReporter.getMessage("msg.uncaughtJSException",
+
errMsg));
+
+ }
+ });
+ updateSourcePath();
+ }
+ return classLoader;
+ }
+ }
+
+ private void updateSourcePath() {
+ if (classLoader != null) {
+ classLoader.setSourcePath(javaSourcePath);
+ }
+ }
+
/**
* Returns the JavaScript scope, a Scriptable object, from the user
* session instance. Each URI prefix, as returned by the [EMAIL
PROTECTED]
@@ -223,17 +314,17 @@
* @param environment an <code>Environment</code> value
* @return a <code>Scriptable</code> value
*/
- private Scriptable getSessionScope(Environment environment)
+ private ThreadScope getSessionScope(Environment environment)
throws Exception {
Map objectModel = environment.getObjectModel();
Request request = ObjectModelHelper.getRequest(objectModel);
- Scriptable scope = null;
+ ThreadScope scope = null;
Session session = request.getSession(false);
if (session != null) {
HashMap userScopes =
(HashMap)session.getAttribute(USER_GLOBAL_SCOPE);
if (userScopes != null) {
String uriPrefix = environment.getURIPrefix();
- scope = (Scriptable)userScopes.get(uriPrefix);
+ scope = (ThreadScope)userScopes.get(uriPrefix);
}
}
if (scope == null) {
@@ -275,10 +366,19 @@
public static class ThreadScope extends ScriptableObject {
+ ClassLoader classLoader;
/* true if this scope has assigned any global vars */
boolean useSession = false;
public ThreadScope() {
+ final String[] names = { "importClass"};
+
+ try {
+ this.defineFunctionProperties(names, ThreadScope.class,
+ ScriptableObject.DONTENUM);
+ } catch (PropertyException e) {
+ throw new Error(); // should never happen
+ }
}
public String getClassName() {
@@ -298,9 +398,37 @@
void reset() {
useSession = false;
}
+
+ // Override importClass to allow reloading of classes
+ public static void importClass(Context cx, Scriptable thisObj,
+ Object[] args,
+ Function funObj) {
+ for (int i = 0; i < args.length; i++) {
+ Object cl = args[i];
+ if (!(cl instanceof NativeJavaClass)) {
+ throw Context.reportRuntimeError("Not a Java class: " +
+ Context.toString(cl));
+ }
+ String s = ((NativeJavaClass) cl).getClassObject().getName();
+ String n = s.substring(s.lastIndexOf('.')+1);
+ Object val = thisObj.get(n, thisObj);
+ thisObj.put(n, thisObj, cl);
+ }
+ }
+
+ public void setupPackages(ClassLoader cl) throws Exception {
+ if (classLoader != cl) {
+ classLoader = cl;
+ Scriptable newPackages = new NativeJavaPackage("", cl);
+ newPackages.setParentScope(this);
+
newPackages.setPrototype(ScriptableObject.getClassPrototype(this,
"JavaPackage"));
+ super.put("Packages", this, newPackages);
+ }
+ }
+
}
- private Scriptable createThreadScope()
+ private ThreadScope createThreadScope()
throws Exception {
org.mozilla.javascript.Context context =
org.mozilla.javascript.Context.getCurrentContext();
@@ -312,11 +440,10 @@
// parent scope to null. This means that any variables created
// by assignments will be properties of "thrScope".
thrScope.setParentScope(null);
-
// Put in the thread scope the Cocoon object, which gives access
// to the interpreter object, and some Cocoon objects. See
// FOM_Cocoon for more details.
- Object args[] = {};
+ Object[] args = {};
FOM_Cocoon cocoon = (FOM_Cocoon)
context.newObject(thrScope, "FOM_Cocoon", args);
cocoon.setParentScope(thrScope);
@@ -347,7 +474,8 @@
*/
private void setupContext(Environment environment,
org.mozilla.javascript.Context context,
- Scriptable thrScope)
+ ThreadScope thrScope,
+ CompilingClassLoader classLoader)
throws Exception {
// Try to retrieve the scope object from the session instance. If
// no scope is found, we create a new one, but don't place it in
@@ -362,21 +490,25 @@
FOM_Cocoon cocoon = (FOM_Cocoon)thrScope.get("cocoon", thrScope);
long lastExecTime = ((Long)thrScope.get(LAST_EXEC_TIME,
thrScope)).longValue();
+ boolean needsRefresh = false;
+ if (reloadScripts) {
+ long now = System.currentTimeMillis();
+ if (now >= lastTimeCheck + checkTime) {
+ needsRefresh = true;
+ }
+ lastTimeCheck = now;
+ }
// We need to setup the FOM_Cocoon object according to the current
// request. Everything else remains the same.
- cocoon.setup(this, environment, manager, serviceManager,
avalonContext, getLogger());
+ thrScope.setupPackages(getClassLoader(needsRefresh));
+ cocoon.setup(this, environment, manager,
+ serviceManager, avalonContext,
+ getLogger());
+
// Check if we need to compile and/or execute scripts
synchronized (compiledScripts) {
List execList = new ArrayList();
- boolean needsRefresh = false;
- if (reloadScripts) {
- long now = System.currentTimeMillis();
- if (now >= lastTimeCheck + checkTime) {
- needsRefresh = true;
- }
- lastTimeCheck = now;
- }
// If we've never executed scripts in this scope or
// if reload-scripts is true and the check interval has expired
// or if new scripts have been specified in the sitemap,
@@ -489,10 +621,10 @@
context.setCompileFunctionsWithDynamicScope(true);
context.setErrorReporter(errorReporter);
FOM_Cocoon cocoon = null;
- Scriptable thrScope = getSessionScope(environment);
+ ThreadScope thrScope = getSessionScope(environment);
synchronized (thrScope) {
try {
- setupContext(environment, context, thrScope);
+ setupContext(environment, context, thrScope, classLoader);
cocoon = (FOM_Cocoon)thrScope.get("cocoon", thrScope);
// Register the current scope for scripts indirectly called
from this function
@@ -578,7 +710,9 @@
Scriptable kScope = k.getParentScope();
synchronized (kScope) {
FOM_Cocoon cocoon = (FOM_Cocoon)kScope.get("cocoon", kScope);
- cocoon.setup(this, environment, manager, serviceManager,
avalonContext, getLogger());
+ cocoon.setup(this, environment, manager,
+ serviceManager, avalonContext,
+ getLogger());
// Register the current scope for scripts indirectly called from
this function
cocoon.getRequest().setAttribute(FOM_JavaScriptFlowHelper.FOM_SCOPE, kScope);
1.1
cocoon-2.1/src/java/org/apache/cocoon/components/flow/javascript/fom/CompilingClassLoader.java
Index: CompilingClassLoader.java
===================================================================
/*
============================================================================
The Apache Software License, Version 1.1
============================================================================
Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
Redistribution and use in source and binary forms, with or without modifica-
tion, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. The end-user documentation included with the redistribution, if any, must
include the following acknowledgment: "This product includes software
developed by the Apache Software Foundation (http://www.apache.org/)."
Alternately, this acknowledgment may appear in the software itself, if
and wherever such third-party acknowledgments normally appear.
4. The names "Apache Cocoon" and "Apache Software Foundation" must not be
used to endorse or promote products derived from this software without
prior written permission. For written permission, please contact
[EMAIL PROTECTED]
5. Products derived from this software may not be called "Apache", nor may
"Apache" appear in their name, without prior written permission of the
Apache Software Foundation.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.apache.cocoon.components.flow.javascript.fom;
import java.net.MalformedURLException;
import java.util.Iterator;
import java.util.List;
import java.util.LinkedList;
import java.util.Map;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.io.IOException;
import java.io.InputStream;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.Reader;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.excalibur.source.Source;
import org.apache.excalibur.source.SourceResolver;
import org.tempuri.javac.JavaCompiler;
import org.tempuri.javac.JavaCompilerErrorHandler;
import org.tempuri.javac.JavaClassWriter;
import org.tempuri.javac.JavaClassWriterFactory;
import org.tempuri.javac.JavaClassReader;
import org.tempuri.javac.JavaClassReaderFactory;
import org.tempuri.javac.JavaSourceReader;
import org.tempuri.javac.JavaSourceReaderFactory;
import org.tempuri.javacImpl.eclipse.JavaCompilerImpl;
public class CompilingClassLoader extends ClassLoader {
SourceResolver sourceResolver;
JavaCompiler compiler;
Map output = new HashMap();
List sourcePath = new LinkedList();
HashSet sourceListeners = new HashSet();
public interface SourceListener {
public void sourceCompiled(Source src);
public void sourceCompilationError(Source src, String error);
}
protected Class findClass(String className)
throws ClassNotFoundException {
byte[] bytes = compile(className);
return defineClass(className, bytes, 0, bytes.length);
}
public CompilingClassLoader(ClassLoader parent,
SourceResolver sourceResolver) {
super(parent);
this.sourceResolver = sourceResolver;
this.compiler = new JavaCompilerImpl();
this.sourcePath.add("");
}
static class ClassCompilationException extends ClassNotFoundException {
public ClassCompilationException(String msg) {
super(msg);
}
}
public void addSourceListener(SourceListener listener) {
synchronized (sourceListeners) {
sourceListeners.add(listener);
}
}
public void removeSourceListener(SourceListener listener) {
synchronized (sourceListeners) {
sourceListeners.remove(listener);
}
}
private void notifyListeners(Source src, String err) {
SourceListener arr[];
synchronized (sourceListeners) {
arr = new SourceListener[sourceListeners.size()];
sourceListeners.toArray(arr);
}
if (err != null) {
for (int i = 0; i < arr.length; i++) {
arr[i].sourceCompilationError(src, err);
}
} else {
for (int i = 0; i < arr.length; i++) {
arr[i].sourceCompiled(src);
}
}
}
public void setSourcePath(String[] path) {
sourcePath.clear();
for (int i = 0; i < path.length; i++) {
sourcePath.add(path[i]);
}
sourcePath.add("");
}
private Source getSource(String className) {
Iterator iter = sourcePath.iterator();
while (iter.hasNext()) {
String prefix = (String)iter.next();
if (prefix.length() > 0) {
if (!prefix.endsWith("/")) {
prefix = prefix + "/";
}
}
String uri = prefix + className.replace('.', '/') + ".java";
Source src;
try {
src = sourceResolver.resolveURI(uri);
} catch (MalformedURLException ignored) {
continue;
} catch (IOException ignored) {
continue;
}
if (src.exists()) {
return src;
}
releaseSource(src);
}
return null;
}
private void releaseSource(Source src) {
sourceResolver.release(src);
}
class SourceReaderFactory implements JavaSourceReaderFactory {
public JavaSourceReader
getSourceReader(final String className)
throws IOException {
Source src = getSource(className);
if (src == null) return null;
try {
InputStream is = src.getInputStream();
byte[] buf = new byte[8192];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int count;
while ((count = is.read(buf, 0, buf.length)) > 0) {
baos.write(buf, 0, count);
}
baos.flush();
final Reader reader =
new BufferedReader(new InputStreamReader(new
ByteArrayInputStream(baos.toByteArray())));;
return new JavaSourceReader() {
public Reader getReader() {
return reader;
}
public String getClassName() {
return className;
}
};
} finally {
releaseSource(src);
}
}
}
private String makeFileName(String className)
throws IOException {
Source src = getSource(className);
if (src != null) {
String result = src.getURI();
releaseSource(src);
return result;
}
return className;
}
class ClassReaderFactory
implements JavaClassReaderFactory {
public JavaClassReader
getClassReader(final String className)
throws IOException {
final byte[] bytes =
(byte[])output.get(className);
if (bytes != null) {
return new JavaClassReader() {
public String getClassName() {
return className;
}
public InputStream getInputStream() {
return new ByteArrayInputStream(bytes);
}
};
}
String classFile = className.replace('.', '/') + ".class";
final InputStream is = getResourceAsStream(classFile);
if (is == null) {
return null;
}
return new JavaClassReader() {
public String getClassName() {
return className;
}
public InputStream getInputStream() {
return is;
}
};
}
}
class ClassWriterFactory
implements JavaClassWriterFactory {
public JavaClassWriter
getClassWriter(final String className) {
return new JavaClassWriter() {
public String
getClassName() {
return className;
}
public void writeClass(InputStream contents)
throws IOException {
byte[] buf = new byte[2048];
ByteArrayOutputStream s =
new ByteArrayOutputStream();
int count;
while ((count =
contents.read(buf, 0,
buf.length)) > 0) {
s.write(buf, 0, count);
}
s.flush();
System.out.println("Compiled: " + className);
output.put(className,
s.toByteArray());
}
};
}
}
class ErrorHandler implements JavaCompilerErrorHandler {
List errList = new LinkedList();
public void handleError(String className,
int line,
int column,
Object errorMessage) {
String msg = className;
try {
// try to it convert to a file name
msg =
makeFileName(className);
} catch (Exception ignored) {
// oh well, I tried
}
if (line > 0) {
msg += ": Line " + line;
}
if (column >= 0) {
msg += "." + column;
}
msg += ": ";
msg += errorMessage;
errList.add(msg);
}
public List getErrorList() {
return errList;
}
}
private byte[] compile(String className)
throws ClassNotFoundException {
byte[] result = (byte[])output.get(className);
if (result != null) {
return result;
}
Source src = getSource(className);
if (src == null) {
throw new ClassNotFoundException(className);
}
try {
// try to compile it
ErrorHandler errorHandler = new ErrorHandler();
compiler.compile(new String[] {className},
new SourceReaderFactory(),
new ClassReaderFactory(),
new ClassWriterFactory(),
errorHandler);
List errorList = errorHandler.getErrorList();
if (errorList.size() > 0) {
String msg = "Failed to compile Java class " + className
+": ";
Iterator iter = errorList.iterator();
while (iter.hasNext()) {
msg += "\n";
msg += (String)iter.next();
}
notifyListeners(src, msg);
throw new ClassCompilationException(msg);
}
notifyListeners(src, null);
return (byte[])output.get(className);
} finally {
releaseSource(src);
}
}
}
1.30 +1 -65 cocoon-2.1/src/documentation/xdocs/userdocs/flow/api.xml
Index: api.xml
===================================================================
RCS file: /home/cvs/cocoon-2.1/src/documentation/xdocs/userdocs/flow/api.xml,v
retrieving revision 1.29
retrieving revision 1.30
diff -u -r1.29 -r1.30
--- api.xml 10 Dec 2003 05:29:51 -0000 1.29
+++ api.xml 27 Dec 2003 07:30:42 -0000 1.30
@@ -14,12 +14,7 @@
<s1 title="Flowscript">
<p>Cocoon Flowscript is a JavaScript API to manage control flow based
on an
<link
href="http://cvs.cocoondev.org/cgi-bin/viewcvs.cgi/?cvsroot=rhino">extended</link>
- version of <link href="http://www.mozilla.org/rhino">Mozilla
Rhino</link> that supports continuations.</p>
- <s2 title="Table of Contents">
- <p><link href="#FOM">Flow Object Model</link></p>
- <p><link href="#Java">Calling Java</link></p>
- </s2>
-
+ version of the <link href="http://www.mozilla.org/rhino">Mozilla
Rhino</link> JavaScript interpreter that supports continuations.</p>
</s1>
<anchor id="FOM"/><s1 title="Flow Object Model">
<p>Cocoon provides a set of system objects for use by Flowscripts. We
call this set of objects the <em>Flow Object Model</em> (FOM).
@@ -732,65 +727,6 @@
</p>
</s3>
</s2>
- </s1>
- <anchor id="Java"/><s1 title="Calling Java">
- <p>
- You can easily call any Java code from your Flowscripts, for example:
- </p>
- <source>
- var map = new java.util.HashMap();
- map.put("foo", "bar");
- </source>
-
- <p>Classes in packages under <code>java</code> are accessible directly
in your scripts.</p>
- <p>Note that classes under <code>java.lang</code> are not automatically
imported, however:</p>
-
- <source>var n = new java.lang.Integer(3);</source>
-
- <p>All other java packages and classes are accessible under the property
<code>Packages</code>:</p>
-
- <source>var tree = new Packages.javax.swing.JTree();</source>
-
- <p>You can get the effect of Java imports using the
<code>importPackage()</code> and <code>importClass()</code> functions:</p>
- <table>
- <tr>
- <td>
- In Java:
- </td>
- <td>
- In JavaScript:
- </td>
- </tr>
- <tr>
- <td>
- import foo.*;
- </td>
- <td>
- importPackage(Packages.foo);
- </td>
- </tr>
- <tr>
- <td>
- import foo.Bar;
- </td>
- <td>
- importClass(Packages.foo.Bar);
- </td>
- </tr>
- </table>
- <p>Example:</p>
- <source>
- importPackage(java.util);
- var set = new TreeSet();</source>
- <p>
- </p>
- <p>
- If your Java classes have getters and setters you can access them as
properties in JavaScript:</p>
-<source>
- var d = new java.util.Date();
- d.year = 2003; // same effect as d.setYear(2003);
-</source>
- <p/>
</s1>
</body>
</document>
1.15 +1 -0 cocoon-2.1/src/documentation/xdocs/userdocs/flow/book.xml
Index: book.xml
===================================================================
RCS file:
/home/cvs/cocoon-2.1/src/documentation/xdocs/userdocs/flow/book.xml,v
retrieving revision 1.14
retrieving revision 1.15
diff -u -r1.14 -r1.15
--- book.xml 12 Oct 2003 13:04:48 -0000 1.14
+++ book.xml 27 Dec 2003 07:30:42 -0000 1.15
@@ -18,6 +18,7 @@
<menu-item label="Tutorial" href="tutor.html"/>
<menu-item label="Sitemap" href="sitemap.html"/>
<menu-item label="Flowscript" href="api.html"/>
+ <menu-item label="Calling Java" href="java.html"/>
<menu-item label="Views" href="views.html"/>
<menu-item label="JXTemplate" href="jxtemplate.html"/>
<menu-item label="JPath" href="jpath.html"/>
1.1 cocoon-2.1/src/documentation/xdocs/userdocs/flow/java.xml
Index: java.xml
===================================================================
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE document PUBLIC "-//APACHE//DTD Documentation V1.0//EN"
"../../dtd/document-v10.dtd">
<document>
<header>
<title>Advanced Control Flow</title>
<authors>
<person name="Christopher Oliver" email="[EMAIL PROTECTED]"/>
</authors>
</header>
<body>
<anchor id="Java"/><s1 title="Calling Java">
<p>
You can easily call any Java code from your Flowscripts, for example:
</p>
<source>
var map = new java.util.HashMap();
map.put("foo", "bar");
</source>
<s2 title="Imports">
<p>Classes in packages under <code>java</code> are accessible directly in
your scripts.</p>
<p>Note that classes under <code>java.lang</code> are not automatically
imported, however:</p>
<source>var n = new java.lang.Integer(3);</source>
<p>All other java packages and classes available to are accessible under
the property <code>Packages</code>:</p>
<source>var tree = new Packages.javax.swing.JTree();</source>
<p>You can get the effect of Java imports using the
<code>importPackage()</code> and <code>importClass()</code> functions:</p>
<table>
<tr>
<td>
In Java:
</td>
<td>
In JavaScript:
</td>
</tr>
<tr>
<td>
import foo.*;
</td>
<td>
importPackage(Packages.foo);
</td>
</tr>
<tr>
<td>
import foo.Bar;
</td>
<td>
importClass(Packages.foo.Bar);
</td>
</tr>
</table>
<p>Example:</p>
<source>
importPackage(java.util);
var set = new TreeSet();</source>
<p>
</p>
</s2>
<s2 title="Bean Properties">
<p>
If your Java classes have getters and setters you can access them as
properties in JavaScript:</p>
<source>
var d = new java.util.Date();
d.year = 2003; // same effect as d.setYear(2003);
</source>
<p/>
</s2>
<s2 title="Dynamic Compilation">
<p>
Cocoon includes an embedded Java compiler that can dynamically compile
Java source files and load and execute the resulting classes at runtime. During
development you can take advantage of this capability to rapidly develop, test,
and debug your applications.
</p>
<p>
The <link href="#cocoon">Cocoon</link> object provides a <link
href="#Cocoon.classes">classes</link> property that provides access to this
capability. If you select the fully qualified name of a Java class under this
property the Cocoon source resolver will be used to locate the source code for
the class.
</p>
<p>Example:</p>
<source>
// Cause com.xyz.MyClass to be compiled and loaded:
importClass(Packages.com.xyz.MyClass);
var obj = MyClass("foo", 123); // call a constructor
obj.someMethod(); // call a method
</source>
<p/>
<s3 title="Configuration">
<p>You control this behavior by specifying configuration properties in the
<code>cocoon.xconf</code> file located in the WEB-INF/ directory of your
application. The set these properties, locate the
<code>component-instance</code> element under <code>flow-interpreters</code>
whose <code>name</code> attribute has the value <code>"javascript"</code>. The
following properties may be set:
</p>
<table>
<tr>
<td>
Property:
</td>
<td>
Description:
</td>
</tr>
<tr>
<td>
reload-scripts
</td>
<td>
Determines whether Cocoon should attempt to detect changes to source
files and reload them. This applies to both JavaScript and Java source files.
</td>
</tr>
<tr>
<td>
check-time
</td>
<td>
Specifies an interval in milliseconds after Cocoon will check for
changes to source files (ignored if reload-scripts is false or unspecified)
</td>
</tr>
<tr>
<td>
classpath
</td>
<td>
A semicolon separated list of URL's that will be searched for Java
source files.
</td>
</tr>
</table>
<p>Example:</p>
<source><![CDATA[
<flow-interpreters default="javascript" logger="flow">
<!-- FOM (Flow Object Model) -->
<component-instance
class="org.apache.cocoon.components.flow.
javascript.fom.FOM_JavaScriptInterpreter" name="javascript">
<load-on-startup>resource://org/apache/cocoon/components/
flow/javascript/fom/fom_system.js</load-on-startup>
<reload-scripts>true</reload-scripts>
<check-time>4000</check-time>
<classpath>file:C:/dev/myPackages;src/java</classpath>
<debugger>enabled</debugger>
</component-instance>
</flow-interpreters>
]]></source>
</s3>
</s2>
<p/>
</s1>
</body>
</document>