Java Code Examples for org.python.core.PyString

The following examples show how to use org.python.core.PyString. These examples are extracted from open source projects. 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 Project: TrackRay   Source File: XunfengInner.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void process() {

    try {
        PythonInterpreter interpreter = python.interpreter();
        interpreter.execfile(filename);
        PyFunction check = interpreter.get("check", PyFunction.class);

        PyObject check_call = check.__call__(new PyString(ip), new PyInteger(port), new PyInteger(timeout));

        String result = check_call.toString();
        if (result!=null &&
                !StringUtils.contains(result,"None")
                && !StringUtils.contains(result,"False")) {

            //PyObject get_plugin_info = interpreter.get("get_plugin_info").__call__();
            //Map map = (Map) get_plugin_info.getDict().__tojava__(Map.class);
            this.result = result;
            return;
        }
    }catch (Exception e){
        log.error(e.toString());
    }

    result="";
}
 
Example 2
Source Project: hazelcast-jet-demos   Source File: FlightTelemetry.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Sink implementation which forwards the items it receives to the Graphite.
 * Graphite's Pickle Protocol is used for communication between Jet and Graphite.
 *
 * @param host Graphite host
 * @param port Graphite port
 */
private static Sink<KeyedWindowResult> buildGraphiteSink(String host, int port) {
    return sinkBuilder("graphite", instance ->
            new BufferedOutputStream(new Socket(host, port).getOutputStream()))
            .<KeyedWindowResult>receiveFn((bos, entry) -> {
                GraphiteMetric metric = new GraphiteMetric();
                metric.from(entry);

                PyString payload = cPickle.dumps(metric.getAsList(), 2);
                byte[] header = ByteBuffer.allocate(4).putInt(payload.__len__()).array();

                bos.write(header);
                bos.write(payload.toBytes());
            })
            .flushFn(BufferedOutputStream::flush)
            .destroyFn(BufferedOutputStream::close)
            .build();
}
 
Example 3
Source Project: zest-writer   Source File: TestMarkdown.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Test
public void test() {
    String strBefore = "Bonjour `Set<Class<? extends Object>>`";
    String strAfter = "<p>Bonjour <code>Set&lt;Class&lt;? extends Object&gt;&gt;</code></p>";

    pyconsole.exec("from markdown import Markdown");
    pyconsole.exec("from markdown.extensions.zds import ZdsExtension");
    pyconsole.exec("from smileys_definition import smileys");

    pyconsole.set("text", strBefore);
    pyconsole.exec("mk_instance = Markdown(extensions=(ZdsExtension(inline=False, emoticons=smileys, js_support=False, ping_url=None),),safe_mode = 'escape', enable_attributes = False, tab_length = 4, output_format = 'html5', smart_emphasis = True, lazy_ol = True)");
    pyconsole.exec("render = mk_instance.convert(text)");

    PyString render = pyconsole.get("render", PyString.class);
    assertEquals(render.toString(), strAfter);

}
 
Example 4
Source Project: constellation   Source File: AbstractCalculatorUtilities.java    License: Apache License 2.0 5 votes vote down vote up
protected static boolean isTrueValue(PyObject obj) {
    if (nullCheck(obj)) {
        return false;
    }
    if (__builtin__.hasattr(obj, new PyString("__nonzero__"))) {
        return obj.__nonzero__();
    }
    if (__builtin__.hasattr(obj, new PyString("__len__"))) {
        return obj.__len__() != 0;
    }
    return true;
}
 
Example 5
private static void registerJythonSerializers(StreamExecutionEnvironment env) {
	env.registerTypeWithKryoSerializer(PyBoolean.class, PyBooleanSerializer.class);
	env.registerTypeWithKryoSerializer(PyFloat.class, PyFloatSerializer.class);
	env.registerTypeWithKryoSerializer(PyInteger.class, PyIntegerSerializer.class);
	env.registerTypeWithKryoSerializer(PyLong.class, PyLongSerializer.class);

	env.registerTypeWithKryoSerializer(PyString.class, PyStringSerializer.class);
	env.registerTypeWithKryoSerializer(PyUnicode.class, PyObjectSerializer.class);

	env.registerTypeWithKryoSerializer(PyTuple.class, PyObjectSerializer.class);
	env.registerTypeWithKryoSerializer(PyObjectDerived.class, PyObjectSerializer.class);
	env.registerTypeWithKryoSerializer(PyInstance.class, PyObjectSerializer.class);
}
 
