Java Code Examples for org.mozilla.javascript.Context#setLanguageVersion()

The following examples show how to use org.mozilla.javascript.Context#setLanguageVersion() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BaseScript.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
protected void executeScript( final Map<String, Object> params ) {
  final Context cx = Context.getCurrentContext();
  // env.js has methods that pass the 64k Java limit, so we can't compile
  // to bytecode. Interpreter mode to the rescue!
  cx.setOptimizationLevel( -1 );
  cx.setLanguageVersion( Context.VERSION_1_7 );

  final Object wrappedParams;
  if ( params != null ) {
    wrappedParams = Context.javaToJS( params, scope );
  } else {
    wrappedParams = Context.javaToJS( new HashMap<String, Object>(), scope );
  }

  try {
    ScriptableObject.defineProperty( scope, "params", wrappedParams, 0 );
    cx.evaluateReader( scope, new FileReader( source ), this.source, 1, null );
  } catch ( IOException ex ) {
    logger.error( "Failed to read " + source + ": " + ex.toString() );
  }
}
 
Example 2
Source File: SdpProcessor.java    From openwebrtc-android-sdk with BSD 2-Clause "Simplified" License 6 votes vote down vote up
static String jsonToSdp(JSONObject json) throws InvalidDescriptionException {
    synchronized (SdpProcessor.class) {
        if (sInstance == null) {
            sInstance = new SdpProcessor();
        }
    }
    Context context = Context.enter();
    context.setOptimizationLevel(-1);
    context.setLanguageVersion(Context.VERSION_1_8);
    try {
        ScriptableObject scope = sInstance.getScope();
        Object result = sInstance.getJsonToSdpFunction().call(context, scope, scope, new Object[]{json.toString()});
        return "" + result;
    } catch (EvaluatorException e) {
        throw new InvalidDescriptionException("failed to parse sdp: " + e.getMessage(), e);
    } finally {
        Context.exit();
    }
}
 
Example 3
Source File: JsRuntimeRepl.java    From stetho with MIT License 6 votes vote down vote up
/**
 * Setups a proper javascript context so that it can run javascript code properly under android.
 * For android we need to disable bytecode generation since the android vms don't understand JVM bytecode.
 * @return a proper javascript context
 */
static @NonNull Context enterJsContext() {
  final Context jsContext = Context.enter();

  // If we cause the context to throw a runtime exception from this point
  // we need to make sure that exit the context.
  try {
    jsContext.setLanguageVersion(Context.VERSION_1_8);

    // We can't let Rhino to optimize the JS and to use a JIT because it would generate JVM bytecode
    // and android runs on DEX bytecode. Instead we need to go in interpreted mode.
    jsContext.setOptimizationLevel(-1);
  } catch (RuntimeException e) {
    // Something bad happened to the javascript context but it might still be usable.
    // The first thing to do is to exit the context and then propagate the error.
    Context.exit();
    throw e;
  }

  return jsContext;
}
 
Example 4
Source File: JsonExtensionNotificationDataConverter.java    From JVoiceXML with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Object convertApplicationLastResult(
        final List<LastResult> lastresults) throws ConversionException {
    if (lastresults == null || lastresults.isEmpty()) {
        return null;
    }
    final Context context = Context.enter();
    context.setLanguageVersion(Context.VERSION_DEFAULT);
    final ScriptableObject scope = context.initStandardObjects();
    final LastResult lastresult = lastresults.get(0);
    final Scriptable vxml = context.newObject(scope);
    ScriptableObject.putProperty(vxml, "utterance",
            lastresult.getUtterance());
    ScriptableObject.putProperty(vxml, "confidence",
            lastresult.getConfidence());
    ScriptableObject.putProperty(vxml, "mode", lastresult.getInputmode());
    ScriptableObject.putProperty(vxml, "interpretation",
            lastresult.getInterpretation());
    return toJSON(vxml);
}
 
