@Test
 public void testScheduledAnnotation() throws Exception {
   ScriptManager sm = new ScriptManager();
   sm.setGlobalClassListener(new ScheduledTaskClassListenerTestAdapter(cronService));
   sm.loadDirectory(new File(FILE_TEST_DATA_DIR));
   assertEquals(cronService.getRunnables().size(), 1);
   sm.shutdown();
   assertEquals(cronService.getRunnables().size(), 0);
 }
  @Test
  public void testOnClassLoadAndUnload() throws Exception {
    ScriptManager sm = new ScriptManager();
    sm.setGlobalClassListener(new OnClassLoadUnloadListener());
    sm.loadDirectory(new File(FILE_TEST_DATA_DIR));
    assertEquals(System.getProperties().containsKey(SYSTEM_PROPERTY_KEY_CLASS_LOADED), true);

    sm.shutdown();
    assertEquals(System.getProperties().containsKey(SYSTEM_PROPERTY_KEY_CLASS_UNLOADED), true);
  }
示例#3
0
  private void initializeGeneralGlobals() {
    engine.put("RuleSet", RuleSet.class);
    engine.put("Rule", Rule.class);
    engine.put("ChangedEventTrigger", ChangedEventTrigger.class);
    engine.put("UpdatedEventTrigger", UpdatedEventTrigger.class);
    engine.put("CommandEventTrigger", CommandEventTrigger.class);
    engine.put("Event", Event.class);
    engine.put("EventTrigger", EventTrigger.class);
    engine.put("ShutdownTrigger", ShutdownTrigger.class);
    engine.put("StartupTrigger", StartupTrigger.class);
    engine.put("TimerTrigger", TimerTrigger.class);
    engine.put("TriggerType", TriggerType.class);
    engine.put("BusEvent", BusEvent.class);
    engine.put("be", BusEvent.class);
    engine.put("PersistenceExtensions", PersistenceExtensions.class);
    engine.put("pe", PersistenceExtensions.class);
    engine.put("HistoricItem", HistoricItem.class);
    engine.put("oh", Openhab.class);
    engine.put("State", State.class);
    engine.put("Command", Command.class);
    engine.put("ItemRegistry", scriptManager.getItemRegistry());
    engine.put("ir", scriptManager.getItemRegistry());
    engine.put("DateTime", DateTime.class);
    engine.put("StringUtils", StringUtils.class);
    engine.put("URLEncoder", URLEncoder.class);
    engine.put("FileUtils", FileUtils.class);
    engine.put("FilenameUtils", FilenameUtils.class);
    engine.put("File", File.class);

    // default types, TODO: auto import would be nice
    engine.put("CallType", CallType.class);
    engine.put("DateTimeType", DateTimeType.class);
    engine.put("DecimalType", DecimalType.class);
    engine.put("HSBType", HSBType.class);
    engine.put("IncreaseDecreaseType", IncreaseDecreaseType.class);
    engine.put("OnOffType", OnOffType.class);
    engine.put("OpenClosedType", OpenClosedType.class);
    engine.put("PercentType", PercentType.class);
    engine.put("PointType", PointType.class);
    engine.put("StopMoveType", StopMoveType.class);
    engine.put("UpDownType", UpDownType.class);
    engine.put("StringType", StringType.class);
    engine.put("UnDefType", UnDefType.class);
  }
示例#4
0
 static void addPatches(final ScriptManager sm, final boolean ecj) {
   final String HOOK_NAME = PatchFunction.class.getName();
   sm.addScript(
       exitEarly()
           .target(new MethodTarget(CLASSSCOPE, "buildFieldsAndMethods", "void"))
           .request(StackRequest.THIS)
           .decisionMethod(
               new Hook(HOOK_NAME, "onClassScope_buildFieldsAndMethods", "boolean", CLASSSCOPE))
           .build());
 }
