/**
   * Register an event. python-facing. this version converts from string info.
   *
   * @param handler function handler
   * @param type Event type string
   * @param priority Event priority string
   */
  public void registerEvent(PyObject handler, PyString type, PyString priority) {
    try {
      String clazz = type.asString();
      Class<?> event = null;

      if (clazz.contains(".")) {
        try {
          // try if we can find the class
          event = Class.forName(clazz);
        } catch (ClassNotFoundException e) {
          // assume the subpackage and class name was given and append org.bukkit.event
          event = Class.forName("org.bukkit.event." + clazz);
        }
      } else if (customEvents.containsKey(clazz)) {
        // check if the name of a custom event was given
        event = customEvents.get(clazz);
      } else {
        throw new IllegalArgumentException("Could not find Event " + clazz);
      }

      if (!event.getClass().isInstance(event)) {
        throw new IllegalArgumentException(type.asString().toUpperCase() + " is not of type Event");
      }
      Class<? extends Event> realtype = (Class<? extends Event>) event;
      EventPriority realpriority = EventPriority.valueOf(priority.upper());
      registerEvent(handler, realtype, realpriority);

    } catch (ClassNotFoundException e) {
      Bukkit.getLogger()
          .log(
              Level.SEVERE,
              "Could not register event " + type + " because the event could not be found",
              e);
    }
  }
 public String markdownToHtml(String chaine) {
   PythonInterpreter console = getMdBox().getPyconsole();
   console.set("text", chaine);
   console.exec(
       "render = Markdown(extensions=(ZdsExtension({'inline': False, 'emoticons': smileys}),),safe_mode = 'escape', enable_attributes = False, tab_length = 4, output_format = 'html5', smart_emphasis = True, lazy_ol = True).convert(text)");
   PyString render = console.get("render", PyString.class);
   return render.toString();
 }
 @Override
 public void write(DataOutput out) throws IOException {
   PyString pyString;
   try {
     pyString = cPickle.dumps(getPyObject());
   } catch (PyException e) {
     LOG.fatal("Could not serialize wrapped Jython value: " + getPyObject().__str__());
     throw e;
   }
   WritableUtils.writeString(out, pyString.getString());
 }
Exemplo n.º 4
0
  @Test
  public void raw_usecase() {
    PythonInterpreter interpreter = new PyGateway().getInterpreter();

    // Set a variable with the content you want to work with
    interpreter.set(
        "code",
        ""
            + "(defn year-end-evaluation\n"
            + "  []\n"
            + "  (if (> (rand) 0.5)\n"
            + "    \"You get a raise!\"\n"
            + "    \"Better luck next year!\"))");

    // Simple use Pygments as you would in Python
    interpreter.exec(
        "from pygments import highlight\n"
            + "from pygments.lexers.jvm import ClojureLexer\n"
            + "from pygments.formatters import RawTokenFormatter\n"
            + "\n"
            + "result = highlight(code, ClojureLexer(), RawTokenFormatter())");

    // Get the result that has been set in a variable
    PyObject result = interpreter.get("result");
    PyString string = (PyString) result;
    assertThat(string.getString())
        .isEqualTo(
            ""
                + "Token.Punctuation\tu'('\n"
                + "Token.Keyword.Declaration\tu'defn '\n"
                + "Token.Name.Variable\tu'year-end-evaluation'\n"
                + "Token.Text\tu'\\n  '\n"
                + "Token.Punctuation\tu'['\n"
                + "Token.Punctuation\tu']'\n"
                + "Token.Text\tu'\\n  '\n"
                + "Token.Punctuation\tu'('\n"
                + "Token.Keyword\tu'if '\n"
                + "Token.Punctuation\tu'('\n"
                + "Token.Name.Builtin\tu'> '\n"
                + "Token.Punctuation\tu'('\n"
                + "Token.Name.Function\tu'rand'\n"
                + "Token.Punctuation\tu')'\n"
                + "Token.Text\tu' '\n"
                + "Token.Literal.Number.Float\tu'0.5'\n"
                + "Token.Punctuation\tu')'\n"
                + "Token.Text\tu'\\n    '\n"
                + "Token.Literal.String\tu'\"You get a raise!\"'\n"
                + "Token.Text\tu'\\n    '\n"
                + "Token.Literal.String\tu'\"Better luck next year!\"'\n"
                + "Token.Punctuation\tu')'\n"
                + "Token.Punctuation\tu')'\n"
                + "Token.Text\tu'\\n'\n");
  }
