package com.dbxml.db.common.scripting;
/*
* dbXML - Native XML Database
* Copyright (c) 1999-2006 The dbXML Group, L.L.C.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* $Id: JavaScriptExtension.java,v 1.3 2006/02/02 18:53:52 bradford Exp $
*/
import java.util.Map;
import com.dbxml.labrador.types.Variant;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
/**
* JavaScriptExtension is an experimental Extension for executing
* JavaScript with the Mozilla Rhino interpreter.
*/
public final class JavaScriptExtension extends ScriptExtension {
private static final String[] EmptyStrings = new String[0];
public Variant execute(Map args) {
Context ctx = Context.enter();
ctx.setLanguageVersion(Context.VERSION_1_5);
Scriptable scope = ctx.initStandardObjects(null);
// Standard Variables
scope.put("this", scope, Context.toObject(this, scope));
scope.put("database", scope, Context.toObject(collection.getDatabase(), scope));
scope.put("collection", scope, Context.toObject(collection, scope));
// Arguments
String[] names = (String[])args.keySet().toArray(EmptyStrings);
for ( int i = 0; i < names.length; i++ ) {
Object obj = args.get(names[i]);
scope.put(names[i], scope, Context.toObject(obj, scope));
}
// Now run the actual script and populate the result
try {
ctx.evaluateString(scope, script, "<cmd>", 1, null);
}
catch ( Exception e ) {
}
Object res = scope.get("result", scope);
if ( res != null )
res = Context.toString(res);
Context.exit();
if ( res != null )
return new Variant(res);
else
return null;
}
}