@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)));
 }
Пример #2
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;
 }
Пример #3
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);
  }
 /**
  * Add class paths for the jython interpreter to find other modules within the portal directory
  * structure.
  *
  * @param portalId a portal id
  * @param sys jython system state
  */
 private void addSysPaths(String portalId, PySystemState sys) {
   for (String skin : skinPriority) {
     String sysPath = portalPath + "/" + portalId + "/" + skin + "/scripts";
     sys.path.append(Py.newString(sysPath));
   }
   if (!defaultPortal.equals(portalId)) {
     addSysPaths(defaultPortal, sys);
   }
 }
 @Override
 public void write(byte b[], int off, int len) throws IOException {
   checkClosed();
   StringBuilder builder = new StringBuilder(len - off);
   for (int i = off; i < len; i++) {
     builder.append((char) b[i]);
   }
   write(Py.newString(builder.toString()));
 }
Пример #6
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);
    }
  }
Пример #7
0
 Object unpack(ByteStream buf) {
   return Py.newString((char) buf.readByte());
 }
Пример #8
0
 void doUnpack(ByteStream buf, int count, PyList list) {
   list.append(Py.newString(buf.readString(count)));
 }
Пример #9
0
  /**
   * Returns the call in the syntax:
   *
   * <p>{? = call <procedure-name>(?, ?, ...)} {call <procedure-name>(?, ?, ...)}
   *
   * <p>As of now, all parameters variables are created and no support for named variable calling is
   * supported.
   *
   * @return String
   */
  public String toSql() throws SQLException {

    int colParam = 0;
    int colReturn = 0;

    if (this.columns != Py.None) {
      for (int i = 0, len = this.columns.__len__(); i < len; i++) {
        PyObject column = this.columns.__getitem__(i);
        int colType = column.__getitem__(COLUMN_TYPE).asInt();

        switch (colType) {
          case DatabaseMetaData.procedureColumnUnknown:
            throw zxJDBC.makeException(zxJDBC.NotSupportedError, "procedureColumnUnknown");
          case DatabaseMetaData.procedureColumnResult:
            throw zxJDBC.makeException(zxJDBC.NotSupportedError, "procedureColumnResult");

            // these go on the right hand side
          case DatabaseMetaData.procedureColumnIn:
          case DatabaseMetaData.procedureColumnInOut:
          case DatabaseMetaData.procedureColumnOut:
            colParam++;
            break;

            // these go on the left hand side
          case DatabaseMetaData.procedureColumnReturn:
            colReturn++;
            break;

          default:
            throw zxJDBC.makeException(zxJDBC.DataError, "unknown column type [" + colType + "]");
        }
      }
    }

    StringBuffer sql = new StringBuffer("{");

    if (colReturn > 0) {
      PyList list = new PyList();

      for (; colReturn > 0; colReturn--) {
        list.append(Py.newString("?"));
      }

      sql.append(Py.newString(",").join(list)).append(" = ");
    }

    String name = this.getProcedureName();

    sql.append("call ").append(name).append("(");

    if (colParam > 0) {
      PyList list = new PyList();

      for (; colParam > 0; colParam--) {
        list.append(Py.newString("?"));
      }

      sql.append(Py.newString(",").join(list));
    }

    return sql.append(")}").toString();
  }
