Example #1
1
  public void build() throws Exception {
    names = Generic.set();
    int access = superclass.getModifiers();
    if ((access & Modifier.FINAL) != 0) {
      throw new InstantiationException("can't subclass final class");
    }
    access = Modifier.PUBLIC | Modifier.SYNCHRONIZED;

    classfile = new ClassFile(myClass, mapClass(superclass), access);
    addProxy();
    addConstructors(superclass);
    classfile.addInterface("org/python/core/PyProxy");

    Set<String> seenmethods = Generic.set();
    addMethods(superclass, seenmethods);
    for (Class<?> iface : interfaces) {
      if (iface.isAssignableFrom(superclass)) {
        Py.writeWarning("compiler", "discarding redundant interface: " + iface.getName());
        continue;
      }
      classfile.addInterface(mapClass(iface));
      addMethods(iface, seenmethods);
    }
    doConstants();
    addClassDictInit();
  }
  /** Provide functionality for Oracle specific types, such as ROWID. */
  public PyObject getPyObject(ResultSet set, int col, int type) throws SQLException {

    PyObject obj = Py.None;

    switch (type) {
      case Types.BLOB:
        BLOB blob = ((OracleResultSet) set).getBLOB(col);

        if (blob == null) {
          return Py.None;
        }

        InputStream stream = new BufferedInputStream(blob.getBinaryStream());

        obj = Py.java2py(DataHandler.read(stream));
        break;

      case OracleTypes.ROWID:
        ROWID rowid = ((OracleResultSet) set).getROWID(col);

        if (rowid != null) {
          obj = Py.java2py(rowid.stringValue());
        }
        break;

      default:
        obj = super.getPyObject(set, col, type);
    }

    return (set.wasNull() ? Py.None : obj);
  }
Example #3
0
  /**
   * Prepare the binding dictionary with the correct datatypes.
   *
   * @param params a non-None list of params
   * @param bindings a dictionary of bindings
   */
  public void normalizeInput(PyObject params, PyObject bindings) throws SQLException {

    if (this.columns == Py.None) {
      return;
    }

    // do nothing with params at the moment
    for (int i = 0, len = this.columns.__len__(), binding = 0; i < len; i++) {
      PyObject column = this.columns.__getitem__(i);
      int colType = column.__getitem__(COLUMN_TYPE).asInt();

      switch (colType) {
        case DatabaseMetaData.procedureColumnIn:
        case DatabaseMetaData.procedureColumnInOut:

          // bindings are Python-indexed
          PyInteger key = Py.newInteger(binding++);

          if (bindings.__finditem__(key) == null) {
            int dataType = column.__getitem__(DATA_TYPE).asInt();
            bindings.__setitem__(key, Py.newInteger(dataType));
          }

          // inputs are JDBC-indexed
          this.inputSet.set(i + 1);
          break;
      }
    }
  }
  public void equip(CreatureObject actor, SWGObject item) {
    String template =
        ((item.getAttachment("customServerTemplate") == null)
            ? item.getTemplate()
            : (item.getTemplate().split("shared_")[0]
                + "shared_"
                + ((String) item.getAttachment("customServerTemplate"))
                + ".iff"));
    String serverTemplate = template.replace(".iff", "");

    PyObject func =
        core.scriptService.getMethod(
            "scripts/" + serverTemplate.split("shared_", 2)[0].replace("shared_", ""),
            serverTemplate.split("shared_", 2)[1],
            "equip");
    if (func != null) func.__call__(Py.java2py(core), Py.java2py(actor), Py.java2py(item));

    // TODO: bio-link (assign it by objectID with setAttachment and then just display the customName
    // for that objectID).

    if (!actor.getEquipmentList().contains(item)) {
      actor.addObjectToEquipList(item);
      processItemAtrributes(actor, item, true);
    }
  }
Example #5
0
 /**
  * Convenience method for constructing a type object of a Python exception, named as given, and
  * added to the namespace of the "_io" module.
  *
  * @param dict module dictionary
  * @param excname name of the exception
  * @param bases one or more bases (superclasses)
  * @return the constructed exception type
  */
 private static PyType makeException(PyObject dict, String excname, PyObject... bases) {
   PyStringMap classDict = new PyStringMap();
   classDict.__setitem__("__module__", Py.newString("_io"));
   PyType type = (PyType) Py.makeClass(excname, bases, classDict);
   dict.__setitem__(excname, type);
   return type;
 }
