org.python.core.PyException Java Examples

The following examples show how to use org.python.core.PyException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ScriptCommandImpl.java    From phoebus with Eclipse Public License 1.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public String[] getDeviceNames(final MacroContext macros) throws Exception
{
    try
    {
        final String[] names = script_object.getDeviceNames();
        for (int i=0; i<names.length; ++i)
            names[i] = macros.resolveMacros(names[i]);
        return names;
    }
    catch (PyException ex)
    {
        throw new Exception(command.getScript() + ":" + JythonSupport.getExceptionMessage(ex), ex);
    }
}
 
Example #2
Source File: JythonEngine.java    From commons-bsf with Apache License 2.0 6 votes vote down vote up
/**
 * Execute script code, emulating console interaction.
 */
public void iexec (String source, int lineNo, int columnNo,
                   Object script) throws BSFException {
    String scriptStr = byteify(script.toString());
    importPackage(scriptStr);
    int newline = scriptStr.indexOf("\n");

    if (newline > -1)
        scriptStr = scriptStr.substring(0, newline);

    try {
        if (interp.buffer.length() > 0)
            interp.buffer.append("\n");
        interp.buffer.append(scriptStr);
        if (!(interp.runsource(interp.buffer.toString())))
            interp.resetbuffer();
    } catch (PyException e) {
        interp.resetbuffer();
        throw new BSFException(BSFException.REASON_EXECUTION_ERROR, 
                               "exception from Jython:\n" + e, e);
    }
}
 
Example #3
Source File: JythonTest.java    From qpid-proton-j with Apache License 2.0 6 votes vote down vote up
private void runTestOnce(String testScript, PythonInterpreter interp, int invocationsSoFar)
{
    try
    {
        interp.execfile(testScript);
    }
    catch (PyException e)
    {
        if( e.type.toString().equals("<type 'exceptions.SystemExit'>") && e.value.toString().equals("0") )
        {
            // Build succeeded.
        }
        else
        {
            if (LOGGER.isLoggable(Level.FINE))
            {
                LOGGER.log(Level.FINE, "Jython interpreter failed. Test failures?", e);
            }

            // This unusual code is necessary because PyException toString() contains the useful Python traceback
            // and getMessage() is usually null
            fail("Caught PyException on invocation number " + invocationsSoFar + ": " + e.toString() + " with message: " + e.getMessage());
        }
    }
}
 
Example #4
Source File: ScanCommandImpl.java    From phoebus with Eclipse Public License 1.0 6 votes vote down vote up
/** Invoke the command's error handler
 *
 *  <p>If command has no custom error handler, 'Abort' will be returned.
 *
 *  @param context {@link ScanContext}
 *  @param error Error from call to <code>execute</code>
 *  @return How to proceed
 *  @throws Exception on error while trying to handle the error
 */
public Result handleError(final ScanContext context, final Exception error) throws Exception
{
    if (error_handler == null)
        return ScanErrorHandler.Result.Abort;
    else
    {
        try
        {
            final ScanScriptContext script_context = new ScriptCommandContextImpl(context);
            return error_handler.handleError(command, error, script_context);
        }
        catch (PyException ex)
        {
            throw new Exception("Error handler for " + command.getCommandName() + ":" +
                    JythonSupport.getExceptionMessage(ex), ex);
        }
    }
}
 
Example #5
Source File: ScanCommandImpl.java    From phoebus with Eclipse Public License 1.0 6 votes vote down vote up
/** Initialize
 *  @param command Command that is implemented
 *  @param jython Jython interpreter, may be <code>null</code>
 *  @throws Exception on error
 */
public ScanCommandImpl(final C command, final JythonSupport jython) throws Exception
{
    this.command = command;
    this.jython = jython;

    // Implement error handler?
    final String error_handler_class = command.getErrorHandler();
    if (error_handler_class.isEmpty()  ||  jython == null)
        error_handler = null;
    else
    {
        try
        {
            error_handler = jython.loadClass(ScanErrorHandler.class, error_handler_class);
        }
        catch (PyException ex)
        {
            throw new Exception(JythonSupport.getExceptionMessage(ex), ex);
        }
    }
}
 
Example #6
Source File: PythonScriptExecutionThread.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {

	try {
		interpreter.execFile(script.getSourceFile(), script);
	}
	catch (PyException pye) {
		if (PyException.exceptionClassName(pye.type).equalsIgnoreCase(
			"exceptions.SystemExit")) {
			interpreter.printErr("SystemExit");
		}
		else {
			pye.printStackTrace(); // this prints to the interpreter error stream.
		}
	}
	catch (StackOverflowError soe) {
		interpreter.printErr("Stack overflow!");
	}
	catch (IllegalStateException e) {
		interpreter.printErr(e.getMessage());
	}
	finally {
		interpreterRunning.set(false);
	}
}
 