Example 5
Source File: JsonExtensionNotificationDataConverter.java    From JVoiceXML with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Object convertRecognitionEvent(final DataModel model,
        final RecognitionEvent event) throws ConversionException {
    final RecognitionResult result = event.getRecognitionResult();
    final Context context = Context.enter();
    context.setLanguageVersion(Context.VERSION_DEFAULT);
    final ScriptableObject scope = context.initStandardObjects();
    final Scriptable vxml = context.newObject(scope);
    ScriptableObject.putProperty(vxml, "utterance", result.getUtterance());
    ScriptableObject
            .putProperty(vxml, "confidence", result.getConfidence());
    ScriptableObject.putProperty(vxml, "mode", result.getMode());
    try {
        ScriptableObject.putProperty(vxml, "interpretation",
                result.getSemanticInterpretation(model));
    } catch (SemanticError e) {
        throw new ConversionException(e.getMessage(), e);
    }
    return toJSON(vxml);
}
 
Example 6
Source File: JsonExtensionNotificationDataConverterTest.java    From JVoiceXML with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void testConvertApplicationLastResultSimpleSemanticInterpretation()
        throws Exception {
    final JsonExtensionNotificationDataConverter converter = new JsonExtensionNotificationDataConverter();
    final List<LastResult> list = new java.util.ArrayList<LastResult>();
    final Context context = Context.enter();
    context.setLanguageVersion(Context.VERSION_1_6);
    final Scriptable scope = context.initStandardObjects();
    context.evaluateString(scope, "var out = 'yes';", "expr", 1, null);
    final Object out = scope.get("out", scope);
    final LastResult result = new LastResult("yeah", .75f, "voice", out);
    list.add(result);
    final String json = (String) converter
            .convertApplicationLastResult(list);
    Assert.assertEquals("vxml.input = {\"utterance\":\"yeah\","
            + "\"confidence\":0.75,\"interpretation\":\"yes\","
            + "\"mode\":\"voice\"}", json);
}
 
Example 7
Source File: XmlExtensionNotificationDataConverterTest.java    From JVoiceXML with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void testConvertApplicationLastResultComplexSemanticInterpretation()
        throws Exception {
    final XmlExtensionNotificationDataConverter converter = new XmlExtensionNotificationDataConverter();
    final List<LastResult> list = new java.util.ArrayList<LastResult>();
    final Context context = Context.enter();
    context.setLanguageVersion(Context.VERSION_1_6);
    final Scriptable scope = context.initStandardObjects();
    context.evaluateString(scope, "var out = new Object();", "expr", 1,
            null);
    context.evaluateString(scope, "var out = new Object();", "expr", 1,
            null);
    context.evaluateString(scope, "out.order = new Object();", "expr", 1,
            null);
    context.evaluateString(scope, "out.order.topping = 'Salami';", "expr",
            1, null);
    context.evaluateString(scope, "out.order.size = 'medium';", "expr", 1,
            null);
    context.evaluateString(scope, "out.date = 'now';", "expr", 1, null);
    final Object out = scope.get("out", scope);
    final LastResult result = new LastResult("yes", .75f, "voice", out);
    list.add(result);
    final Element element = (Element) converter
            .convertApplicationLastResult(list);
    System.out.println(toString(element));
}
 
Example 8
Source File: SunSpiderBenchmark.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
private void runTest(int optLevel)
    throws IOException
{

    Context cx = RhinoAndroidHelper.prepareContext();
    cx.setLanguageVersion(Context.VERSION_1_8);
    cx.setOptimizationLevel(optLevel);
    Global root = new Global(cx);
    TestUtils.addAssetLoading(root);
    root.put("RUN_NAME", root, "SunSpider-" + optLevel);
    Object result = cx.evaluateString(root, TestUtils.readAsset(TEST_SRC), TEST_SRC, 1, null);
    results.put(optLevel, result.toString());
}
 
