Ejemplo n.º 1
1
  @SuppressWarnings("unchecked")
  public AnimatorCore(File file) throws FileNotFoundException {
    Beans.setDesignTime(false);
    rootContext = new BeanContextServicesSupport();
    try {
      URL specURL = new URL("file:///E:/czt/zml/examples/z/birthdaybook_unfolded.tex");
      history = new ZLiveHistory("BirthdayBook", "InitBirthdayBook", specURL);
    } catch (MalformedURLException ex) {
      ex.printStackTrace();
    }

    XMLDecoder decoder;
    decoder = new XMLDecoder(new FileInputStream(file), this);

    try {
      while (true) {
        final Form newForm;
        newForm = (Form) decoder.readObject();
        final JFrame frame =
            new JFrame() {
              /** */
              private static final long serialVersionUID = 4731706062562233200L;

              public void setVisible(boolean b) {
                super.setVisible(b);
                if (newForm.isVisible() != b) newForm.setVisible(b);
              };
            };

        newForm.addComponentListener(
            new ComponentAdapter() {
              public void componentHidden(ComponentEvent e) {
                // If the last form was closed, then quit.
                Vector<Form> visibleForms = new Vector<Form>(forms_);
                for (Iterator<Form> i = visibleForms.iterator(); i.hasNext(); )
                  if (!i.next().isVisible()) i.remove();
                visibleForms.remove(e.getComponent());
                if (visibleForms.isEmpty()) System.exit(0);
              };
            });
        newForm.addPropertyChangeListener(
            "title",
            new PropertyChangeListener() {
              public void propertyChange(PropertyChangeEvent evt) {
                frame.setTitle((String) evt.getNewValue());
              };
            });

        if (!newForm.isPreferredSizeSet()) newForm.setPreferredSize(newForm.getSize());

        newForm.setLocation(0, 0);
        frame.getContentPane().setLayout(new BorderLayout());
        frame.getContentPane().add(newForm, BorderLayout.CENTER);
        frame.pack();
        frame.setTitle(newForm.getTitle());

        // XXX URGENT setVisible should be moved after the init scripts.
        //    If somebody starts using the interface before the init script
        //    finishes it can have `weird and fun' side-effects
        //        frame.setVisible(newForm.getStartsVisible());

        forms_.add(newForm);
        decoder.readObject(); // beanWrappers
        // unchecked
        Vector<BeanLink> beanLinks = (Vector<BeanLink>) decoder.readObject(); // eventLinks
        for (Iterator<BeanLink> iter = beanLinks.iterator(); iter.hasNext(); ) {
          BeanLink bl = iter.next();
          IntrospectionHelper.addBeanListener(bl.source, bl.listenerType, bl.listener);
        }
        rootContext.add(newForm); // unchecked
      }
    } catch (ArrayIndexOutOfBoundsException ex) {
    } finally {
      decoder.close();
    }

    // XXX Load Z specification.
    // XXX Display appropriate forms.

    BSFManager bsfm = new BSFManager();
    // XXX (register any new scripting languages)
    // XXX register and declare beans in bsfm
    try {
      bsfm.declareBean("History", history, history.getClass());
      bsfm.declareBean("AnimatorCore", this, this.getClass());
      bsfm.declareBean("Forms", forms_, forms_.getClass());
      bsfm.declareBean("err", System.err, System.err.getClass());
      bsfm.declareBean("out", System.out, System.out.getClass());
    } catch (BSFException ex) {
      throw new Error(
          "History,AnimatorCore, or Forms couldn't be declared "
              + "with the Scripting Engine. "
              + ex);
    }

    rootContext.addService(BSFManager.class, new BSFServiceProvider(bsfm));
    rootContext.addService(History.class, new HistoryServiceProvider(history));
    try {
      bsfm.exec(initScriptLanguage_, "init", 1, 1, initScript_);
    } catch (BSFException ex) {
      // XXX Do something?
      // error dialog?
      // send message back?
      // make it settable?
      System.err.println("Init Script caught BSFException:");
      System.err.println(ex);
      ex.printStackTrace();
      System.err.println("------");
      ex.getTargetException().printStackTrace();
    }
    ;
    for (Iterator<Form> it = forms_.iterator(); it.hasNext(); ) {
      Form form = it.next();
      boolean v = form.getStartsVisible();
      form.setVisible(v);
      System.err.println("Setting visible " + form.getName() + " = " + v);
    }
  };