Example #7
Source File: QueryableDevice.java    From androidtestdebug with MIT License 6 votes vote down vote up
/**
 * Get the coordinates of the element's center.
 * 
 * @param selector
 *            the element selector
 * @return the (x,y) coordinates of the center
 * @throws IOException
 * @throws UnsupportedEncodingException
 * @throws RecognitionException
 */
private Point getElementCenter(By selector, ControlHierarchy ch)
		throws UnsupportedEncodingException, IOException,
		RecognitionException {
	List<ITreeNode> result = selector.query(ch.getAllNodes());
	if (result == null) {
		throw new PyException(Py.ValueError, String.format(
				"找不到iQuery语句指定的控件: %s", selector.getSelector()));
	}

	if (result.size() != 1) {
		throw new PyException(Py.ValueError, String.format(
				"iQuery查询语句找到多于一个控件: %s", selector.getSelector()));
	}

	ITreeNode node = result.get(0);
	Point p = getAbsoluteCenterOfView(node);
	return p;
}
 
Example #8
Source File: JConsole.java    From opensim-gui with Apache License 2.0 6 votes vote down vote up
public void executeCommand(String commands) {

        StringBuilder text;

        moreCommand += commands;

        try {           
            // If command is not finished (i.e. loop)
            if(interp.runsource(moreCommand)) {
                text = new StringBuilder(getText()); 
                text.append(ps2);
                moreCommand += "\n";
            } else {
                text = new StringBuilder(getText()); 
                text.append(ps1);
                moreCommand = "";
            }

            setText(text.toString());
        } catch (PyException e) {
            e.printStackTrace();
        }
        fireCommandExecuted(commands);
    }
 
Example #9
Source File: PythonRowDoFnSecurityTest.java    From components with Apache License 2.0 6 votes vote down vote up
@Test(expected = UserCodeException.class)
public void test_limitCode() throws Throwable {
    String command =
            "from java.security import AccessControlException, Permissions, AllPermission, SecureClassLoader, CodeSource\n"
                    + "from java.net import URL\n" + "import java.security\n" + "\n"
                    + "class MagicClassLoader(SecureClassLoader):\n" + "  def _init_(self):\n"
                    + "    SecureClassLoader._init_(self)\n" + "    self.datamap = {}\n"
                    + "    self.codeSource = CodeSource(URL('file:/pwn'), None)\n" + "\n"
                    + "  def addClass(self, name, data):\n" + "    self.datamap[name] = data\n" + "\n"
                    + "  def findClass(self, name):\n" + "    data = self.datamap[name]\n"
                    + "    return self.super_defineClass(name, data, 0, len(data), self.codeSource)\n" + "    \n"
                    + "  def getPermissions(self, codesource):\n" + "    permissions = Permissions()\n"
                    + "    permissions.add(AllPermission())\n" + "    return permissions    \n" + "\n"
                    + "output = input\n";
    try {
        execute(command);
    } catch (PyException pyEx) {
        assertEquals("ImportError", ((PyType) pyEx.type).getName());
        assertEquals("No module named os", ((PyBaseExceptionDerived) pyEx.value).getMessage().toString());
        return;
    }
    assertTrue(false);
}
 
Example #10
Source File: JConsole.java    From opensim-gui with Apache License 2.0 5 votes vote down vote up
public void executeFile(String filename) {
    try {
        interp.execfile(filename);
    } catch (PyException e) {
        e.printStackTrace();
    }                    
  
    fireCommandExecuted(getFileContents(filename));
    fireCommandExecuted("Finished executing script file " + filename);

}
 
Example #11
Source File: ScriptCommandImpl.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public void execute(final ScanContext context) throws Exception
{
    is_cancelled = false;
    synchronized (this)
    {
        thread = Thread.currentThread();
    }
    try
    {
        final ScanScriptContext script_context = new ScriptCommandContextImpl(context);
        script_object.run(script_context);
    }
    catch (PyException ex)
    {
        // Ignore if 'next' was requested
        if (! is_cancelled)
            throw new Exception(command.getScript() + ":" + JythonSupport.getExceptionMessage(ex), ex);
    }
    finally
    {
        synchronized (this)
        {
            thread = null;
        }
    }

    context.workPerformed(1);
}
 
Example #12
Source File: JPythonInterpreterDriver.java    From tn5250j with GNU General Public License v2.0 5 votes vote down vote up
public void executeScript(SessionPanel session, String script)
      throws InterpreterDriver.InterpreterException {
   try {
      session.setMacroRunning(true);
      _interpreter.set("_session",session);
      _interpreter.exec(script);
      session.setMacroRunning(false);
   }
   catch (PyException ex) {
      throw new InterpreterDriver.InterpreterException(ex);
   }
}
 