Example 9
Source File: SdpProcessor.java    From openwebrtc-android-sdk with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private SdpProcessor() {
    Context context = Context.enter();
    context.setOptimizationLevel(-1);
    context.setLanguageVersion(Context.VERSION_1_8);
    mScope = context.initStandardObjects();

    try {
        context.evaluateString(mScope, sSdpJsSource, "sdp.js", 1, null);
        mSdpToJsonFunction = context.compileFunction(mScope, "function sdpToJson(sdp) { return JSON.stringify(SDP.parse(sdp)); }", "sdpToJson", 1, null);
        mJsonToSdpFunction = context.compileFunction(mScope, "function jsonToSdp(sdp) { return SDP.generate(JSON.parse(sdp)); }", "jsonToSdp", 1, null);
    } finally {
        Context.exit();
    }
}
 
Example 10
Source File: EcmaScriptDataModel.java    From JVoiceXML with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Safe retrieval of the current context.
 * @return context
 * @since 0.7.9
 */
private Context getContext() {
    Context context = Context.getCurrentContext();
    if (context == null) {
        context = Context.enter();
        context.setLanguageVersion(Context.VERSION_DEFAULT);
    }
    return context;
}
 
Example 11
Source File: MatchConsumption.java    From JVoiceXML with GNU Lesser General Public License v2.1 5 votes vote down vote up
public Object executeSisr() {
    final Context context = Context.enter();
    context.setLanguageVersion(Context.VERSION_DEFAULT);
    final Scriptable globalScope = context.initStandardObjects();

    if (globalExecutation != null) {
        globalExecutation.execute(context, globalScope);
    }
    final ScriptableObject scriptable = (ScriptableObject) globalScope;
    scriptable.sealObject();

    // Set up working scope - note out initialized at this level, but
    // shouldn't be used
    Scriptable workingScope = context.newObject(globalScope);
    context.evaluateString(
            workingScope,
            "var out=new Object();\nvar rules=new Object();\n"
                    + "var meta={current: function() {return {text:'', score:1.0};}};\n",
            "SISR init from MatchConsumer", 0, null);

    if (executationCollection.size() != 1) {
        LOGGER.error("Execution collection was not 1: "
                + executationCollection.size());
    }

    // At the top level, there should only be one item, a context for the
    // rule being fired.
    for (ExecutableSemanticInterpretation si : executationCollection) {
        si.execute(context, workingScope);
    }

    // Since the last item was a rule, we can return rules.latest
    return context.evaluateString(workingScope, "rules.latest();",
            "SISR from MatchConsumer", 0, null);
}
 
Example 12
Source File: XmlExtensionNotificationDataConverterTest.java    From JVoiceXML with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testConvertApplicationLastResultSimpleSemanticInterpretation()
        throws Exception {
    final XmlExtensionNotificationDataConverter converter = new XmlExtensionNotificationDataConverter();
    final List<LastResult> list = new java.util.ArrayList<LastResult>();
    final Context context = Context.enter();
    context.setLanguageVersion(Context.VERSION_1_6);
    final Scriptable scope = context.initStandardObjects();
    context.evaluateString(scope, "var out = 'yes';", "expr", 1, null);
    final Object out = scope.get("out", scope);
    final LastResult result = new LastResult("yeah", .75f, "voice", out);
    list.add(result);
    Element element = (Element) converter.convertApplicationLastResult(list);
    System.out.println(toString(element));
}
 