Ejemplo n.º 2
0
 public void eval(BSFManager interpreter) throws BSFException {
   // interpreter.eval(ExpressionFieldExtension.BEANSHELL,null,-1,-1,"String
   // toString(java.lang.Object value){"
   // +
   // "if (value instanceof java.util.Date)" +
   // "return ((java.util.Date)value).toString();" +
   // "return String.valueOf(value);};");
   interpreter.exec(
       ExpressionFieldExtension.JYTHON,
       null,
       -1,
       -1,
       "import java.util.Date as Date\n"
           + "import java.text.DateFormat as DateFormat\n"
           + "import java.text.SimpleDateFormat as SimpleDateFormat\n"
           + "import java.text.NumberFormat as NumberFormat\n"
           + "dateFormat = DateFormat.getInstance()\n"
           + "myDateFormat = SimpleDateFormat()\n"
           + "def dateToString(value, format=None):\n"
           + "  if value == None:\n"
           + "    return None\n"
           + "  if value == '':\n"
           + "    return ''\n"
           + "  if isinstance(value,Date):\n"
           + "    if format != None:\n"
           + "      myDateFormat.applyPattern(format)\n"
           + "      return myDateFormat.format(value)\n"
           + "    else:\n"
           + "      return dateFormat.format(value)\n"
           + "  else:\n"
           + "    raise InputError\n"
           + "  return str(value)");
 }
Ejemplo n.º 3
0
 //	public Object getValue(String nameField,Index indexRow,SelectableDataSource sds) {
 //		try {
 //			int index=sds.getFieldIndexByName(nameField);
 //			Value value=sds.getFieldValue(indexRow.get(),index);
 //			if (value instanceof NumericValue) {
 //				double dv=((NumericValue)value).doubleValue();
 //				return new Double(dv);
 //			}else if (value instanceof DateValue) {
 //				Date date=((DateValue)value).getValue();
 //				return date;
 //			}else if (value instanceof BooleanValue){
 //				boolean b=((BooleanValue)value).getValue();
 //				return new Boolean(b);
 //			}else {
 //				return value.toString();
 //			}
 //		} catch (ReadDriverException e) {
 //			throw new RuntimeException(e.getMessage());
 //		}
 //	}
 public void eval(BSFManager interpreter) throws BSFException {
   if (!isEval) {
     interpreter.declareBean("jfield", this, Field.class);
     interpreter.exec(
         ExpressionFieldExtension.JYTHON,
         null,
         -1,
         -1,
         "def field(nameField):\n"
             + "  return jfield.getValue(featureContainer.getFeature(), nameField)");
     isEval = true;
   }
 }
Ejemplo n.º 4
0
 public void eval(BSFManager interpreter) throws BSFException {
   //		interpreter.eval(ExpressionFieldExtension.BEANSHELL,null,-1,-1,"String
   // toString(java.lang.Object value){" +
   //				"if (value instanceof java.util.Date)" +
   //					"return ((java.util.Date)value).toString();" +
   //				"return String.valueOf(value);};");
   interpreter.exec(
       ExpressionFieldExtension.JYTHON,
       null,
       -1,
       -1,
       "def toString(value):\n" + "  return str(value)");
 }
  /* (non-Javadoc)
   * @see org.opennms.netmgt.notifd.NotificationStrategy#send(java.util.List)
   */
  @Override
  public int send(List<Argument> arguments) {
    m_arguments = arguments;
    String fileName = getFileName();
    String lang = getLangClass();
    String engine = getBsfEngine();
    String extensions[] = getFileExtensions();

    LogUtils.infof(this, "Loading notification script from file '%s'", fileName);
    File scriptFile = new File(fileName);
    BSFManager bsfManager = new BSFManager();
    int returnCode = -1;

    try {

      if (lang == null) lang = BSFManager.getLangFromFilename(fileName);

      // Declare some beans that can be used inside the script
      HashMap<String, String> results = new HashMap<String, String>();
      bsfManager.declareBean("results", results, HashMap.class);
      declareBeans(bsfManager);

      if (engine != null && lang != null && extensions != null && extensions.length > 0) {
        BSFManager.registerScriptingEngine(lang, engine, extensions);
      }

      if (scriptFile.exists() && scriptFile.canRead()) {
        String code =
            IOUtils.getStringFromReader(
                new InputStreamReader(new FileInputStream(scriptFile), "UTF-8"));

        // Check foot before firing
        checkAberrantScriptBehaviors(code);

        // Execute the script
        bsfManager.exec(lang, "BSFNotificationStrategy", 0, 0, code);

        // Check whether the script finished successfully
        if ("OK".equals(results.get("status"))) {
          LogUtils.infof(
              this,
              "Execution succeeded and successful status passed back for script '%s'",
              scriptFile);
          returnCode = 0;
        } else {
          LogUtils.warnf(
              this,
              "Execution succeeded for script '%s', but script did not indicate successful notification by putting an entry into the 'results' bean with key 'status' and value 'OK'",
              scriptFile);
          returnCode = -1;
        }
      } else {
        LogUtils.warnf(
            this,
            "Cannot locate or read BSF script file '%s'. Returning failure indication.",
            fileName);
        returnCode = -1;
      }
    } catch (BSFException e) {
      LogUtils.warnf(
          this,
          e,
          "Execution of script '%s' failed with BSFException: %s",
          scriptFile,
          e.getMessage());
      returnCode = -1;
    } catch (FileNotFoundException e) {
      LogUtils.warnf(this, "Could not find BSF script file '%s'.", fileName);
      returnCode = -1;
    } catch (IOException e) {
      LogUtils.warnf(
          this,
          e,
          "Execution of script '%s' failed with IOException: %s",
          scriptFile,
          e.getMessage());
      returnCode = -1;
    } catch (Throwable e) {
      // Catch any RuntimeException throws
      LogUtils.warnf(
          this,
          e,
          "Execution of script '%s' failed with unexpected throwable: %s",
          scriptFile,
          e.getMessage());
      returnCode = -1;
    } finally {
      bsfManager.terminate();
    }

    return returnCode;
  }