Example 6
private static void runScript(String args[], String fn, int idx) {
    String ext = GlobalUtil.getFileExtension(fn);
    System.out.println("Running Jython script...");
    //PySystemState state = Py.getSystemState();
    //Py.getSystemState().setdefaultencoding("utf-8");
    PySystemState state = new PySystemState();
    //state.setdefaultencoding("utf-8");
    if (args.length > idx + 1) {
        for (int i = idx + 1; i < args.length; i++) {
            state.argv.append(new PyString(args[i]));
        }
    }

    PythonInterpreter interp = new PythonInterpreter(null, state);
    String pluginPath = GlobalUtil.getAppPath(FrmMain.class) + File.separator + "plugins";
    List<String> jarfns = GlobalUtil.getFiles(pluginPath, ".jar");
    String path = GlobalUtil.getAppPath(FrmMain.class) + File.separator + "pylib";
    interp.exec("import sys");
    //interp.set("mis", mis);
    interp.exec("sys.path.append('" + path + "')");
    //interp.exec("import mipylib");
    //interp.exec("from mipylib.miscript import *");
    //interp.exec("from meteoinfo.numeric.JNumeric import *");
    for (String jarfn : jarfns) {
        interp.exec("sys.path.append('" + jarfn + "')");
    }
    interp.execfile(fn);
    System.exit(0);
}
 
Example 7
Source Project: phoebus   Source File: JythonSupport.java    License: 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 8
Source Project: zest-writer   Source File: MenuController.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static String markdownToHtml(MdTextController index, String chaine) {
    PythonInterpreter console = index.getPyconsole();
    console.set("text", chaine);
    console.exec("render = mk_instance.convert(text)");
    PyString render = console.get("render", PyString.class);
    return render.toString();
}
 
Example 9
Source Project: zest-writer   Source File: MdTextController.java    License: GNU General Public License v3.0 5 votes vote down vote up
public String markdownToHtml(String chaine) {
    if (pyconsole != null) {
        pyconsole.set("text", chaine);
        pyconsole.exec("render = mk_instance.convert(text)");
        PyString render = pyconsole.get("render", PyString.class);
        return render.toString();
    } else {
        return null;
    }
}
 
Example 10
Source Project: qpid-proton-j   Source File: JythonTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws Exception
{
    String testScript = getJythonTestScript();
    String testRoot = getJythonTestRoot();
    String xmlReportFile = getOptionalXmlReportFilename();
    String ignoreFile = getOptionalIgnoreFile();

    final PythonInterpreter interp = createInterpreterWithArgs(xmlReportFile, ignoreFile);
    PathBuilder pathBuilder = new PathBuilder() {
        @Override
        public PathBuilder append(String path) {
            interp.getSystemState().path.insert(0, new PyString(path));
            return this;
        }
    };
    extendPath(pathBuilder);

    LOGGER.info("About to call Jython test script: '" + testScript
            + "' with '" + testRoot + "' added to Jython path");

    int maxInvocations = Integer.getInteger(TEST_INVOCATIONS_SYSTEM_PROPERTY, 1);
    assertTrue("Number of invocations should be non-negative", maxInvocations >= 0);
    boolean loopForever = maxInvocations == 0;
    if(maxInvocations > 1)
    {
        LOGGER.info("Will invoke Python test " + maxInvocations + " times");
    }
    if(loopForever)
    {
        LOGGER.info("Will repeatedly invoke Python test forever");
    }
    int invocations = 1;
    while(loopForever || invocations++ <= maxInvocations)
    {
        runTestOnce(testScript, interp, invocations);
    }
}
 
Example 11
Source Project: qpid-proton-j   Source File: JythonTest.java    License: Apache License 2.0 5 votes vote down vote up
private PythonInterpreter createInterpreterWithArgs(String xmlReportFile, String ignoreFile)
{
    PySystemState systemState = new PySystemState();

    if (xmlReportFile != null)
    {
        systemState.argv.append(new PyString("--xml"));
        systemState.argv.append(new PyString(xmlReportFile));
    }

    if(ignoreFile == null)
    {
        ignoreFile = System.getProperty(IGNORE_FILE_SYSTEM_PROPERTY);
    }

    if(ignoreFile != null)
    {
        systemState.argv.append(new PyString("-I"));
        systemState.argv.append(new PyString(ignoreFile));
    }

    String testPattern = System.getProperty(TEST_PATTERN_SYSTEM_PROPERTY);
    if(testPattern != null)
    {
        systemState.argv.append(new PyString(testPattern));
    }

    if(Boolean.getBoolean(ALWAYS_COLORIZE_SYSTEM_PROPERTY))
    {
        systemState.argv.append(new PyString("--always-colorize"));
    }

    PythonInterpreter interp = new PythonInterpreter(null, systemState);
    return interp;
}
 
