Introduction of Jython, a docking tool between python and java

quick get start

Next we use jython to call the classes in the custom jar package.

Edit java file: Beach.java

public class Beach {

    private String name;
    private String city;

    public Beach(String name, String city){
        this.name = name;
        this.city = city;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

}

Compile to jar package:

# javac Beach.java 
# echo Main-Class: Beach >manifest.txt
# jar cvfm Craps.jar manifest.txt *.class
 List added
 Adding: beach.class (input = 795) (output = 430) (45% compressed)
Adding: point.class (input = 708) (output = 445) (37% compressed)

Add Craps.jar to CLASSPATH, modify / etc/profile, and CLASSPATH

export CLASSPATH=.:$JAVA_HOME/jre/lib/rt.jar:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar:/usr/local/jython/Craps.jar

Use. / etc/profile to import variables. Then use jython to call java code.

# ./jython 
Jython 2.7.0 (default:9987c746f838, Apr 29 2015, 02:25:11) 
[Java HotSpot(TM) 64-Bit Server VM (Oracle Corporation)] on java1.7.0_79
Type "help", "copyright", "credits" or "license" for more information.
>>> import Beach
>>> beach = Beach("Cocoa Beach","Cocoa Beach")
>>> beach.getName()
u'Cocoa Beach'
>>> print beach.getName()
Cocoa Beach
>>>

Basics

Linux Installation:

# java -jar jython-installer-2.7.0.jar 
# ./jython 
Jython 2.7.0 (default:9987c746f838, Apr 29 2015, 02:25:11) 
[Java HotSpot(TM) 64-Bit Server VM (Oracle Corporation)] on java1.7.0_79
Type "help", "copyright", "credits" or "license" for more information.
>>>

windows installation: double click jython-installer-2.7.0.jar and execute jython.exe

Variable definition:

java
int x = 0;
jython: 
x = 0
x = 'Hello Jython'

Is of dynamic type.

Reserved words:

and     assert     break     class     continue
def     del     elif     else     except
exec     finally     for     from     global
or     pass     print     raise     return
try     while     with     yield

The encoding structure uses indentation.

The function name can also be used as an argument to the function.

Statement key:

if-elif-else     for
while     continue
break     try-except-finally
assert     def
print     del
raise     import

File name and class name can be imported directly.

This part of reference:

http://www.jython.org/jythonbook/en/1.0/JythonAndJavaIntegration.html

http://www.skylit.com/javamethods/faqs/createjar.html

reference material:

http://www.jython.org/jythonbook/en/1.0/

Modules and packages

View namespace

>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']

Jython's import does not have to be in the header as java does. The right name takes precedence in importing java, and the left name takes precedence in python. Module lookup path:

>>> import sys
>>> sys.path
['', '/usr/local/jython2.7.0/Lib', '__classpath__', '__pyclasspath__/', '/usr/local/jython2.7.0/Lib/site-packages']

>>> import sys
>>> sys.path
['', '/usr/local/jython2.7.0/Lib', '__classpath__', '__pyclasspath__/', '/usr/local/jython2.7.0/Lib/site-packages']

>>> import sys
>>> sys.path.append("/home/andrew/code/java/mysql-connector-java-5.1.39/mysql-connector-java-5.1.39-bin.jar")
>>> import com.mysql
*sys-package-mgr*: can't write cache file for '/home/andrew/code/java/mysql-connector-java-5.1.39/mysql-connector-java-5.1.39-bin.jar'
*sys-package-mgr*: can't write index file
>>> dir(com.mysql)
['__name__', 'fabric', 'jdbc']

>>> import java.util.zip
>>> dir(java.util.zip)
['Adler32', 'CRC32', 'CheckedInputStream', 'CheckedOutputStream', 'Checksum', 'DataFormatException', 'Deflater', 'DeflaterInputStream', 'DeflaterOutputStream', 'GZIPInputStream', 'GZIPOutputStream', 'Inflater', 'InflaterInputStream', 'InflaterOutputStream', 'ZipEntry', 'ZipError', 'ZipException', 'ZipFile', 'ZipInputStream', 'ZipOutputStream', '__name__']
>>> dir(java.util.zip.ZipInputStream)
['__class__', '__copy__', '__deepcopy__', '__delattr__', '__doc__', '__ensure_finalizer__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__subclasshook__', '__unicode__', 'available', 'class', 'close', 'closeEntry', 'equals', 'getClass', 'getNextEntry', 'hashCode', 'mark', 'markSupported', 'nextEntry', 'notify', 'notifyAll', 'read', 'reset', 'skip', 'toString', 'wait']

Jython's method to find Jar and class:

python.packages.paths
python.packages.directories

java.class.path
java.ext.dirs

python.cachedir.skip

pycimport converts python bytecode to Java bytecode. Jython import java package may have multiple package merges.

>>> import sys
>>> sys.path_hooks
[<type 'org.python.core.JavaImporter'>, <type 'zipimport.zipimporter'>,
<type 'ClasspathPyImporter'>]

import pycimport

data type

Jython specific collection is mostly used to pass data to java.

# Import and use a Java ArrayList

>>> import java.util.ArrayList as ArrayList

>>> arr = ArrayList()

#  Add method will add an element to the list and return a boolean to signify
successsful addition

>>> arr.add(1)

True

>>> arr.add(2)

True

>>> print arr

[1, 2]

The older Jarray is not recommended, but you can create an empty array:

Type:


Character    Java Equivalent
z    boolean
b    byte
c    char
d    Double
f    Float
h    Short
i    Int
l    Long

>>> my_seq = (1,2,3,4,5)

>>> from jarray import array

>>> array(my_seq,'i')

array('i', [1, 2, 3, 4, 5])

>>> myStr = "Hello Jython"

>>> array(myStr,'c')

array('c', 'Hello Jython')

>>> arr = zeros(10,'z')

>>> arr

array('z', [False, False, False, False, False, False, False, False, False, False])

>>> arr2 = zeros(6, 'i')

>>> arr2

array('i', [0, 0, 0, 0, 0, 0])

Finding prime number

`>>> ``nums = range(2, 50) `
`>>> ``for i in range(2, 8): `
`... ``    nums = filter(lambda x: x == i or x % i, nums)`
`... `
`>>> ``print nums`

Read input:

<pre># Obtain a value from the command line and store it into a variable
>>> import sys
>>> fav_team = sys.stdin.readline()
Cubs
>>> sys.stdout.write("My favorite team is: %s" % fav_team)
My favorite team is: Cubs</pre>

function

Cooperation:


**def** search_file(filename):
    **print** 'Searching file *%s*' % (filename)
    my_file = open(filename, 'r')
    file_content = my_file.read()
    my_file.close()
    **while** True:
        search_text = (**yield**)
        search_result = file_content.count(search_text)
        **print** 'Number of matches: *%d*' % (search_result)</pre>

Jython script programming foundation

os.chdir does not change the jvm's boot directory.

>>> import os
>>> os.getcwd()
'/Users/frank/Desktop/frank/hg/jythonbook~jython-book/src/chapter8'
>>> from java.io import File
>>> f = File(".")
>>> for x in f.list():
... print x
...
args.py
search.py
>>> os.chdir("/Users/frank")
>>> os.getcwd()
'/Users/frank'
>>> os.listdir(".")
['Desktop', 'Documents', 'Downloads', 'Dropbox', 'Library', 'Movies', 'Music', 'Pictures', 'Public', 'Sites']
>>> g = File(".")
>>> for x in g.list():
...     print x
...
args.py
search.py

//Compile code
```#!python
#!/usr/local/jython2.7.0/bin/jython

from javax.tools import (ForwardingJavaFileManager, ToolProvider, DiagnosticCollector,)
names = ["/home/andrew/code/python/jythonbook/src/chapter8/HelloWorld.java"]
compiler = ToolProvider.getSystemJavaCompiler()
diagnostics = DiagnosticCollector()
manager = compiler.getStandardFileManager(diagnostics, None, None)
units = manager.getJavaFileObjectsFromStrings(names)
comp_task = compiler.getTask(None, manager, diagnostics, None, None, units)
success = comp_task.call()
manager.close()

<pre>**import** **os**
**import** **sys**
**import** **glob**

**from** **javax.tools** **import** (forwardingjavafilemanager, toolprovider,
         diagnosticcollector,)

tasks = {}

**def** task(func):
    tasks[func.func_name] = func

**@task**
**def** clean():
    files = glob.glob("\*.class")
    **for** file **in** files:
        os.unlink(file)

**@task**
**def** compile():
    files = glob.glob("\*.java")
    _log("compiling *%s*" % files)
    **if** **not** _compile(files):
        quit()
    _log("compiled")

**def** _log(message):
    **if** options.verbose:
        **print** message

**def** _compile(names):
    compiler = toolprovider.getsystemjavacompiler()
    diagnostics = diagnosticcollector()
    manager = compiler.getstandardfilemanager(diagnostics, none, none)
    units = manager.getjavafileobjectsfromstrings(names)
    comp_task = compiler.gettask(none, manager, diagnostics, none, none, units)
    success = comp_task.call()
    manager.close()
    **return** success

**if** __name__ == '__main__':
    **from** **optparse** **import** optionparser
    parser = optionparser()
    parser.add_option("-q", "--quiet",
        action="store_false", dest="verbose", default=true,
        help="don't print out task messages.")
    parser.add_option("-p", "--projecthelp",
        action="store_true", dest="projecthelp",
        help="print out list of tasks.")
    (options, args) = parser.parse_args()

    **if** options.projecthelp:
        **for** task **in** tasks:
            **print** task
        sys.exit(0)

    **if** len(args) < 1:
        **print** "usage: jython builder.py [options] task"
        sys.exit(1)

    **try**:
        current = tasks[args[0]]
    **except** KeyError:
        **print** "task *%s* not defined." % args[0]
        sys.exit(1)
    current()</pre>

<pre>public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World");
    }
}</pre>

<pre>[frank@pacman chapter8]$ jython builder.py --help
Usage: builder.py [options]

Options:
    -h, --help show this help message and exit
    -q, --quiet Don't print out task messages.
    -p, --projecthelp Print out list of tasks.
[frank@pacman chapter8]$ jython builder.py --projecthelp
compile
clean
[frank@pacman chapter8]$ jython builder.py compile
compiling ['HelloWorld.java']
compiled
[frank@pacman chapter8]$ ls
HelloWorld.java HelloWorld.class builder.py
[frank@pacman chapter8]$ jython builder.py clean
[frank@pacman chapter8]$ ls
HelloWorld.java builder.py
[frank@pacman chapter8]$ jython builder.py --quiet compile
[frank@pacman chapter8]$ ls
HelloWorld.class HelloWorld.java builder.py
[frank@pacman chapter8]$</pre>

Keywords: Java Python MySQL Oracle

Added by stlewis on Tue, 17 Dec 2019 23:28:24 +0200