Example #6
0
  // XXX: needs to handle NumberFormatException (on input like 0b2) and needs
  //     a better long guard than ndigits > 11 (this is much to short for
  //     binary for example)
  Object makeInt(Token t) {
    String s = t.getText();
    int radix = 10;
    if (s.startsWith("0x") || s.startsWith("0X")) {
      radix = 16;
      s = s.substring(2, s.length());
    } else if (s.startsWith("0o") || s.startsWith("0O")) {
      radix = 8;
      s = s.substring(2, s.length());
    } else if (s.startsWith("0b") || s.startsWith("0B")) {
      radix = 2;
      s = s.substring(2, s.length());
    } else if (s.startsWith("0")) {
      radix = 8;
    }
    int ndigits = s.length();
    int i = 0;
    while (i < ndigits && s.charAt(i) == '0') i++;
    if ((ndigits - i) > 11) {
      return Py.newInteger(new BigInteger(s, radix));
    }

    long l = Long.valueOf(s, radix).longValue();
    if (l > 0xffffffffl || (l > Integer.MAX_VALUE)) {
      return Py.newInteger(new BigInteger(s, radix));
    }
    return Py.newInteger((int) l);
  }
Example #7
0
  /**
   * Read into the given PyObject that implements the Jython buffer API (with write access) or is a
   * PyArray.
   *
   * @param buf a PyObject compatible with the buffer API
   * @return the amount of data read as an int
   */
  public int readinto(PyObject buf) {

    // This is an inefficient version of readinto: but readinto is
    // not recommended for use in Python 2.x anyway

    if (buf instanceof PyArray) {
      // PyArray has the buffer interface but it only works for bytes at present
      PyArray array = (PyArray) buf;
      String read = read(array.__len__());
      for (int i = 0; i < read.length(); i++) {
        array.set(i, new PyString(read.charAt(i)));
      }
      return read.length();

    } else if (buf instanceof BufferProtocol) {
      try (PyBuffer view = ((BufferProtocol) buf).getBuffer(PyBUF.FULL_RO)) {
        if (view.isReadonly()) {
          // More helpful than falling through to CPython message
          throw Py.TypeError("cannot read into read-only " + buf.getType().fastGetName());
        } else {
          // Inefficiently, we have to go via a String
          String read = read(view.getLen());
          int n = read.length();
          for (int i = 0; i < n; i++) {
            view.storeAt((byte) read.charAt(i), i);
          }
          return read.length();
        }
      }
    }

    // No valid alternative worked
    throw Py.TypeError("argument 1 must be read-write buffer, not " + buf.getType().fastGetName());
  }
Example #8
0
 Object unpack(ByteStream buf) {
   int bits = BEreadInt(buf);
   float v = Float.intBitsToFloat(bits);
   if (PyFloat.float_format == PyFloat.Format.UNKNOWN
       && (Float.isInfinite(v) || Float.isNaN(v))) {
     throw Py.ValueError("can't unpack IEEE 754 special value on non-IEEE platform");
   }
   return Py.newFloat(v);
 }
Example #9
0
 Object unpack(ByteStream buf) {
   long bits = (((long) BEreadInt(buf)) << 32) + (BEreadInt(buf) & 0xFFFFFFFFL);
   double v = Double.longBitsToDouble(bits);
   if (PyFloat.double_format == PyFloat.Format.UNKNOWN
       && (Double.isInfinite(v) || Double.isNaN(v))) {
     throw Py.ValueError("can't unpack IEEE 754 special value on non-IEEE platform");
   }
   return Py.newFloat(v);
 }
Example #10
0
 private PyObject checkCircularReference(PyObject obj) {
   PyObject ident = null;
   if (markers != null) {
     ident = Py.newInteger(Py.id(obj));
     if (markers.__contains__(ident)) {
       throw Py.ValueError("Circular reference detected");
     }
     markers.__setitem__(ident, obj);
   }
   return ident;
 }
 @Override
 public long seek(long pos, int whence) {
   PyType self_type = getType();
   PyObject impl = self_type.lookup("seek");
   if (impl != null) {
     return impl.__get__(this, self_type)
         .__call__(Py.newLong(pos), Py.newInteger(whence))
         .asLong();
   } else {
     return super.seek(pos, whence);
   }
 }