Example 12
Source Project: AndroidRobot   Source File: JythonUtils.java    License: Apache License 2.0 5 votes vote down vote up
private static PyObject convertObject(Object o) {
/* 222 */     if ((o instanceof String))
/* 223 */       return new PyString((String)o);
/* 224 */     if ((o instanceof Double))
/* 225 */       return new PyFloat(((Double)o).doubleValue());
/* 226 */     if ((o instanceof Integer))
/* 227 */       return new PyInteger(((Integer)o).intValue());
/* 228 */     if ((o instanceof Float)) {
/* 229 */       float f = ((Float)o).floatValue();
/* 230 */       return new PyFloat(f);
/*     */     }
/* 232 */     return Py.None;
/*     */   }
 
Example 13
Source Project: AndroidRobot   Source File: JythonUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static PyDictionary convertMapToDict(Map<String, Object> map)
/*     */   {
/* 242 */     Map resultMap = Maps.newHashMap();
/*     */
/* 244 */     for (Entry entry : map.entrySet()) {
/* 245 */       resultMap.put(new PyString((String)entry.getKey()), convertObject(entry.getValue()));
/*     */     }
/*     */
/* 248 */     return new PyDictionary(resultMap);
/*     */   }
 
Example 14
Source Project: sikuli-monkey   Source File: AndroidRobot.java    License: MIT License 5 votes vote down vote up
private void press(String keycodeName, float durationSec) {
    sleep(1);
    if (durationSec == 0) {
        _device.press(new PyObject[] { new PyString(keycodeName), new PyString(MonkeyDevice.DOWN_AND_UP) }, null);
    } else {
        _device.press(new PyObject[] { new PyString(keycodeName), new PyString(MonkeyDevice.DOWN) }, null);
        sleep(durationSec);
        _device.press(new PyObject[] { new PyString(keycodeName), new PyString(MonkeyDevice.UP) }, null);
    }
}
 
Example 15
Source Project: sikuli-monkey   Source File: AndroidScreen.java    License: MIT License 5 votes vote down vote up
public AndroidScreen(String serialNumber) throws AWTException {
    MonkeyDevice device = MonkeyRunner.waitForConnection(new PyObject[] { new PyFloat(15), new PyString(serialNumber) }, null);

    try { // waitForConnection() never returns null, even the connection cannot be created.
        String model = device.getProperty(new PyObject[] {new PyString("build.model")}, null);
        Debug.history("Successfully connect to a device. MODEL: " + model);
    } catch (Throwable e) {
        throw new RuntimeException("Failed to connect to a device (within timeout).", e);
    }
    _robot = new AndroidRobot(device);

    // Region's default constructor doesn't use this screen as the default one.
    Rectangle bounds = getBounds();
    super.init(bounds.x, bounds.y, bounds.width, bounds.height, this);
}
 
Example 16
Source Project: score   Source File: PythonExecutor.java    License: Apache License 2.0 5 votes vote down vote up
protected PythonInterpreter initInterpreter(Set<String> dependencies) {
    logger.info("Creating python interpreter with [" + dependencies.size() + "] dependencies [" + dependencies + "]");
    if(!dependencies.isEmpty()) {
        PySystemState systemState = new PySystemState();
        for (String dependency: dependencies) {
            systemState.path.append(new PyString(dependency));
        }
        return new ThreadSafePythonInterpreter(systemState);
    }
    return GLOBAL_INTERPRETER;
}
 
Example 17
Source Project: nifi   Source File: JythonScriptEngineConfigurator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object init(ScriptEngine engine, String[] modulePaths) throws ScriptException {
    if (engine != null) {
        // Need to import the module path inside the engine, in order to pick up
        // other Python/Jython modules.
        engine.eval("import sys");
        if (modulePaths != null) {
            for (String modulePath : modulePaths) {
                engine.eval("sys.path.append(" + PyString.encode_UnicodeEscape(modulePath, true) + ")");
            }
        }
    }
    return null;
}
 
