Return-Path:
Cocoon Flowscript is a JavaScript API to manage control flow based on an
extended
- version of Mozilla Rhino that supports continuations. Flow Object Model Calling JavaString
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 {@link
@@ -223,17 +314,17 @@
* @param environment an Environment
value
* @return a Scriptable
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
apache@apache.org.
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 @@
Cocoon provides a set of system objects for use by Flowscripts. We call this set of objects the Flow Object Model (FOM). @@ -732,65 +727,6 @@
-- You can easily call any Java code from your Flowscripts, for example: -
- - -Classes in packages under java
are accessible directly in your scripts.
Note that classes under java.lang
are not automatically imported, however:
All other java packages and classes are accessible under the property Packages
:
You can get the effect of Java imports using the importPackage()
and importClass()
functions:
- In Java: - | -- In JavaScript: - | -
- import foo.*; - | -- importPackage(Packages.foo); - | -
- import foo.Bar; - | -- importClass(Packages.foo.Bar); - | -
Example:
- --
-- If your Java classes have getters and setters you can access them as properties in JavaScript:
- -