Example 13
Source File: JsonExtensionNotificationDataConverterTest.java    From JVoiceXML with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testConvertApplicationLastResultComplexSemanticInterpretation()
        throws Exception {
    final JsonExtensionNotificationDataConverter converter = new JsonExtensionNotificationDataConverter();
    final List<LastResult> list = new java.util.ArrayList<LastResult>();
    final Context context = Context.enter();
    context.setLanguageVersion(Context.VERSION_1_6);
    final Scriptable scope = context.initStandardObjects();
    context.evaluateString(scope, "var out = new Object();", "expr", 1,
            null);
    context.evaluateString(scope, "var out = new Object();", "expr", 1,
            null);
    context.evaluateString(scope, "out.order = new Object();", "expr", 1,
            null);
    context.evaluateString(scope, "out.order.topping = 'Salami';", "expr",
            1, null);
    context.evaluateString(scope, "out.order.size = 'medium';", "expr", 1,
            null);
    context.evaluateString(scope, "out.date = 'now';", "expr", 1, null);
    final Object out = scope.get("out", scope);
    final LastResult result = new LastResult("yes", .75f, "voice", out);
    list.add(result);
    final String json = (String) converter
            .convertApplicationLastResult(list);
    Assert.assertEquals("vxml.input = {\"utterance\":\"yes\","
            + "\"confidence\":0.75,\"interpretation\":{\"order\":"
            + "{\"topping\":\"Salami\",\"size\":\"medium\"},"
            + "\"date\":\"now\"},\"mode\":\"voice\"}", json);
}
 
Example 14
Source File: JsonExtensionNotificationDataConverter.java    From JVoiceXML with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Packs the given SSML document into a JSON structure.
 * 
 * @param speakable
 *            the speakable with the SSML document
 * @return JSON formatted string
 */
private String toJson(final SpeakableText speakable) {
    final Context context = Context.enter();
    context.setLanguageVersion(Context.VERSION_DEFAULT);
    final ScriptableObject scope = context.initStandardObjects();
    final String ssml = speakable.getSpeakableText();
    final Scriptable vxml = context.newObject(scope);
    ScriptableObject.putProperty(vxml, "ssml", ssml);
    return toJSON(vxml);
}
 
Example 15
Source File: Bug708801Test.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
@Override
protected Context makeContext() {
    Context cx = super.makeContext();
    cx.setLanguageVersion(Context.VERSION_1_8);
    cx.setOptimizationLevel(COMPILER_MODE);
    return cx;
}
 
Example 16
Source File: V8Benchmark.java    From rhino-android with Apache License 2.0 5 votes vote down vote up
private void runTest(int optLevel)
    throws IOException
{


    Context cx = RhinoAndroidHelper.prepareContext();
    cx.setLanguageVersion(Context.VERSION_1_8);
    cx.setOptimizationLevel(optLevel);
    Global root = new Global(cx);
    TestUtils.addAssetLoading(root);
    root.put("RUN_NAME", root, "V8-Benchmark-" + optLevel);
    Object result = cx.evaluateString(root, TestUtils.readAsset(TEST_SRC), TEST_SRC, 1, null);
    results.put(optLevel, result.toString());
}
 
Example 17
Source File: LessCompiler.java    From projectforge-webapp with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Initializes this <code>LessCompiler</code>.
 * <p>
 * It is not needed to call this method manually, as it is called implicitly by the compile methods if needed.
 * </p>
 */
public synchronized void init() {
  final long start = System.currentTimeMillis();

  try {
    final Context cx = Context.enter();
    cx.setOptimizationLevel(-1);
    cx.setLanguageVersion(Context.VERSION_1_7);

    final Global global = new Global();
    global.init(cx);

    scope = cx.initStandardObjects(global);

    final List<URL> jsUrls = new ArrayList<URL>(2 + customJs.size());
    jsUrls.add(envJs);
    jsUrls.add(lessJs);
    jsUrls.addAll(customJs);

    for(final URL url : jsUrls){
      final InputStreamReader inputStreamReader = new InputStreamReader(url.openConnection().getInputStream());
      try{
        cx.evaluateReader(scope, inputStreamReader, url.toString(), 1, null);
      }finally{
        inputStreamReader.close();
      }
    }
    doIt = cx.compileFunction(scope, COMPILE_STRING, "doIt.js", 1, null);
  }
  catch (final Exception e) {
    final String message = "Failed to initialize LESS compiler.";
    log.error(message, e);
    throw new IllegalStateException(message, e);
  }finally{
    Context.exit();
  }

  if (log.isDebugEnabled()) {
    log.debug("Finished initialization of LESS compiler in " + (System.currentTimeMillis() - start) + " ms.");
  }
}