Example 18
Source Project: elasticsearch-inout-plugin   Source File: DocTest.java    License: Apache License 2.0 5 votes vote down vote up
private void execFile(String filePath, String... arguments) {
    interp.cleanup();
    interp.set("__file__", filePath);
    sys.argv = new PyList(new PyString[]{new PyString(filePath)});
    sys.argv.extend(new PyArray(PyString.class, arguments));
    interp.execfile(filePath);
}
 
Example 19
Source Project: constellation   Source File: AttributeCalculatorPlugin.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void edit(final GraphWriteMethods graph, final PluginInteraction interaction, final PluginParameters parameters) throws InterruptedException, PluginException {
    final ScriptEngineManager manager = new ScriptEngineManager();
    final ScriptEngine engine = manager.getEngineByMimeType(language);
    final Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
    final CalculatorContextManager calculatorContext = new CalculatorContextManager(graph, elementType);

    final Map<Integer, Object> editedAttributeValues = new HashMap<>();

    preprocessScriptAndBindObjects(graph, bindings, calculatorContext);
    LOGGER.log(Level.INFO, "processedScript::{0}", script);
    int editAttributeId = graph.getAttribute(elementType, editAttribute);
    if (editAttributeId == Graph.NOT_FOUND) {
        editAttributeId = graph.addAttribute(elementType, editAttributeType, editAttribute, "", null, null);
    }

    int selectedAttr = selectedOnly ? graph.getAttribute(elementType, "selected") : Graph.NOT_FOUND;

    try {

        // Import any desired modules before trying to do anything with the script.
        importModules(engine);

        CompiledScript compiledScript;
        CompiledScript functionWrapperScript = null;
        final CompiledScript testExpressionScript = ((Compilable) engine).compile("ast.parse(" + __builtin__.repr(new PyString(script)) + ", mode='eval')"); // shiiii, such a ridic line of code
        try {
            testExpressionScript.eval();
            compiledScript = ((Compilable) engine).compile(script);
        } catch (ScriptException e) {
            final String functionWrappedScript = "def __script__():\n " + script.replace("\n", "\n ") + "\n";
            LOGGER.log(Level.INFO, "processedScript::{0}", functionWrappedScript);
            compiledScript = ((Compilable) engine).compile(functionWrappedScript);
            functionWrapperScript = ((Compilable) engine).compile("__script__()");
        }

        final int elementCount = elementType == GraphElementType.VERTEX ? graph.getVertexCount() : graph.getTransactionCount();

        // Compute the values for the desired attribute
        for (int i = 0; i < elementCount; i++) {
            final int elementId = elementType == GraphElementType.VERTEX ? graph.getVertex(i) : graph.getTransaction(i);
            if (selectedAttr == Graph.NOT_FOUND || graph.getBooleanValue(selectedAttr, elementId)) {
                calculatorContext.enter(elementId);
                Object result = compiledScript.eval();
                if (functionWrapperScript != null) {
                    result = functionWrapperScript.eval();
                }
                if (result == AbstractCalculatorValue.getTheObliterator()) {
                    result = null;
                }
                editedAttributeValues.put(elementId, result);
                calculatorContext.exit();
            }
        }

        // Edit the actual attribute values for the desired attribute
        for (final Map.Entry<Integer, Object> entry : editedAttributeValues.entrySet()) {
            graph.setObjectValue(editAttributeId, entry.getKey(), entry.getValue());
            if (!completeWithSchema) {
                // do nothing
            } else if (elementType == GraphElementType.VERTEX) {
                if (graph.getSchema() != null) {
                    graph.getSchema().completeVertex(graph, entry.getKey());
                }
            } else {
                if (graph.getSchema() != null) {
                    graph.getSchema().completeTransaction(graph, entry.getKey());
                }
            }
        }

    } catch (ScriptException ex) {
        throw new PluginException(PluginNotificationLevel.ERROR, "Attribute Calculator Error: " + ex.getMessage());
    }
}
 
Example 20
Source Project: Flink-CEPplus   Source File: PyStringSerializer.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void write(Kryo kryo, Output output, PyString object) {
	output.writeString(object.asString());
}
 