Example #12
0
  private void runSphinx() throws MavenReportException {
    PySystemState engineSys = new PySystemState();

    engineSys.path.append(Py.newString(sphinxSourceDirectory.getAbsolutePath()));
    Py.setSystemState(engineSys);

    ScriptEngine engine = new ScriptEngineManager().getEngineByName("python");

    if (verbose) {
      getLog()
          .info(
              "Running sphinx on "
                  + sourceDirectory.getAbsolutePath()
                  + ", output will be placed in "
                  + outputDirectory.getAbsolutePath());
    }

    List<String> args = new ArrayList<String>();

    if (verbose) {
      args.add("-v");
    } else {
      args.add("-Q");
    }
    if (warningsAsErrors) {
      args.add("-W");
    }
    if (force) {
      args.add("-a");
      args.add("-E");
    }
    if (builder != null) {
      args.add("-b");
      args.add(builder);
    }
    if ((tags != null) && !tags.isEmpty()) {
      for (String tag : tags) {
        args.add("-t");
        args.add(tag);
      }
    }
    args.add("-n");
    args.add(sourceDirectory.getAbsolutePath());
    args.add(outputDirectory.getAbsolutePath());

    engine.put("args", args.toArray(new String[args.size()]));
    try {
      engine.eval("import sphinx; sphinx.main(args)");
    } catch (ScriptException ex) {
      throw new MavenReportException("Could not generate documentation", ex);
    }
  }
 public void cleanup() {
   systemState.callExitFunc();
   try {
     Py.getSystemState().stdout.invoke("flush");
   } catch (PyException pye) {
     // fall through
   }
   try {
     Py.getSystemState().stderr.invoke("flush");
   } catch (PyException pye) {
     // fall through
   }
 }
Example #14
0
 public PyObject __call__(PyObject args[], String keywords[]) {
   ThreadState ts = Py.getThreadState();
   if (ts.recursion_depth++ > ts.systemState.getrecursionlimit())
     throw Py.RuntimeError("maximum __call__ recursion depth exceeded");
   try {
     PyType self_type = getType();
     PyObject impl = self_type.lookup("__call__");
     if (impl != null) return impl.__get__(this, self_type).__call__(args, keywords);
     return super.__call__(args, keywords);
   } finally {
     --ts.recursion_depth;
   }
 }
Example #15
0
  /**
   * Gets the value of the attribute name.
   *
   * @param name
   * @return the attribute for the given name
   */
  public PyObject __findattr_ex__(String name) {

    if ("destinationDataHandler".equals(name)) {
      return Py.java2py(this.destDH);
    } else if ("sourceDataHandler".equals(name)) {
      return Py.java2py(this.sourceDH);
    } else if ("batchsize".equals(name)) {
      return Py.newInteger(this.batchsize);
    } else if ("queuesize".equals(name)) {
      return Py.newInteger(this.queuesize);
    }

    return super.__findattr_ex__(name);
  }
Example #16
0
 public int hashCode() {
   PyType self_type = getType();
   PyObject impl = self_type.lookup("__hash__");
   if (impl != null) {
     PyObject res = impl.__get__(this, self_type).__call__();
     if (res instanceof PyInteger) {
       return ((PyInteger) res).getValue().intValue();
     }
     throw Py.TypeError("__hash__ should return a int");
   }
   if (self_type.lookup("__eq__") != null || self_type.lookup("__cmp__") != null) {
     throw Py.TypeError(String.format("unhashable type: '%.200s'", getType().fastGetName()));
   }
   return super.hashCode();
 }
Example #17
0
 public void setDict(PyObject newDict) {
   if (newDict instanceof PyStringMap || newDict instanceof PyDictionary) {
     dict = newDict;
   } else {
     throw Py.TypeError("__dict__ must be set to a Dictionary " + newDict.getClass().getName());
   }
 }
 public T createObject(Object args[], String keywords[]) {
   PyObject convertedArgs[] = new PyObject[args.length];
   for (int i = 0; i < args.length; i++) {
     convertedArgs[i] = Py.java2py(args[i]);
   }
   return (T) klass.__call__(convertedArgs, keywords).__tojava__(interfaceType);
 }
