@Test
  public void testNativeScript() throws InterruptedException {
    Settings settings =
        Settings.settingsBuilder()
            .put("script.native.my.type", MyNativeScriptFactory.class.getName())
            .put("name", "testNativeScript")
            .put("path.home", createTempDir())
            .build();
    Injector injector =
        new ModulesBuilder()
            .add(
                new EnvironmentModule(new Environment(settings)),
                new ThreadPoolModule(new ThreadPool(settings)),
                new SettingsModule(settings),
                new ScriptModule(settings))
            .createInjector();

    ScriptService scriptService = injector.getInstance(ScriptService.class);

    ExecutableScript executable =
        scriptService.executable(
            new Script("my", ScriptType.INLINE, NativeScriptEngineService.NAME, null),
            ScriptContext.Standard.SEARCH);
    assertThat(executable.run().toString(), equalTo("test"));
    terminate(injector.getInstance(ThreadPool.class));
  }
 public void testAllOpsDisabled() throws Exception {
   ContextAndHeaderHolder contextAndHeaders = new ContextAndHeaderHolder();
   Settings settings =
       Settings.builder()
           .put("script.engine." + MockScriptEngine.NAME + ".file.aggs", false)
           .put("script.engine." + MockScriptEngine.NAME + ".file.search", false)
           .put("script.engine." + MockScriptEngine.NAME + ".file.mapping", false)
           .put("script.engine." + MockScriptEngine.NAME + ".file.update", false)
           .put("script.engine." + MockScriptEngine.NAME + ".file.ingest", false)
           .build();
   ScriptService scriptService = makeScriptService(settings);
   Script script =
       new Script("script1", ScriptService.ScriptType.FILE, MockScriptEngine.NAME, null);
   for (ScriptContext context : ScriptContext.Standard.values()) {
     try {
       scriptService.compile(script, context, contextAndHeaders, Collections.emptyMap());
       fail(context.getKey() + " script should have been rejected");
     } catch (Exception e) {
       assertTrue(
           e.getMessage(),
           e.getMessage()
               .contains(
                   "scripts of type [file], operation ["
                       + context.getKey()
                       + "] and lang ["
                       + MockScriptEngine.NAME
                       + "] are disabled"));
     }
   }
 }
 @Test
 public void testRot13() throws Exception {
   final Context context = new Context(ScriptService.class);
   final ScriptService scriptService = context.getService(ScriptService.class);
   final ScriptLanguage hello = scriptService.getLanguageByName("Hello");
   assertNotNull(hello);
   final ScriptLanguage rot13 = scriptService.getLanguageByName("Rot13");
   assertEquals(hello, rot13);
   assertEquals("Svool", rot13.getScriptEngine().eval("Hello"));
 }
 public void testFileScriptFound() throws Exception {
   ContextAndHeaderHolder contextAndHeaders = new ContextAndHeaderHolder();
   Settings settings =
       Settings.builder()
           .put("script.engine." + MockScriptEngine.NAME + ".file.aggs", false)
           .build();
   ScriptService scriptService = makeScriptService(settings);
   Script script =
       new Script("script1", ScriptService.ScriptType.FILE, MockScriptEngine.NAME, null);
   assertNotNull(
       scriptService.compile(
           script, ScriptContext.Standard.SEARCH, contextAndHeaders, Collections.emptyMap()));
 }
 @Test
 public void testScriptModuleValue() throws Exception {
   final Context context = new Context(ScriptService.class);
   final ScriptService scriptService = context.getService(ScriptService.class);
   final ScriptModule module =
       scriptService
           .run("test.rot13", ScriptModule.class.getName(), false, (Map<String, Object>) null)
           .get();
   final ScriptModule scriptModule = Rot13Engine.latestModule;
   assertEquals(module, scriptModule);
   assertNotNull(scriptModule);
   final ScriptInfo info = scriptModule.getInfo();
   assertEquals(context, info.context());
 }
Exemple #6
0
 @Override
 public void run() {
   final String fileExtension = FileUtils.getExtension(file);
   final ScriptEngineFactory factory = scriptService.getByFileExtension(fileExtension);
   try {
     final Object result = factory.getScriptEngine().eval(new FileReader(file));
     if (result != null) {
       System.out.println(result.toString());
     }
   } catch (final ScriptException e) {
     scriptService.getLogService().error(e.getCause());
   } catch (final Throwable e) {
     scriptService.getLogService().error(e);
   }
 }