Пример #10
0
  /** {@inheritDoc} */
  public Object getScriptedObject(ScriptSource scriptSourceLocator, Class[] scriptInterfaces)
      throws IOException, ScriptCompilationException {
    // TODO: how to do this when running under Tomcat?
    ContextHandler handler = WebAppContext.getCurrentWebAppContext();
    String basePath = "";
    if (handler != null) {
      File root = handler.getBaseResource().getFile();
      if (root != null && root.exists()) {
        basePath = root.getAbsolutePath() + File.separator + "WEB-INF" + File.separator;
      }
    }

    String strScript = scriptSourceLocator.getScriptAsString();
    if (scriptInterfaces.length > 0) {
      try {
        PySystemState state = new PySystemState();
        if (!"".equals(basePath)) {
          // Add webapp paths that can contain classes and .jar files to python search path
          state.path.insert(0, Py.newString(basePath + "classes"));
          File jarRoot = new File(basePath + "lib");
          if (jarRoot.exists()) {
            for (String filename :
                jarRoot.list(
                    new FilenameFilter() {
                      public boolean accept(File dir, String name) {
                        return (name.endsWith(".jar"));
                      }
                    })) {
              state.path.insert(1, Py.newString(basePath + "lib" + File.separator + filename));
            }
          }
        }
        PythonInterpreter interp = new PythonInterpreter(null, state);
        interp.exec(strScript);
        PyObject getInstance = interp.get("getInstance");
        if (!(getInstance instanceof PyFunction)) {
          throw new ScriptCompilationException("\"getInstance\" is not a function.");
        }
        PyObject _this;
        if (arguments == null) {
          _this = ((PyFunction) getInstance).__call__();
        } else {
          PyObject[] args = new PyObject[arguments.length];
          for (int i = 0; i < arguments.length; i++) {
            args[i] = new PyJavaInstance(arguments[i]);
          }
          _this = ((PyFunction) getInstance).__call__(args);
        }
        return _this.__tojava__(scriptInterfaces[0]);
      } catch (Exception ex) {
        logger.error("Error while loading script.", ex);
        if (ex instanceof IOException) {
          // Raise to caller
          throw (IOException) ex;
        } else if (ex instanceof ScriptCompilationException) {
          // Raise to caller
          throw (ScriptCompilationException) ex;
        }

        throw new ScriptCompilationException(ex.getMessage());
      }
    }
    logger.error("No scriptInterfaces provided.");
    return null;
  }
Пример #11
0
/**
 * CSV file reader.
 *
 * <p>Analogous to CPython's _csv.c::ReaderObj struct.
 */
@ExposedType(name = "_csv.reader")
public class PyReader extends PyIterator {

  public static final PyType TYPE = PyType.fromClass(PyReader.class);

  public PyString __doc__ =
      Py.newString(
          "CSV reader\n"
              + "\n"
              + "Reader objects are responsible for reading and parsing tabular data\n"
              + "in CSV format.\n");

  /** Parsing Dialect. */
  @ExposedGet public PyDialect dialect;

  /** The current line number. */
  @ExposedGet public int line_num = 0;

  /** The underlying input iterator. */
  private PyObject input_iter;

  /** Current CSV parse state. */
  private ParserState state = ParserState.START_RECORD;

  /** Field list for current record. */
  private PyList fields = new PyList();

  /** Current field builder in here. */
  private StringBuffer field = new StringBuffer(INITIAL_BUILDER_CAPACITY);

  /** Whether the field should be treated as numeric. */
  private boolean numeric_field = false;

  /** Initial capacity of the field StringBuilder. */
  private static final int INITIAL_BUILDER_CAPACITY = 4096;

  public PyReader(PyObject input_iter, PyDialect dialect) {
    this.input_iter = input_iter;
    this.dialect = dialect;
  }

  public PyObject __iternext__() {
    PyObject lineobj;
    PyObject fields;
    String line;
    char c;
    int linelen;

    parse_reset();
    do {
      lineobj = input_iter.__iternext__();
      if (lineobj == null) {
        // End of input OR exception
        if (field.length() != 0) {
          throw _csv.Error("newline inside string");
        } else {
          return null;
        }
      }

      line_num++;
      line = lineobj.toString();
      linelen = line.length();

      for (int i = 0; i < linelen; i++) {
        c = line.charAt(i);
        if (c == '\0') {
          throw _csv.Error("line contains NULL byte");
        }
        parse_process_char(c);
      }
      parse_process_char('\0');
    } while (state != ParserState.START_RECORD);

    fields = this.fields;
    this.fields = new PyList();

    return fields;
  }