Ejemplo n.º 6
0
  /**
   * Evaluate the expression.
   *
   * @throws ReadDriverException
   * @throws BSFException
   */
  public boolean evalExpression(String expression) throws ReadDriverException, BSFException {
    long rowCount = sds.getRowCount();
    byte[] expressionBytes;
    String encoding = System.getProperty("file.encoding");
    try {
      expressionBytes = expression.getBytes(encoding);
      expression = new String(expressionBytes, "ISO-8859-1");
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    expression = expression.replaceAll("\\[", "field(\"").replaceAll("\\]", "\")");

    interpreter.declareBean("ee", this, EvalExpression.class);
    interpreter.exec(
        ExpressionFieldExtension.JYTHON,
        null,
        -1,
        -1,
        "def expression():\n" + "  return " + expression + "");
    if (rowCount > 0) {
      try {
        interpreter.exec(
            ExpressionFieldExtension.JYTHON,
            null,
            -1,
            -1,
            "def isCorrect():\n" + "    ee.isCorrectValue(expression())\n");
        interpreter.exec(ExpressionFieldExtension.JYTHON, null, -1, -1, "isCorrect()");
      } catch (BSFException ee) {
        String message = ee.getMessage();
        if (message.length() > 200) {
          message = message.substring(0, 200);
        }
        int option =
            JOptionPane.showConfirmDialog(
                (Component) PluginServices.getMainFrame(),
                PluginServices.getText(this, "error_expression")
                    + "\n"
                    + message
                    + "\n"
                    + PluginServices.getText(this, "continue?"));
        if (option != JOptionPane.OK_OPTION) {
          return false;
        }
      }
    }
    ies.startComplexRow();

    ArrayList exceptions = new ArrayList();
    interpreter.declareBean("exceptions", exceptions, ArrayList.class);
    FBitSet selection = sds.getSelection();
    if (selection.cardinality() > 0) {
      interpreter.declareBean("selection", selection, FBitSet.class);
      interpreter.exec(
          ExpressionFieldExtension.JYTHON,
          null,
          -1,
          -1,
          "def p():\n"
              + "  i=selection.nextSetBit(0)\n"
              + "  while i >=0:\n"
              + "    indexRow.set(i)\n"
              + "    obj=expression()\n"
              + "    ee.setValue(obj,i)\n"
              + "    ee.saveEdits(i)\n"
              + "    i=selection.nextSetBit(i+1)\n");
    } else {
      interpreter.exec(
          ExpressionFieldExtension.JYTHON,
          null,
          -1,
          -1,
          "def p():\n"
              + "  for i in xrange("
              + rowCount
              + "):\n"
              + "    indexRow.set(i)\n"
              +
              //						"    print i , expression() , repr (expression())\n" +
              "    ee.setValue(expression(),i)\n"
              + "    ee.saveEdits(i)\n");
    }
    try {
      interpreter.eval(ExpressionFieldExtension.JYTHON, null, -1, -1, "p()");
    } catch (BSFException ee) {

      JOptionPane.showMessageDialog(
          (Component) PluginServices.getMainFrame(),
          PluginServices.getText(this, "evaluate_expression_with_errors")
              + " "
              + (rowCount - indexRow.get())
              + "\n"
              + ee.getMessage());
    }

    ies.endComplexRow(PluginServices.getText(this, "expression"));

    return true;
  }