Exemple #7
0
  @Test
  public void testBasic() throws Exception {
    final ImageJ context = new ImageJ();
    new ServiceHelper(context).createExactService(DefaultScriptService.class);
    final ScriptService scriptService = context.getService(ScriptService.class);
    new ServiceHelper(context).createExactService(DummyService.class);

    String script =
        "dummy = IJ.getService(imagej.script.DummyService.class);\n"
            + "dummy.context = IJ;\n"
            + "dummy.value = 1234;\n";
    scriptService.eval("hello.bsh", new StringReader(script));

    final DummyService dummy = context.getService(DummyService.class);
    assertEquals(context, dummy.context);
    assertEquals(1234, dummy.value);
  }
 /** Initializes {@link #languages}. */
 private synchronized void initLanguages() {
   if (languages != null) return;
   final List<ScriptLanguage> langs = new ArrayList<>();
   for (final ScriptLanguage lang : scriptService.getLanguages()) {
     if (!lang.isCompiledLanguage()) langs.add(lang);
   }
   languages = langs;
 }
  @Test
  public void testFineGrainedSettingsDontAffectNativeScripts() throws IOException {
    Settings.Builder builder = Settings.settingsBuilder();
    if (randomBoolean()) {
      ScriptType scriptType = randomFrom(ScriptType.values());
      builder.put(ScriptModes.SCRIPT_SETTINGS_PREFIX + scriptType, randomFrom(ScriptMode.values()));
    } else {
      String scriptContext = randomFrom(ScriptContext.Standard.values()).getKey();
      builder.put(
          ScriptModes.SCRIPT_SETTINGS_PREFIX + scriptContext, randomFrom(ScriptMode.values()));
    }
    Settings settings = builder.put("path.home", createTempDir()).build();
    Environment environment = new Environment(settings);
    ResourceWatcherService resourceWatcherService = new ResourceWatcherService(settings, null);
    Map<String, NativeScriptFactory> nativeScriptFactoryMap = new HashMap<>();
    nativeScriptFactoryMap.put("my", new MyNativeScriptFactory());
    Set<ScriptEngineService> scriptEngineServices =
        ImmutableSet.<ScriptEngineService>of(
            new NativeScriptEngineService(settings, nativeScriptFactoryMap));
    ScriptContextRegistry scriptContextRegistry =
        new ScriptContextRegistry(Lists.<ScriptContext.Plugin>newArrayList());
    ScriptService scriptService =
        new ScriptService(
            settings,
            environment,
            scriptEngineServices,
            resourceWatcherService,
            scriptContextRegistry);

    for (ScriptContext scriptContext : scriptContextRegistry.scriptContexts()) {
      assertThat(
          scriptService.compile(
              new Script("my", ScriptType.INLINE, NativeScriptEngineService.NAME, null),
              scriptContext),
          notNullValue());
    }
  }
    @Override
    public SignificanceHeuristic parse(XContentParser parser)
        throws IOException, QueryParsingException {
      NAMES_FIELD.match(parser.currentName(), ParseField.EMPTY_FLAGS);
      String script = null;
      String scriptLang;
      XContentParser.Token token;
      Map<String, Object> params = new HashMap<>();
      String currentFieldName = null;
      ScriptService.ScriptType scriptType = ScriptService.ScriptType.INLINE;
      ScriptParameterParser scriptParameterParser = new ScriptParameterParser();
      while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token.equals(XContentParser.Token.FIELD_NAME)) {
          currentFieldName = parser.currentName();
        } else if (token == XContentParser.Token.START_OBJECT) {
          if ("params".equals(currentFieldName)) {
            params = parser.map();
          } else {
            throw new ElasticsearchParseException(
                "unknown object " + currentFieldName + " in script_heuristic");
          }
        } else if (!scriptParameterParser.token(currentFieldName, token, parser)) {
          throw new ElasticsearchParseException(
              "unknown field " + currentFieldName + " in script_heuristic");
        }
      }

      ScriptParameterParser.ScriptParameterValue scriptValue =
          scriptParameterParser.getDefaultScriptParameterValue();
      if (scriptValue != null) {
        script = scriptValue.script();
        scriptType = scriptValue.scriptType();
      }
      scriptLang = scriptParameterParser.lang();

      if (script == null) {
        throw new ElasticsearchParseException("No script found in script_heuristic");
      }
      ExecutableScript searchScript;
      try {
        searchScript =
            scriptService.executable(
                scriptLang, script, scriptType, ScriptContext.Standard.AGGS, params);
      } catch (Exception e) {
        throw new ElasticsearchParseException("The script [" + script + "] could not be loaded", e);
      }
      return new ScriptHeuristic(searchScript, scriptLang, script, scriptType, params);
    }
  /**
   * Creates a new {@link ScriptInterpreter} to interpret statements, preserving existing variables
   * from the previous interpreter.
   *
   * @param langName The script language of the new interpreter.
   * @throws IllegalArgumentException if the requested language is not available.
   */
  public void lang(final String langName) {
    // create the new interpreter
    final ScriptLanguage language = scriptService.getLanguageByName(langName);
    if (language == null) {
      out.println("No such language: " + langName);
      return;
    }
    final ScriptInterpreter newInterpreter = new DefaultScriptInterpreter(language);

    // preserve state of the previous interpreter
    try {
      copyBindings(interpreter, newInterpreter);
    } catch (final Throwable t) {
      t.printStackTrace(out);
    }
    out.println("language -> " + newInterpreter.getLanguage().getLanguageName());
    interpreter = newInterpreter;
  }
  // Show the main (seattle already installed) layout
  private void showMainLayout() {
    setContentView(R.layout.main);
    currentContentView = R.layout.main;
    // Set up status toggle button
    final ToggleButton toggleStatus = (ToggleButton) findViewById(R.id.toggleStatus);
    toggleStatus.setChecked(ScriptService.isServiceRunning());

    if (ScriptActivity.autostartedAfterInstallation) {
      ScriptActivity.autostartedAfterInstallation = false;
      toggleStatus.setChecked(true);
    }

    toggleStatus.setOnCheckedChangeListener(
        new OnCheckedChangeListener() {
          @Override
          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
              // Start service
              ScriptService.serviceInitiatedByUser = true;
              startService(new Intent(getBaseContext(), ScriptService.class));
            } else {
              // Kill service
              killService();
            }
          }
        });
    // Set up autostart checkbox
    final CheckBox checkBoxAutostart = (CheckBox) findViewById(R.id.checkBoxAutostart);
    checkBoxAutostart.setOnCheckedChangeListener(
        new OnCheckedChangeListener() {
          @Override
          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // Store changes
            saveSharedBooleanPreference(AUTOSTART_ON_BOOT, isChecked);
          }
        });
    checkBoxAutostart.setChecked(settings.getBoolean(AUTOSTART_ON_BOOT, true));
  }