  private void parse_process_char(char c) {
    switch (state) {
      case START_RECORD:
        // start of record
        if (c == '\0') {
          // empty line - return []
          break;
        } else if (c == '\n' || c == '\r') {
          state = ParserState.EAT_CRNL;
          break;
        }
        // normal character - handle as START_FIELD
        state = ParserState.START_FIELD;
        // *** fallthru ***
      case START_FIELD:
        // expecting field
        if (c == '\n' || c == '\r' || c == '\0') {
          // save empty field - return [fields]
          parse_save_field();
          state = c == '\0' ? ParserState.START_RECORD : ParserState.EAT_CRNL;
        } else if (c == dialect.quotechar && dialect.quoting != QuoteStyle.QUOTE_NONE) {
          // start quoted field
          state = ParserState.IN_QUOTED_FIELD;
        } else if (c == dialect.escapechar) {
          // possible escaped character
          state = ParserState.ESCAPED_CHAR;
        } else if (c == ' ' && dialect.skipinitialspace) {
          // ignore space at start of field
          ;
        } else if (c == dialect.delimiter) {
          // save empty field
          parse_save_field();
        } else {
          // begin new unquoted field
          if (dialect.quoting == QuoteStyle.QUOTE_NONNUMERIC) {
            numeric_field = true;
          }
          parse_add_char(c);
          state = ParserState.IN_FIELD;
        }
        break;

      case ESCAPED_CHAR:
        if (c == '\0') {
          c = '\n';
        }
        parse_add_char(c);
        state = ParserState.IN_FIELD;
        break;

      case IN_FIELD:
        // in unquoted field
        if (c == '\n' || c == '\r' || c == '\0') {
          // end of line - return [fields]
          parse_save_field();
          state = c == '\0' ? ParserState.START_RECORD : ParserState.EAT_CRNL;
        } else if (c == dialect.escapechar) {
          // possible escaped character
          state = ParserState.ESCAPED_CHAR;
        } else if (c == dialect.delimiter) {
          // save field - wait for new field
          parse_save_field();
          state = ParserState.START_FIELD;
        } else {
          // normal character - save in field
          parse_add_char(c);
        }
        break;

      case IN_QUOTED_FIELD:
        // in quoted field
        if (c == '\0') {;
        } else if (c == dialect.escapechar) {
          // Possible escape character
          state = ParserState.ESCAPE_IN_QUOTED_FIELD;
        } else if (c == dialect.quotechar && dialect.quoting != QuoteStyle.QUOTE_NONE) {
          if (dialect.doublequote) {
            // doublequote; " represented by ""
            state = ParserState.QUOTE_IN_QUOTED_FIELD;
          } else {
            // end of quote part of field
            state = ParserState.IN_FIELD;
          }
        } else {
          // normal character - save in field
          parse_add_char(c);
        }
        break;

      case ESCAPE_IN_QUOTED_FIELD:
        if (c == '\0') {
          c = '\n';
        }
        parse_add_char(c);
        state = ParserState.IN_QUOTED_FIELD;
        break;

      case QUOTE_IN_QUOTED_FIELD:
        // doublequote - seen a quote in an quoted field
        if (dialect.quoting != QuoteStyle.QUOTE_NONE && c == dialect.quotechar) {
          // save "" as "
          parse_add_char(c);
          state = ParserState.IN_QUOTED_FIELD;
        } else if (c == dialect.delimiter) {
          // save field - wait for new field
          parse_save_field();
          state = ParserState.START_FIELD;
        } else if (c == '\n' || c == '\r' || c == '\0') {
          // end of line - return [fields]
          parse_save_field();
          state = c == '\0' ? ParserState.START_RECORD : ParserState.EAT_CRNL;
        } else if (!dialect.strict) {
          parse_add_char(c);
          state = ParserState.IN_FIELD;
        } else {
          // illegal
          throw _csv.Error(
              String.format("'%c' expected after '%c'", dialect.delimiter, dialect.quotechar));
        }
        break;

      case EAT_CRNL:
        if (c == '\n' || c == '\r') {;
        } else if (c == '\0') {
          state = ParserState.START_RECORD;
        } else {
          String err =
              "new-line character seen in unquoted field - do you need to "
                  + "open the file in universal-newline mode?";
          throw _csv.Error(err);
        }
        break;
    }
  }

  private void parse_reset() {
    fields = new PyList();
    state = ParserState.START_RECORD;
    numeric_field = false;
  }

  private void parse_save_field() {
    PyObject field;

    field = new PyString(this.field.toString());
    if (numeric_field) {
      numeric_field = false;
      field = field.__float__();
    }
    fields.append(field);

    // XXX: fastest way to clear StringBuffer?
    this.field = new StringBuffer(INITIAL_BUILDER_CAPACITY);
  }

  private void parse_add_char(char c) {
    int field_len = field.length();
    if (field_len >= _csv.field_limit) {
      throw _csv.Error(String.format("field larger than field limit (%d)", _csv.field_limit));
    }
    field.append(c);
  }

  /** State of the CSV reader. */
  private enum ParserState {
    START_RECORD,
    START_FIELD,
    ESCAPED_CHAR,
    IN_FIELD,
    IN_QUOTED_FIELD,
    ESCAPE_IN_QUOTED_FIELD,
    QUOTE_IN_QUOTED_FIELD,
    EAT_CRNL;
  }
}