Example #13
Source File: JPythonInterpreterDriver.java    From tn5250j with GNU General Public License v2.0 5 votes vote down vote up
public void executeScript(String script)
      throws InterpreterDriver.InterpreterException {
   try {
      _interpreter = new PythonInterpreter();
      _interpreter.exec(script);
   }
   catch (PyException ex) {
      throw new InterpreterDriver.InterpreterException(ex);
   }
}
 
Example #14
Source File: JPythonInterpreterDriver.java    From tn5250j with GNU General Public License v2.0 5 votes vote down vote up
public void executeScriptFile(String scriptFile)
               throws InterpreterDriver.InterpreterException {

   try {
      _interpreter.execfile(scriptFile);
   }
   catch (PyException ex) {
      throw new InterpreterDriver.InterpreterException(ex);
   }
}
 
Example #15
Source File: PythonRowDoFnSecurityTest.java    From components with Apache License 2.0 5 votes vote down vote up
public void execute(String command, MapType type) throws Throwable {
    try {
        PythonRowProperties properties = new PythonRowProperties("test");
        properties.init();
        properties.mapType.setValue(type);
        properties.pythonCode.setValue(command);
        PythonRowDoFn function = new PythonRowDoFn();
        function.initialize(null, properties);
        DoFnTester<IndexedRecord, IndexedRecord> fnTester = DoFnTester.of(function);
        fnTester.processBundle((IndexedRecord) inputIndexedRecord);
    } catch (PyException pyEx) {
        throw pyEx.getCause() == null ? pyEx : pyEx.getCause();
    }
}
 
Example #16
Source File: PythonRowDoFnSecurityTest.java    From components with Apache License 2.0 5 votes vote down vote up
@Test
public void test_oss() throws Throwable {
    String command = "import oss";
    try {
        execute(command);
    } catch (PyException pyEx) {
        assertEquals("ImportError", ((PyType) pyEx.type).getName());
        assertEquals("No module named oss", ((PyBaseExceptionDerived) pyEx.value).getMessage().toString());
        return;
    }
    assertTrue(false);
}
 
Example #17
Source File: JythonSupport.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
/** We can only report the message of an exception back to scan server
 *  clients, not the whole exception because it doesn't 'serialize'.
 *  The PyException, however, tends to have no message at all.
 *  This helper tries to generate a somewhat useful message
 *  from the content of the exception.
 *  @param ex Python exception
 *  @return Message with info about python exception
 */
public static String getExceptionMessage(final PyException ex)
{
    final StringBuilder buf = new StringBuilder();
    if (ex.value instanceof PyString)
        buf.append(" ").append(ex.value.asString());
    else if (ex.getCause() != null)
        buf.append(" ").append(ex.getCause().getMessage());
    if (ex.traceback != null)
    {
        buf.append(" ");
        ex.traceback.dumpStack(buf);
    }
    return buf.toString();
}
 
Example #18
Source File: PythonExecutor.java    From score with Apache License 2.0 5 votes vote down vote up
private boolean isThreadsRelatedModuleIssue(Exception e) {
    if (e instanceof PyException) {
        PyException pyException = (PyException) e;
        String message = pyException.value.toString();
        return message.contains(THREADED_MODULES_ISSUE);
    }
    return false;
}
 
Example #19
Source File: JavaPythonInteropUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenPythonInterpreter_whenErrorOccurs_thenExceptionIsThrown() {
    thrown.expect(PyException.class);
    thrown.expectMessage("ImportError: No module named syds");

    try (PythonInterpreter pyInterp = new PythonInterpreter()) {
        pyInterp.exec("import syds");
    }
}
 
Example #20
Source File: JyInterpreter.java    From minecraft-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void execfile(File script) {
	lastCall = System.currentTimeMillis();
	try {
		super.execfile(script.getAbsolutePath());
	} catch (PyException exc) {
           if (exc.match(Py.SystemExit)) {
               // Suppress this: we don't want clients to stop the whole JVM!
           	// We do stop this interpreter, however
           	this.close();
           	return;
           }
           showexception(exc);
       }
}
 
Example #21
Source File: JyInterpreter.java    From minecraft-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void runcode(PyObject code) {
    try {
        exec(code);
    } catch (PyException exc) {
        if (exc.match(Py.SystemExit)) {
            // Suppress this: we don't want clients to stop the whole JVM!
        	// We do stop this interpreter, however
        	this.close();
        	return;
        }
        showexception(exc);
    }
}
 
Example #22
Source File: JythonEngine.java    From commons-bsf with Apache License 2.0 5 votes vote down vote up
/**
 * call the named method of the given object.
 */