Example #19
0
  /**
   * Create an iterator whose <code>next()</code> method returns the result of calling the function
   * (first argument) with a tuple of arguments returned from the iterable (second argument).
   *
   * @param starargs [0] = callable function, [1] = iterable with argument tuples
   */
  public static PyIterator starmap(PyObject[] starargs) {
    if (starargs.length != 2) {
      throw Py.TypeError("starmap requires 2 arguments, got " + starargs.length);
    }
    final PyObject callable = starargs[0];
    final PyObject iterator = starargs[1].__iter__();

    return new ItertoolsIterator() {

      public PyObject __iternext__() {
        PyObject args = nextElement(iterator);
        PyObject result = null;

        if (args != null) {
          if (!args.getClass().isAssignableFrom(PyTuple.class)) {
            throw Py.TypeError("iterator must return a tuple");
          }
          PyTuple argTuple = (PyTuple) args;
          // convert to array of PyObjects in call to function
          result = callable.__call__(argTuple.getArray());
        }
        return result;
      }
    };
  }
  /**
   * command decorator. approximately equivalent python:
   *
   * <pre>
   * def command(arg1, desc=None, usage=None, aliases=None):
   *     if isfunc(arg1):
   *         registerFunc(arg1, arg1.func_name)
   *     else:
   *         def decorate(func):
   *             registerFunc(func, arg1 if arg1 else func.func_name, usage, desc, aliases)
   * </pre>
   *
   * the literally equivalent python looks so similar to the actual code as to not be worth
   * mentioning
   *
   * @param args jython magic
   * @param keywords jython magic
   * @return jython magic
   */
  public PyObject command(PyObject args[], String keywords[]) {
    int kwdelta = args.length - keywords.length;
    if (args.length == 1 && args[0].isCallable()) {
      registerCommand((PyFunction) args[0]);
      return args[0];
    } else if (kwdelta == 1 || kwdelta == 0) {

      String desc = null;
      String usage = null;
      List<?> aliases = null;
      for (int i = kwdelta; i < args.length; i++) {
        String keyword = keywords[i - kwdelta];
        if (keyword.equals("desc") || keyword.equals("description")) desc = args[i].toString();
        else if (keyword.equals("usage")) usage = args[i].toString();
        else if (keyword.equals("aliases")) aliases = new PyList(args[i]);
      }
      final String name;
      if (kwdelta == 1) name = args[0].toString();
      else name = null;
      final String finaldesc = desc;
      final String finalusage = usage;
      final List<?> finalaliases = aliases;
      return new PyObject() {
        public PyObject __call__(PyObject func) {
          registerCommand(func, name, finalusage, finaldesc, finalaliases);
          return func;
        }
      };
    } else {
      throw Py.TypeError(
          "you gave command() bad arguments, but lahwran was tired when he wrote this, so you don't get a helpful error message. sucks to be you.");
    }
  }
Example #21
0
  private void encode_obj(PyList rval, PyObject obj, int indent_level) {
    /* Encode Python object obj to a JSON term, rval is a PyList */
    if (obj == Py.None) {
      rval.append(new PyString("null"));
    } else if (obj == Py.True) {
      rval.append(new PyString("true"));
    } else if (obj == Py.False) {
      rval.append(new PyString("false"));
    } else if (obj instanceof PyString) {
      rval.append(encode_string(obj));
    } else if (obj instanceof PyInteger || obj instanceof PyLong) {
      rval.append(obj.__str__());
    } else if (obj instanceof PyFloat) {
      rval.append(encode_float(obj));
    } else if (obj instanceof PyList || obj instanceof PyTuple) {
      encode_list(rval, obj, indent_level);
    } else if (obj instanceof PyDictionary) {
      encode_dict(rval, (PyDictionary) obj, indent_level);
    } else {
      PyObject ident = checkCircularReference(obj);
      if (defaultfn == Py.None) {
        throw Py.TypeError(String.format(".80s is not JSON serializable", obj.__repr__()));
      }

      PyObject newobj = defaultfn.__call__(obj);
      encode_obj(rval, newobj, indent_level);
      if (ident != null) {
        markers.__delitem__(ident);
      }
    }
  }
 /**
  * Get the value of a variable in the local namespace Value will be returned as an instance of the
  * given Java class. <code>interp.get("foo", Object.class)</code> will return the most appropriate
  * generic Java object.
  *
  * @param name the name of the variable
  * @param javaclass the class of object to return
  * @return the value of the variable as the given class, or null if that name isn't assigned
  */
 public <T> T get(String name, Class<T> javaclass) {
   PyObject val = locals.__finditem__(name.intern());
   if (val == null) {
     return null;
   }
   return Py.tojava(val, javaclass);
 }
Example #23
0
 /** for python x[] functionality */
 public DataSetElement __getitem__(int i) {
   try {
     return getElementAt(i);
   } catch (Throwable t) {
     throw Py.IndexError("index out of range: " + i);
   }
 }
 @Override
 public void write(int b) throws IOException {
   checkClosed();
   // Writing one byte at a time is going to be inefficient.
   // Of course it will be. :)
   write(Py.newString((char) (b & 0x7ff)));
 }
Example #25
0
 // xxx - may need to consider doing a generic arg parser here
 public static void pack_into(PyObject[] args) {
   if (args.length < 3) Py.TypeError("illegal argument type for built-in operation");
   String format = args[0].toString();
   FormatDef[] f = whichtable(format);
   int size = calcsize(format, f);
   pack_into(format, f, size, 1, args);
 }