示例#5
0
 static void addPatches(final ScriptManager sm, final boolean ecj) {
   final String HOOK_NAME = PatchYield.class.getName();
   sm.addScript(
       ScriptBuilder.exitEarly()
           .target(new MethodTarget(ABSTRACTMETHODDECLARATION, "resolveStatements", "void"))
           .request(StackRequest.THIS)
           .decisionMethod(
               new Hook(
                   HOOK_NAME,
                   "onAbstractMethodDeclaration_resolveStatements",
                   "boolean",
                   ABSTRACTMETHODDECLARATION))
           .build());
 }
  /**
   * Constructor.
   *
   * @param eventSource source of the mouse and key events which will be translated into scripting
   *     language commands. Such a typical source is e.g. the VNC viewer panel.
   */
  public RecordingModule(
      MainFrame frame, Component eventSource, ScriptManager scriptManager, UserConfiguration cfg) {
    this.cfg = cfg;
    this.scriptManager = scriptManager;
    readOnly = cfg.getBoolean("rfb.readOnly").booleanValue();

    fb = (DesktopViewer) eventSource;
    fb.removeMouseListener(fb);
    eventSource.addMouseListener(this);
    fb.addMouseListener(fb);
    eventSource.addMouseMotionListener(this);
    eventSource.addMouseWheelListener(this);
    eventSource.addKeyListener(this);

    client = scriptManager.getClient();
    if (client != null) {
      client.addServerListener(this);
    }

    //        scriptManager.addMouseInputListener(this);
    //        scriptManager.addKeyListener(this);

    // Number of archived events
    //        events.setSize(EVENT_VECTOR_SIZE);

    // Populate the reversed keycode->keyname Map
    Map t = Utils.getKeyCodeTable();
    Iterator e = t.keySet().iterator();
    Object o;
    while (e.hasNext()) {
      o = e.next();
      keyCodes.put(t.get(o), o);
    }
    cfg.addConfigurationListener(this);
    scriptManager.addScriptListener(this);
    configurationChanged(null);
  }
  public void setEnabled(boolean enabled) {
    if (!enabled && this.enabled && lastElement != null) {
      // Insert a timeout to the last generated command
      Editor ed = editorPnl.getEditor();
      if (lastElement.getDocument().equals(ed.getDocument())) {
        Element e = ed.getCurrentElement();
        int offset = ed.getCaretPosition() - e.getStartOffset();
        ed.setCaretPosition(lastElement.getStartOffset());
        String text = DocumentUtils.getElementText(lastElement);
        int pos = text.indexOf(" ");
        String cmd = pos >= 0 ? text.substring(0, pos) : text;
        String time = convertTime(System.currentTimeMillis() - lastInsertTime);
        CommandHandler h =
            (CommandHandler) scriptManager.getCommandHandlers().get(cmd.toUpperCase());

        if (h != null
            && h.getContextAttributes() != null
            && h.getContextAttributes().containsKey("wait")) {
          text += " wait=" + time;
        } else {
          text += "\nWait " + time;
        }
        insertLine(text, true, false, false);
      }
    }
    this.enabled = enabled;
    fb.setRecordingMode(enabled);
    if (enabled) {
      firstRecord = true;
      lastElement = null;
      lastInsertTime = -1;
      lastMouseMoveEvent = null;
      events.clear();
      synchronized (rfbEvents) {
        rfbEvents.clear();
      }
    }
  }