Example 21
Source Project: Flink-CEPplus   Source File: PyStringSerializer.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public PyString read(Kryo kryo, Input input, Class<PyString> type) {
	return new PyString(input.readString());
}
 
Example 22
Source Project: hazelcast-jet-demos   Source File: FlightTelemetry.java    License: Apache License 2.0 4 votes vote down vote up
private void fromAirCraftEntry(KeyedWindowResult<Long, Aircraft> aircraftEntry) {
    Aircraft aircraft = aircraftEntry.getValue();
    metricName = new PyString(replaceWhiteSpace(aircraft.getAirport()) + "." + aircraft.getVerticalDirection());
    timestamp = new PyInteger(getEpochSecond(aircraft.getPosTime()));
    metricValue = new PyFloat(1);
}
 
Example 23
Source Project: hazelcast-jet-demos   Source File: FlightTelemetry.java    License: Apache License 2.0 4 votes vote down vote up
private void fromMaxNoiseEntry(KeyedWindowResult<String, Integer> entry) {
    metricName = new PyString(replaceWhiteSpace(entry.getKey()));
    timestamp = new PyInteger(getEpochSecond(entry.end()));
    metricValue = new PyFloat(entry.getValue());
}
 
Example 24
Source Project: hazelcast-jet-demos   Source File: FlightTelemetry.java    License: Apache License 2.0 4 votes vote down vote up
private void fromTotalC02Entry(KeyedWindowResult<String, Double> entry) {
    metricName = new PyString(replaceWhiteSpace(entry.getKey()));
    timestamp = new PyInteger(getEpochSecond(entry.end()));
    metricValue = new PyFloat(entry.getValue());
}
 
Example 25
Source Project: phoebus   Source File: JythonSupport.java    License: Eclipse Public License 1.0 4 votes vote down vote up
/** Load a Jython class
 *
 *  @param type Type of the Java object to return
 *  @param class_name Name of the Jython class,
 *                    must be in package (file) using lower case of class name
 *  @param args Arguments to pass to constructor
 *  @return Java object for instance of Jython class
 *  @throws Exception on error
 */
@SuppressWarnings("unchecked")
public <T> T loadClass(final Class<T> type, final String class_name, final String... args) throws Exception
{
    // Get package name
    final String pack_name = class_name.toLowerCase();
    logger.log(Level.FINE, "Loading Jython class {0} from {1}",
               new Object[] { class_name, pack_name });

    try
    {
        // Import class into Jython
        // Debug: Print the path that's actually used
        // final String statement = "import sys\nprint sys.path\nfrom " + pack_name +  " import " + class_name;
        final String statement = "from " + pack_name +  " import " + class_name;
        interpreter.exec(statement);
    }
    catch (PyException ex)
    {
        logger.log(Level.WARNING, "Error loading Jython class {0} from {1}",
            new Object[] { class_name, pack_name });
        logger.log(Level.WARNING, "Jython sys.path:\n * {0}",
                   interpreter.getSystemState()
                              .path
                              .stream()
                              .collect(Collectors.joining("\n * ")));

        throw new Exception("Error loading Jython class " + class_name + ":" + getExceptionMessage(ex), ex);
    }
    // Create Java reference
    final PyObject py_class = interpreter.get(class_name);
    final PyObject py_object;
    if (args.length <= 0)
        py_object = py_class.__call__();
    else
    {
        final PyObject[] py_args = new PyObject[args.length];
        for (int i=0; i<py_args.length; ++i)
            py_args[i] = new PyString(args[i]);
        py_object = py_class.__call__(py_args);
    }
    final T java_ref = (T) py_object.__tojava__(type);
    return java_ref;
}
 
Example 26
Source Project: sikuli-monkey   Source File: AndroidRobot.java    License: MIT License 4 votes vote down vote up
public String getModel() {
    if (_model != null) return _model;

    _model = _device.getProperty(new PyObject[] { new PyString("build.model") }, null);
    return _model;
}
 
Example 27
Source Project: sikuli-monkey   Source File: AndroidRobot.java    License: MIT License 4 votes vote down vote up
public void tap(int x, int y) {
    _device.touch(new PyObject[] { new PyInteger(x), new PyInteger(y), new PyString("DOWN_AND_UP")}, null);
}
 
Example 28
public static void addPathToPySystemState(PySystemState sys, String path) {
	try {
		sys.path.append(new PyString(path));
	} catch (Exception e){}
}