Example #26
0
 public PyObject __call__(PyObject args[], String keywords[]) {
   // if(args[0].toString().endsWith(JAVA_IMPORT_PATH_ENTRY)){
   // return this;
   // }
   // System.out.println("CPythonImporter7: "+args[0]+"  "+args.length);
   // libPath = args[0].toString();
   String s = args[0].toString();
   if (knownPaths == null) {
     if (!libPaths.contains(s)) libPaths.add(s);
     return this;
   } else if (knownPaths.contains(s)) {
     if (!libPaths.contains(s)) libPaths.add(s);
     return this;
   }
   /*String suf = "."+getSystemDependendDynamicLibraryExtension();
   System.out.println(suf);
   File look = new File(args[0].toString());
   String[] ch = look.list();
   for (int i = 0; i < ch.length; ++i)
   {
   	//if (s.endsWith(suf))
   	{
   		//System.out.println("CPythonExtension handles "+args[0]);
   		//libPaths.add(args[0]);
   		//return this;
   	}
   }
   //return this;*/
   throw Py.ImportError("unable to handle");
 }
 /**
  * Allocates native memory, aligned to a minimum boundary.
  *
  * @param size The number of bytes to allocate
  * @param align The minimum alignment of the memory
  * @param clear Whether the memory should be cleared (zeroed)
  * @return A new {@link AllocatedDirectMemory}
  */
 static final AllocatedNativeMemory allocateAligned(int size, int align, boolean clear) {
   long memory = IO.allocateMemory(size + align - 1, clear);
   if (memory == 0) {
     throw Py.RuntimeError("failed to allocate " + size + " bytes");
   }
   return new AllocatedNativeMemory(memory, size, align);
 }
  final Invoker createInvoker(
      com.kenai.jffi.Function function, PyObject returnType, ParameterMarshaller[] marshallers) {
    CType cReturnType = CType.typeOf(returnType);
    if (cReturnType instanceof CType.Builtin) {
      switch (cReturnType.getNativeType()) {
        case VOID:
          return new VoidInvoker(function, marshallers);

        case BYTE:
          return new Signed8Invoker(function, marshallers);

        case UBYTE:
          return new Unsigned8Invoker(function, marshallers);

        case SHORT:
          return new Signed16Invoker(function, marshallers);

        case USHORT:
          return new Unsigned16Invoker(function, marshallers);

        case INT:
          return new Signed32Invoker(function, marshallers);

        case UINT:
          return new Unsigned32Invoker(function, marshallers);

        case LONGLONG:
          return new Signed64Invoker(function, marshallers);

        case ULONGLONG:
          return new Unsigned64Invoker(function, marshallers);

        case LONG:
          return Platform.getPlatform().longSize() == 32
              ? new Signed32Invoker(function, marshallers)
              : new Signed64Invoker(function, marshallers);

        case ULONG:
          return Platform.getPlatform().longSize() == 32
              ? new Unsigned32Invoker(function, marshallers)
              : new Unsigned64Invoker(function, marshallers);
        case FLOAT:
          return new FloatInvoker(function, marshallers);

        case DOUBLE:
          return new DoubleInvoker(function, marshallers);

        case POINTER:
          return new PointerInvoker(function, marshallers);

        case STRING:
          return new StringInvoker(function, marshallers);

        default:
          break;
      }
    }
    throw Py.RuntimeError("Unsupported return type: " + returnType);
  }
Example #29
0
  /**
   * Initializes the object's namespace.
   *
   * @param dict
   */
  public static void classDictInit(PyObject dict) {

    dict.__setitem__(
        "__version__",
        Py.newString("$Revision: 5206 $").__getslice__(Py.newInteger(11), Py.newInteger(-2), null));
    dict.__setitem__("bcp", new BCPFunc("bcp", 0, 1, 2, zxJDBC.getString("bcp")));
    dict.__setitem__("batchsize", Py.newString(zxJDBC.getString("batchsize")));
    dict.__setitem__("queuesize", Py.newString(zxJDBC.getString("queuesize")));

    // hide from python
    dict.__setitem__("classDictInit", null);
    dict.__setitem__("toString", null);
    dict.__setitem__("PyClass", null);
    dict.__setitem__("getPyClass", null);
    dict.__setitem__("sourceDH", null);
    dict.__setitem__("destDH", null);
  }
Example #30
0
 FormatDef init(char name) {
   String dataModel = System.getProperty("sun.arch.data.model");
   if (dataModel == null)
     throw Py.NotImplementedError("Can't determine if JVM is 32- or 64-bit");
   int length = dataModel.equals("64") ? 8 : 4;
   super.init(name, length, length);
   return this;
 }