示例#8
0
  /**
   * initializes Globals for Oracle Nashorn in conjunction with Java 8
   *
   * <p>To prevent Class loading Problems use this directive in start.sh/-.bat:
   * -Dorg.osgi.framework.bundle.parent=ext further information:
   * http://apache-felix.18485.x6.nabble.com/org-osgi-framework-bootdelegation-and-org-osgi-framework-system-packages-extra-td4946354.html
   * https://bugs.eclipse.org/bugs/show_bug.cgi?id=466683
   * http://spring.io/blog/2009/01/19/exposing-the-boot-classpath-in-osgi/
   * http://osdir.com/ml/users-felix-apache/2015-02/msg00067.html
   * http://stackoverflow.com/questions/30225398/java-8-scriptengine-across-classloaders
   *
   * <p>later we will get Autoimports for Classes in Nashorn: further information:
   * http://nashorn.36665.n7.nabble.com/8u60-8085937-add-autoimports-sample-script-to-easily-explore-Java-classes-in-interactive-mode-td4705.html
   *
   * <p>Later in a pure Java 8/9 environment:
   * http://mail.openjdk.java.net/pipermail/nashorn-dev/2015-February/004177.html Using Nashorn with
   * interfaces loaded from custom classloaders, "script function" as a Java lambda:
   *
   * <p>engine.put("JavaClass", (Function<String, Class>) s -> { try { // replace this whatever
   * Class finding logic here // say, using your own class loader(s) based search Class<?> c =
   * Class.forName(s); logger.error("Class " + c.getName()); logger.error("s " + s); return
   * Class.forName(s); } catch (ClassNotFoundException cnfe) { throw new RuntimeException(cnfe); }
   * }); engine.eval("var System = JavaClass('java.lang.System').static");
   * engine.eval("System.out.println('hello world')");
   */
  private void initializeNashornGlobals() {
    if (!Script.class.getClassLoader().getParent().toString().contains("ExtClassLoader")) {
      logger.warn(
          "Found wrong classloader: To prevent Class loading Problems use this directive in start.sh/-.bat: -Dorg.osgi.framework.bundle.parent=ext");
    }
    try {

      logger.info("initializeSciptGlobals for : " + engine.getFactory().getEngineName());
      engine.put("ItemRegistry", scriptManager.getItemRegistry());
      engine.put("ir", scriptManager.getItemRegistry());
      engine.eval(
          "var shared = org.openhab.core.jsr223.internal.shared,\n"
              + "RuleSet 				= Java.type('org.openhab.core.jsr223.internal.shared.RuleSet'),\n"
              + "Rule 					= Java.type('org.openhab.core.jsr223.internal.shared.Rule'),\n"
              + "ChangedEventTrigger 	= Java.type('org.openhab.core.jsr223.internal.shared.ChangedEventTrigger'),\n"
              + "CommandEventTrigger 	= Java.type('org.openhab.core.jsr223.internal.shared.CommandEventTrigger'),\n"
              + "Event 				= Java.type('org.openhab.core.jsr223.internal.shared.Event'),\n"
              + "EventTrigger			= Java.type('org.openhab.core.jsr223.internal.shared.EventTrigger'),\n"
              + "ShutdownTrigger 		= Java.type('org.openhab.core.jsr223.internal.shared.ShutdownTrigger'),\n"
              + "StartupTrigger 		= Java.type('org.openhab.core.jsr223.internal.shared.StartupTrigger'),\n"
              + "TimerTrigger 			= Java.type('org.openhab.core.jsr223.internal.shared.TimerTrigger'),\n"
              + "TriggerType 			= Java.type('org.openhab.core.jsr223.internal.shared.TriggerType'),\n"
              + "PersistenceExtensions	= Java.type('org.openhab.core.persistence.extensions.PersistenceExtensions'),\n"
              + "pe					= Java.type('org.openhab.core.persistence.extensions.PersistenceExtensions'),\n"
              + "HistoricItem			= Java.type('org.openhab.core.persistence.HistoricItem'),\n"
              + "oh 					= Java.type('org.openhab.core.jsr223.internal.shared.Openhab'),\n"
              + "State 				= Java.type('org.openhab.core.types.State'),\n"
              + "Command 				= Java.type('org.openhab.core.types.Command'),\n"
              + "DateTime 				= Java.type('org.joda.time.DateTime'),\n"
              + "StringUtils 			= Java.type('org.apache.commons.lang.StringUtils'),\n"
              + "URLEncoder 			= Java.type('java.net.URLEncoder'),\n"
              + "CallType 				= Java.type('org.openhab.library.tel.types.CallType'),\n"
              + "DateTimeType 			= Java.type('org.openhab.core.library.types.DateTimeType'),\n"
              + "DecimalType 			= Java.type('org.openhab.core.library.types.DecimalType'),\n"
              + "HSBType 				= Java.type('org.openhab.core.library.types.HSBType'),\n"
              + "IncreaseDecreaseType 	= Java.type('org.openhab.core.library.types.IncreaseDecreaseType'),\n"
              + "OnOffType 			= Java.type('org.openhab.core.library.types.OnOffType'),\n"
              + "OpenClosedType 		= Java.type('org.openhab.core.library.types.OpenClosedType'),\n"
              + "PercentType 			= Java.type('org.openhab.core.library.types.PercentType'),\n"
              + "PointType 			= Java.type('org.openhab.core.library.types.PointType'),\n"
              + "StopMoveType 			= Java.type('org.openhab.core.library.types.StopMoveType'),\n"
              + "UpDownType 			= Java.type('org.openhab.core.library.types.UpDownType'),\n"
              + "StringType 			= Java.type('org.openhab.core.library.types.StringType'),\n"
              + "UnDefType 			= Java.type('org.openhab.core.types.UnDefType'),\n"

              // As of now, Nashorn does not support calling super class methods.
              // http://nashorn-dev.openjdk.java.narkive.com/VX59ksgk/calling-super-methods-when-extending-classes
              // therefore:
              + "BusEvent 				= Java.type('org.openhab.model.script.actions.BusEvent'),\n"
              + "be 					= Java.type('org.openhab.model.script.actions.BusEvent'),\n"
              + "transform 			= oh.getAction('Transformation').static.transform,\n"

              // Item
              + "getItem 				= ItemRegistry.getItem,\n"
              + "postUpdate 			= BusEvent.postUpdate,\n"
              + "sendCommand 			= BusEvent.sendCommand,\n"

              // System
              + "FileUtils 			= Java.type('org.apache.commons.io.FileUtils'),\n"
              + "FilenameUtils			= Java.type('org.apache.commons.io.FilenameUtils'),\n"
              + "File 					= Java.type('java.io.File'),\n"
              + "ohEngine				= 'javascript';\n"

          // Helper Functions and Libs eventually later a lib Folder for default (Auto) loaded
          // Libraries
          // Bas64: https://gist.github.com/ncerminara/11257943
          // +"load('configurations/scripts/jslib/b64.js');\n"
          );

    } catch (ScriptException e) {
      logger.error(
          "ScriptException in initializeSciptGlobals while importing default-classes: ", e);
    }
  }
  public synchronized Element insertLine(
      String command,
      boolean replaceLast,
      boolean insertPrecedingWait,
      boolean removePrecedingWait) {
    //        System.out.println("insertLine(\"" + command + "\")");
    EditorPnl editor = getEditorPnl();
    if (editor != null) {
      try {
        Document doc = editor.getEditor().getDocument();
        int caretPos = editor.getEditor().getCaretPosition();
        //                System.out.println("  -->Initial caret position: " + caretPos);
        int elemIndex = doc.getDefaultRootElement().getElementIndex(caretPos);
        boolean insertNewLine = true;

        Element ce = doc.getDefaultRootElement().getElement(elemIndex);
        String txt = DocumentUtils.getElementText(ce).trim();
        if (!replaceLast && caretPos == 0 && elemIndex == 0 && !"".equals(txt)) {
          doc.insertString(0, "\n", null);
          txt = "";
          insertNewLine = false;
        }

        // The following code finds out if we are in an empty line or not.
        // If the current line contains some text, a new line is inserted
        // and the caret is moved there.
        if (!txt.equals("")) {
          Element next = doc.getDefaultRootElement().getElement(elemIndex + 1);
          if (next == null || !DocumentUtils.getElementText(next).trim().equals("")) {
            //                        DocumentUtils.analyzeEditorDocument(editor.getEditor(),
            // false);
            //                        System.out.println("Inserting an empty line to offset " +
            // ce.getEndOffset());
            doc.insertString(ce.getEndOffset() - 1, "\n", null);
            //                        DocumentUtils.analyzeEditorDocument(editor.getEditor(),
            // false);
            next =
                doc.getDefaultRootElement()
                    .getElement(doc.getDefaultRootElement().getElementIndex(ce.getEndOffset() + 1));
          }
          //                    caretPos = next.getEndOffset()-1;
          caretPos = ce.getEndOffset();
          //                    System.out.println("Setting caret position to "+caretPos);
          //                    System.out.println("  -->1. Setting caret position to: " +
          // caretPos);
          editor.getEditor().setCaretPosition(caretPos);
        }

        Element e = DocumentUtils.getCommandElementPriorTo(doc, caretPos);
        //                System.out.println(" --> Element prior: " +
        // DocumentUtils.getElementText(e));

        // First look if we should insert a Wait command
        if (!replaceLast
            && (insertPrecedingWait || removePrecedingWait)
            && (!firstRecord && !removePrecedingWait)
            && e != null) {
          String prevCmd = DocumentUtils.getElementText(e);
          int pos = prevCmd.indexOf(" ");
          String cmd = pos >= 0 ? prevCmd.substring(0, pos) : prevCmd;
          String time = convertTime(System.currentTimeMillis() - lastInsertTime);
          CommandHandler h =
              (CommandHandler) scriptManager.getCommandHandlers().get(cmd.toUpperCase());

          if (!"waitfor".equalsIgnoreCase(cmd) && !"screenshot".equalsIgnoreCase(cmd)) {

            if (h != null
                && h.getContextAttributes() != null
                && h.getContextAttributes().containsKey("wait")) {
              doc.remove(e.getStartOffset(), prevCmd.length());
              String replaceStr = insertPrecedingWait ? " wait=" + time : "";
              String s =
                  prevCmd
                          .replaceAll("\\n", "")
                          .replaceAll("\\swait=[\"]*[0-9]*[sSmMhHdD]*[\"]*", "")
                      + replaceStr;
              doc.insertString(e.getStartOffset(), s, null);
              caretPos = e.getEndOffset();
              //                            System.out.println("  -->2. Setting caret position to: "
              // + caretPos);
            } else {
              String waitCmd = "Wait " + time + '\n';
              doc.insertString(caretPos, waitCmd, null);
              caretPos += waitCmd.length();
              //                            System.out.println("  -->3. Setting caret position to: "
              // + caretPos);
            }
          }
        }

        firstRecord = false;

        if (replaceLast && e != null) {
          int length = e.getEndOffset() - e.getStartOffset();
          doc.remove(e.getStartOffset(), length);
          caretPos = e.getStartOffset();
        }
        command = insertNewLine && !replaceLast ? command + "\n" : command;
        doc.insertString(caretPos, command, null);
        editor.getEditor().setCaretPosition(caretPos + 1);

        //                System.out.println(" --> Inserted, caretPos = " +
        // editor.getEditor().getCaretPosition());

        //                DocumentUtils.analyzeEditorDocument(editor.getEditor(), true);
        lastElement =
            doc.getDefaultRootElement()
                .getElement(doc.getDefaultRootElement().getElementIndex(caretPos));
        lastInsertTime = System.currentTimeMillis();
        filterRfbEvents();

      } catch (Exception ex) {
        ex.printStackTrace();
      }
    }
    return lastElement;
  }