public Object call (Object object, String method, Object[] args) 
    throws BSFException {
    try {
        PyObject[] pyargs = Py.EmptyObjects;

        if (args != null) {
            pyargs = new PyObject[args.length];
            for (int i = 0; i < pyargs.length; i++)
                pyargs[i] = Py.java2py(args[i]);
        }

        if (object != null) {
            PyObject o = Py.java2py(object);
            return unwrap(o.invoke(method, pyargs));
        }

        PyObject m = interp.get(method);

        if (m == null)
            m = interp.eval(method);
        if (m != null) {
            return unwrap(m.__call__(pyargs));
        }

        return null;
    } catch (PyException e) {
        throw new BSFException (BSFException.REASON_EXECUTION_ERROR,
                                "exception from Jython:\n" + e, e);
    }
}
 
Example #23
Source File: JythonEngine.java    From commons-bsf with Apache License 2.0 5 votes vote down vote up
/**
 * Evaluate an anonymous function (differs from eval() in that apply() 
 * handles multiple lines).
 */
public Object apply (String source, int lineNo, int columnNo, 
                     Object funcBody, Vector paramNames,
                     Vector arguments) throws BSFException {
    try {
        /* We wrapper the original script in a function definition, and
         * evaluate the function. A hack, no question, but it allows
         * apply() to pretend to work on Jython.
         */
        StringBuffer script = new StringBuffer(byteify(funcBody.toString()));
        int index = 0;
        script.insert(0, "def bsf_temp_fn():\n");
       
        while (index < script.length()) {
            if (script.charAt(index) == '\n') {
                script.insert(index+1, '\t');
            }
            index++;
        }

        String scriptStr = script.toString ();
        importPackage(scriptStr);
        interp.exec (scriptStr);
        
        Object result = interp.eval ("bsf_temp_fn()");
        
        if (result != null && result instanceof PyJavaInstance)
            result = ((PyJavaInstance)result).__tojava__(Object.class);
        return result;
    } catch (PyException e) {
        throw new BSFException (BSFException.REASON_EXECUTION_ERROR,
                                "exception from Jython:\n" + e, e);
    }
}
 
Example #24
Source File: JythonEngine.java    From commons-bsf with Apache License 2.0 5 votes vote down vote up
/**
  * Evaluate an expression.
  */
 public Object eval (String source, int lineNo, int columnNo, 
	      Object script) throws BSFException {
try {
  String scriptStr = byteify(script.toString ());
  importPackage(scriptStr);
  Object result = interp.eval (scriptStr);
  if (result != null && result instanceof PyJavaInstance)
	result = ((PyJavaInstance)result).__tojava__(Object.class);
  return result;
} catch (PyException e) {
  throw new BSFException (BSFException.REASON_EXECUTION_ERROR,
		      "exception from Jython:\n" + e, e);
}
 }
 
Example #25
Source File: JythonEngine.java    From commons-bsf with Apache License 2.0 5 votes vote down vote up
/**
  * Execute a script. 
  */
 public void exec (String source, int lineNo, int columnNo,
	    Object script) throws BSFException {
try {
  String scriptStr = byteify(script.toString());
  importPackage(scriptStr);
  interp.exec (scriptStr);
} catch (PyException e) {
  throw new BSFException (BSFException.REASON_EXECUTION_ERROR,
		      "exception from Jython:\n" + e, e);
}
 }
 
Example #26
Source File: JythonEngine.java    From commons-bsf with Apache License 2.0 5 votes vote down vote up
public void runcode(PyObject code) {
    try {
        this.exec(code);
    } catch (PyException exc) {
        throw exc;
    }
}
 
Example #27
Source File: PythonSinkFunction.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
@Override
public void invoke(PyObject value, Context context) throws Exception {
	try {
		this.fun.invoke(value, context);
	} catch (PyException pe) {
		throw createAndLogException(pe);
	}
}
 
Example #28
Source File: PythonIteratorFunction.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
@Override
public void open(Configuration parameters) throws Exception {
	this.fun = InterpreterUtils.deserializeFunction(getRuntimeContext(), this.serFun);
	if (this.fun instanceof RichFunction) {
		try {
			final RichFunction winFun = (RichFunction) this.fun;
			winFun.setRuntimeContext(getRuntimeContext());
			winFun.open(parameters);
		} catch (PyException pe) {
			throw AbstractPythonUDF.createAndLogException(pe, LOG);
		}
	}
}
 
Example #29
Source File: PythonIteratorFunction.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
@Override
public void run(SourceContext<Object> ctx) throws Exception {
	try {
		while (isRunning && this.fun.hasNext()) {
			ctx.collect(this.fun.next());
		}
	} catch (PyException pe) {
		throw AbstractPythonUDF.createAndLogException(pe, LOG);
	}
}
 
Example #30
Source File: PythonIteratorFunction.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
@Override
public void close() throws Exception {
	if (this.fun instanceof RichFunction) {
		try {
			((RichFunction) this.fun).close();
		} catch (PyException pe) {
			throw AbstractPythonUDF.createAndLogException(pe, LOG);
		}
	}
}