bc7952b0 by Adam Heath

First real commit, mostly functional.

1 parent cae0ed34
.*.swp
build/
<?xml version="1.0"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<project name="ofbiz-rhino" default="jar" basedir=".">
<first id="possible.ofbiz.home.common.xml">
<resources>
<fileset dir="..">
<include name="ofbiz/common.xml"/>
</fileset>
<fileset dir="/">
<include name="srv/ofbiz-upstream/common.xml"/>
<include name="opt/ofbiz-upstream/common.xml"/>
<include name="job/ofbiz-upstream/common.xml"/>
</fileset>
</resources>
</first>
<dirname property="possible.ofbiz.home.dir" file="${toString:possible.ofbiz.home.common.xml}"/>
<property name="ofbiz.home.dir" value="${possible.ofbiz.home.dir}"/>
<import file="${ofbiz.home.dir}/common.xml"/>
<!-- ================================================================== -->
<!-- Initialization of all property settings -->
<!-- ================================================================== -->
<property name="desc" value="ofbiz-rhino"/>
<property name="name" value="ofbiz-rhino"/>
<path id="local.class.path">
<fileset dir="lib" includes="*.jar"/>
<fileset dir="${ofbiz.home.dir}/framework/base/lib" includes="*.jar"/>
<fileset dir="${ofbiz.home.dir}/framework/base/lib/commons" includes="*.jar"/>
<fileset dir="${ofbiz.home.dir}/framework/base/lib/scripting" includes="*.jar"/>
<fileset dir="${ofbiz.home.dir}/framework/base/lib/j2eespecs" includes="*.jar"/>
<fileset dir="${ofbiz.home.dir}/framework/base/build/lib" includes="*.jar"/>
</path>
</project>
No preview for this file type
This diff could not be displayed because it is too large.
<?xml version="1.0" encoding="UTF-8"?>
<ofbiz-component name="ofbiz-rhino"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://www.ofbiz.org/dtds/ofbiz-component.xsd">
<resource-loader name="main" type="component"/>
<classpath type="jar" location="lib/*"/>
<classpath type="jar" location="build/lib/*"/>
</ofbiz-component>
package com.brainfood.ofbiz.rhino;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import com.brainfood.rhino.Console;
import com.brainfood.rhino.HelperObjectProvider;
import com.brainfood.rhino.InContext;
import com.brainfood.rhino.Require;
import com.brainfood.rhino.RhinoContainer;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.NativeObject;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.ofbiz.base.location.FlexibleLocation;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.base.util.cache.UtilCache;
public class OfbizRhinoContainer extends RhinoContainer<OfbizRhinoContainer> {
public static final String module = OfbizRhinoContainer.class.getName();
private final File base;
public OfbizRhinoContainer(File base) {
super(new OfbizHelperObjectProvider());
this.base = base;
}
public static class OfbizHelperObjectProvider implements HelperObjectProvider<OfbizRhinoContainer> {
public Console newConsole(OfbizRhinoContainer container) {
return new OfbizConsole(container);
}
}
public static class OfbizConsole extends Console {
public OfbizConsole(OfbizRhinoContainer container) {
super(container);
}
@Override
public String getClassName() {
return "OfbizConsole";
}
public void log(Context cx, Object[] args, Function funObj) {
Object[] sargs = Console.getSArgs(args);
StringBuilder format = new StringBuilder();
for (int i = 0; i < args.length; i++) {
if (i != 0) {
format.append(", ");
}
format.append("%s");
}
Debug.logInfo(format.toString(), module, sargs);
}
}
public void print(Context cx, Scriptable thisObj, Object[] args, Function funObj) {
Debug.logInfo("print:%s", module, Arrays.asList(args));
}
public void processSource(Context cx, Scriptable thisObj, String filename) throws FileNotFoundException, IOException {
while (filename.length() > 0 && filename.charAt(0) == '/') {
filename = filename.substring(1);
}
cx.evaluateReader(thisObj, new FileReader(new File(base, filename)), filename, 1, null);
}
private static final UtilCache<String, Require> cache = UtilCache.getOrCreateUtilCache("OfbizRhinoContainer.Require", 0, 5, 10000, false, false);
public static Require getOrCreateRequire(String appLocation, String configPath, String... deps) throws Exception {
Require require = cache.get(appLocation);
if (require == null) {
File base = new File(FlexibleLocation.resolveLocation(appLocation).getPath());
OfbizRhinoContainer container = new OfbizRhinoContainer(base);
File rLocation = new File(FlexibleLocation.resolveLocation("component://ofbiz-rhino/lib/r.js").getPath());
require = new Require(container, rLocation, configPath);
for (String dep: deps) {
require.require(dep);
}
require = cache.putIfAbsentAndGet(appLocation, require);
}
return require;
}
}
package com.brainfood.rhino;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
public abstract class Console<C extends RhinoContainer> extends ScriptableObject {
public static final String module = Console.class.getName();
private final C container;
public Console(C container) {
this.container = container;
this.defineFunctionProperties(new String[] {"log"}, Interface.class, ScriptableObject.DONTENUM);
}
public C getContainer() {
return container;
}
public static Object[] getSArgs(Object[] args) {
Object[] sargs = new Object[args.length];
for (int i = 0; i < args.length; i++) {
sargs[i] = Context.toString(args[i]);
}
return sargs;
}
public static class Interface {
public static void log(Context cx, Scriptable thisObj, Object[] args, Function funObj) {
((Console) thisObj).log(cx, args, funObj);
}
}
public abstract void log(Context cx, Object[] args, Function funObj);
}
package com.brainfood.rhino;
public interface HelperObjectProvider<C extends RhinoContainer> {
Console newConsole(C container);
}
package com.brainfood.rhino;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.mozilla.javascript.WrapFactory;
public abstract class InContext<T> extends ScriptableObject {
public abstract T run(Context cx, RhinoContainer<?> container) throws Exception;
}
package com.brainfood.rhino;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.NativeObject;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
public class Require {
private final RhinoContainer<?> container;
private final Loader loader;
private final Function require;
public Require(RhinoContainer<?> container, File rLocation, String configPath) throws Exception {
this.container = container;
this.loader = new Loader(container, rLocation, configPath);
this.require = container.run(loader);
}
public RhinoContainer<?> getContainer() {
return container;
}
public <T> T require(final String path) throws Exception {
container.run(new InContext<Object>() {
@Override
public String getClassName() {
return "SetupRunner";
}
public Object run(Context cx, RhinoContainer container) throws FileNotFoundException, IOException {
Object[] arguments = {
cx.newArray(loader, new Object[] {path}),
};
return require.call(cx, loader, null, arguments);
}
});
return container.run(new InContext<T>() {
@Override
public String getClassName() {
return "RequireRunner";
}
public T run(Context cx, RhinoContainer container) throws FileNotFoundException, IOException {
return (T) require.call(cx, loader, null, new Object[] {path});
}
});
}
public Map<String, Object> validateWithBackbone(String moduleId, String preInitEval, Map<String, Object> data, Map<String, Object> extraOptions) throws Exception {
Function modelClass = require(moduleId);
Scriptable modelInstance = container.newObject(modelClass);
container.eval(loader, preInitEval, modelInstance);
Map<String, Object> setOptions = new HashMap<String, Object>();
if (extraOptions != null) {
setOptions.putAll(extraOptions);
}
setOptions.put("validate", false);
container.call(modelInstance, "set", container.javaToJS(data), container.javaToJS(setOptions));
NativeObject r = container.call(modelInstance, "toJSON", container.javaToJS(extraOptions));
System.err.printf("r[%s]=%s\n", moduleId, container.toMap(r));
NativeObject errors = RhinoContainer.allowUndefined(container.call(modelInstance, "validate"));
return new HashMap<String, Object>(errors);
}
public static class Loader extends InContext<Function> {
private final RhinoContainer<?> container;
private final File rLocation;
private final String configPath;
public Loader(RhinoContainer<?> container, File rLocation, String configPath) {
this.container = container;
this.rLocation = rLocation;
this.configPath = configPath;
}
@Override
public String getClassName() {
return "Loader";
}
public Function run(Context cx, RhinoContainer<?> container) throws FileNotFoundException, IOException {
container.configureTopScriptable(cx, this);
defineFunctionProperties(new String[] {"load", "print"}, Loader.class, ScriptableObject.DONTENUM);
Scriptable argsObj = cx.newArray(this, new Object[] {});
defineProperty("arguments", argsObj, ScriptableObject.DONTENUM);
if (configPath != null && configPath.length() > 0) {
container.processSource(cx, this, configPath);
}
cx.evaluateReader(this, new FileReader(rLocation.getPath()), "r.js", 1, null);
return (Function) cx.evaluateString(this, "require", null, -1, null);
}
public static void print(Context cx, Scriptable thisObj, Object[] args, Function funObj) {
Loader loader = (Loader) getTopLevelScope(thisObj);
loader.container.print(cx, thisObj, args, funObj);
}
public static void load(Context cx, Scriptable thisObj, Object[] args, Function funObj) throws FileNotFoundException, IOException {
Loader loader = (Loader) getTopLevelScope(thisObj);
for (int i = 0; i < args.length; i++) {
String path = Context.toString(args[i]);
if (path.endsWith("/jquery.js")) {
loader.container.print(cx, thisObj, new Object[] {"Skipping file " + path}, funObj);
continue;
}
loader.container.print(cx, thisObj, new Object[] {"Loading file " + path}, funObj);
loader.container.processSource(cx, thisObj, path);
}
}
}
}
package com.brainfood.rhino;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.ContextFactory;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.FunctionObject;
import org.mozilla.javascript.NativeObject;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.mozilla.javascript.WrapFactory;
import org.mozilla.javascript.Undefined;
public abstract class RhinoContainer<C extends RhinoContainer<C>> extends ScriptableObject {
private final HelperObjectProvider<C> objectProvider;
private final Console console;
private final ContextFactory contextFactory = new ContextFactory();
private final WrapFactory wrapFactory = new WrapFactory() {
public Scriptable wrapAsJavaObject(Context cx, Scriptable scope, Object javaObject, Class<?> staticType) {
System.err.printf("wrapAsJavaObject(%s, %s, %s, %s)\n", cx, scope, javaObject, staticType);
if (javaObject instanceof Map) {
NativeObject no = new NativeObject();
for (Map.Entry<String, Object> entry: ((Map<String, Object>) javaObject).entrySet()) {
no.defineProperty(entry.getKey(), RhinoContainer.this.javaToJS(entry.getValue()), NativeObject.READONLY);
}
return no;
}
return super.wrapAsJavaObject(cx, scope, javaObject, staticType);
}
};
public RhinoContainer(HelperObjectProvider<C> objectProvider) {
this.objectProvider = objectProvider;
console = objectProvider.newConsole((C) this);
}
@Override
public String getClassName() {
return "RhinoContainer";
}
public Context enterContext() {
Context cx = contextFactory.enterContext();
cx.setWrapFactory(wrapFactory);
return cx;
}
public void configureTopScriptable(Context cx, ScriptableObject s) {
cx.initStandardObjects(s, false);
s.defineProperty("console", console, ScriptableObject.DONTENUM);
s.defineFunctionProperties(new String[] {"setTimeout"}, RhinoContainer.class, ScriptableObject.DONTENUM);
}
public <T> T eval(ScriptableObject s, String evalString, Object... args) {
Context cx = enterContext();
try {
if (evalString != null && evalString.length() > 0) {
Function f = (Function) cx.evaluateString(s, "(function() {" + evalString + "});", null, -1, null);
return (T) f.call(cx, this, null, args);
} else {
return null;
}
} finally {
applyTimers(cx);
Context.exit();
}
}
public <T> T run(InContext<T> inContext) throws Exception {
Context cx = enterContext();
try {
return inContext.run(cx, this);
} finally {
applyTimers(cx);
Context.exit();
}
}
public <T> T newObject(Function f, Object... args) {
Context cx = enterContext();
try {
return (T) f.construct(cx, this, wrapArgs(args));
} finally {
applyTimers(cx);
Context.exit();
}
}
public <T> T call(Scriptable s, String methodName, Object... args) {
Context cx = enterContext();
try {
return (T) ScriptableObject.callMethod(cx, s, methodName, wrapArgs(args));
} finally {
applyTimers(cx);
Context.exit();
}
}
public Object[] wrapArgs(Object... args) {
Object[] result = new Object[args.length];
for (int i = 0; i < result.length; i++) {
result[i] = javaToJS(args[i]);
}
return result;
}
public Object javaToJS(Object value) {
Context cx = enterContext();
try {
return Context.javaToJS(value, this);
} finally {
applyTimers(cx);
Context.exit();
}
}
public Object jsToJava(Object value) {
Context cx = enterContext();
try {
return Context.jsToJava(value, null);
} finally {
applyTimers(cx);
Context.exit();
}
}
public Map<String, Object> toMap(Object value) {
value = allowUndefined(value);
if (value == null) {
return null;
}
Map<String, Object> result = new LinkedHashMap();
for (Map.Entry<Object, Object> entry: ((NativeObject) value).entrySet()) {
Object subValue = entry.getValue();
if (subValue instanceof NativeObject) {
subValue = toMap(subValue);
}
result.put((String) entry.getKey(), subValue);
}
return result;
}
private void applyTimers(Context cx) {
Map<Long, List<Function>> timers = (Map<Long, List<Function>>) cx.getThreadLocal(RhinoContainer.class.getName() +":timers");
if (timers == null) {
return;
}
long currentTime = System.currentTimeMillis();
while (!timers.isEmpty()) {
Iterator<Map.Entry<Long, List<Function>>> it = timers.entrySet().iterator();
Map.Entry<Long, List<Function>> entry = it.next();
it.remove();
Long delay = entry.getKey();
List<Function> functions = entry.getValue();
if (delay != 0) {
System.err.printf("Unhandled delay: %s -> %s\n", delay, functions);
}
while (!functions.isEmpty()) {
Function function = functions.remove(0);
function.call(cx, this, null, new Object[0]);
}
}
}
public abstract void print(Context cx, Scriptable thisObj, Object[] args, Function funObj);
public abstract void processSource(Context cx, Scriptable thisObj, String filename) throws FileNotFoundException, IOException;
public static void setTimeout(Context cx, Scriptable thisObj, Object[] args, Function funObj) {
Function toCall = (Function) args[0];
Long delay = args.length > 1 ? ((Number) args[1]).longValue() : 0;
Map<Long, List<Function>> timers = (Map<Long, List<Function>>) cx.getThreadLocal(RhinoContainer.class.getName() +":timers");
if (timers == null) {
timers = new TreeMap<Long, List<Function>>();
cx.putThreadLocal(RhinoContainer.class.getName() +":timers", timers);
}
List<Function> functions = timers.get(delay);
if (functions == null) {
functions = new ArrayList<Function>();
timers.put(delay, functions);
}
functions.add(toCall);
}
public static <T> T allowUndefined(Object value) {
if (value instanceof Undefined) {
return null;
} else {
return (T) value;
}
}
}