Exemplo n.º 5
0
 public void write(PyObject ttype, PyString value) {
   out.append(ttype)
       .append(":[")
       .append(value.getString().replace("\n", "\\n"))
       .append("']")
       .append('\n');
 }
Exemplo n.º 6
0
 public void __delattr__(String name) {
   PyType self_type = getType();
   PyObject impl = self_type.lookup("__delattr__");
   if (impl != null) {
     impl.__get__(this, self_type).__call__(PyString.fromInterned(name));
     return;
   }
   super.__delattr__(name);
 }
 public void __setattr__(String name, PyObject value) {
   PyType self_type = getType();
   PyObject impl = self_type.lookup("__setattr__");
   if (impl != null) {
     impl.__get__(this, self_type).__call__(PyString.fromInterned(name), value);
     // CPython does not support instance-acquired finalizers.
     // So we don't check for __del__ here.
     return;
   }
   super.__setattr__(name, value);
 }
 public void setDict(PyObject newDict) {
   if (newDict instanceof PyStringMap || newDict instanceof PyDictionary) {
     dict = newDict;
     if (dict.__finditem__(PyString.fromInterned("__del__")) != null
         && !JyAttribute.hasAttr(this, JyAttribute.FINALIZE_TRIGGER_ATTR)) {
       FinalizeTrigger.ensureFinalizer(this);
     }
   } else {
     throw Py.TypeError("__dict__ must be set to a Dictionary " + newDict.getClass().getName());
   }
 }
 public PyObject __findattr_ex__(String name) {
   PyType self_type = getType();
   // TODO: We should speed this up. As the __getattribute__ slot almost never
   //       changes, it is a good candidate for caching, as PyClass does with
   //       __getattr__. See #1102.
   PyObject getattribute = self_type.lookup("__getattribute__");
   PyString py_name = null;
   PyException firstAttributeError = null;
   try {
     if (getattribute != null) {
       py_name = PyString.fromInterned(name);
       return getattribute.__get__(this, self_type).__call__(py_name);
     } else {
       Py.Warning(String.format("__getattribute__ not found on type %s", self_type.getName()));
       PyObject ret = super.__findattr_ex__(name);
       if (ret != null) {
         return ret;
       } // else: pass through to __getitem__ invocation
     }
   } catch (PyException e) {
     if (!Py.matchException(e, Py.AttributeError)) {
       throw e;
     } else {
       firstAttributeError = e; // saved to avoid swallowing custom AttributeErrors
       // and pass through to __getattr__ invocation.
     }
   }
   PyObject getattr = self_type.lookup("__getattr__");
   if (getattr != null) {
     if (py_name == null) {
       py_name = PyString.fromInterned(name);
     }
     return getattr.__get__(this, self_type).__call__(py_name);
   }
   if (firstAttributeError != null) {
     throw firstAttributeError;
   }
   return null;
 }
Exemplo n.º 10
0
  StringPair extractString(Token t) {
    String string = t.getText();
    char quoteChar = string.charAt(0);
    int start = 0;
    int end;
    boolean ustring = false;
    boolean bstring = false;

    if (quoteChar == 'b' || quoteChar == 'B') {
      bstring = true;
      start++;
    }
    if (quoteChar == 'u' || quoteChar == 'U') {
      ustring = true;
      start++;
    }
    quoteChar = string.charAt(start);
    boolean raw = false;
    if (quoteChar == 'r' || quoteChar == 'R') {
      raw = true;
      start++;
    }
    int quotes = 3;
    if (string.length() - start == 2) {
      quotes = 1;
    }
    if (string.charAt(start) != string.charAt(start + 1)) {
      quotes = 1;
    }

    start = quotes + start;
    end = string.length() - quotes;
    string = string.substring(start, end);
    if (raw) {
      string = codecs.PyUnicode_DecodeRawUnicodeEscape(string, "strict");
    } else {
      string = PyString.decode_UnicodeEscape(string, 0, string.length(), "strict", true);
    }

    return new StringPair(string, ustring, bstring);
  }