صفحه 1:
Otxtoy Pywoo ood dav
dow Pyikoo ced devo coo عدصفى صصص
and work together
PuvP wa COO (heer GO COOO, Brwtardrerv)
Ocnbews Gchreber <Duackeus. Gchreber @drche>
Ceram Derveper Orcter (DLR), Ovkxpe, Cero
http: //www.dlr.de/sc
صفحه 2:
صفحه 3:
rad Orrsiva oP tis Glider > 2
من سره 0۵ vs
Kitz:/hr.tctepDOnwe
صفحه 4:
&, Frat eed Raub
صفحه 5:
9000 ew pers ures
C0 resewch testes od
B09 sites.
OP fives tt Brussets,
arts ل
صفحه 6:
|
i
>
+
یت
Cory 7
>
بت
&, Frat eed Raub
صفحه 7:
ee ae ما .چ
Ordtog Ppa ond dao?
4s it al ubvut
صفحه 8:
Orxdtog Ppa od daa?
Outline
ovessieg Pyiwe Prow مرول
7 رل
7 100
ماب مس مرول موه
۶ 7
ICO 7
صفحه 9:
“re
FZ Gord perPorannce
ما0 لس Oolevior (card wo OL)
ea ما رو بط
تست تا مت سا مق Por ریق
qeueraiva, sevuriy, ۳) ,سر
wa
ky People ore Osta dev?
7 Olde) used to روج dPPeredt opphoaicg docaices
7 eer ieteess, لو طسو
7 وم تام وله روم مس للم
oe a
or wer tierPares
رل( oP goed dorama Pox
سمل تاه مسرت لو
7 لو ما لو بو( aVa
FZ Cobre, VetPeas, ‘hich! KDE, ...
ot und Route eV
7ت
صفحه 10:
ee ae ما .چ
لب
People ure Osiag Ppihow? بواط)
Pyhwa ta Reorack ond eke
7 Gerctets orl poxiorers datum te arte aera but net ok fete
problem
TZ AP bey frase te tame cand, tenet be a ey ce pombe
ساره سس
جص جا برب جد وميا جا صم و0 2
ee brace une) = (
FJ ةا revit develop
( = chert سمسجاسط tee)
7 تحص ret cetera
&, a Rts
صفحه 11:
ee ae ما .چ
Python has the cleanest,
most-scientist- or engineer
friendly syntax and semantics.
“Pal P. Dubois
صفحه 12:
Obkvy Opxtoy dave oad Ppa?
Cubedded soriptiog cod wore...
7 Oxey woture ava اون ced Prosmeworks exist
72 bee oP axewercid od Opeo Source svPware systews ond tbrortes
F Cor emnope, The Cripse Oversee, و وکسم(
۳ Dorktbus sysiews, ..
J Onn er xe
7 Odd ewbedded (Python) sori to lava opphcctioces
F Ove مرول throes Brow Python ode
سسب عد
0
صفحه 13:
Obkvy Oday dave ond Ppa?
موه مرول و یی مطایرظ) و موجه[
7 Cxistien) code or tbrores ext ether Por tava or Pyke oly
7 CPPort te restore ed the Pooriocdites oud be very hob
7 Pike tbrary te very wel tested, tf ozukd be oo poor ef Port و و a
باس و اما اون
72 وك موم 50595
72 het use oo existioy brary Prow the “viker” brocpucte
J Copevidy, we Pyboa code (or OlPorirad DEPTEOER onde wits
(ykwea wroppers) Pro eva
Fe harder tp wrap O codes ta hava tha it Phos (see OT pen)
&, Frat eed Raub
صفحه 14:
صفحه 15:
Cxavple
7
صفحه 16:
Ose Ouses Por Pytwa Oorptay (1)
وه لصو ی بو موم سا باه له سوق
ای ری تاه or او و وچ شوم 7
مود
اه مور (ه مس
72 Saws cuses, this is coled “wane” وا له ملس
هه جی مق
ی واه ی رل موی لمطللی لس Cor exnope, 7
this reqires scripts which use he hat BO throes (BOP, Gorn, or ,مرول و
Gor)
عامط برصيحا “tegration oP adddtiond
موه سص جب لجه Aeepertcat cod widely used Por toteqraica 7
سا موس ول با مه فلت له لصو وه موه موی Ged 77
&, ti mae
صفحه 17:
Ose Owes Por Pyiwa Goriptay (C)
(terwive expertoeruiion ued debuasay oF he dave progr
7 Oca be eusiy door wits oa pwobedded موه tnierpreter
7 lows eed were ocd spPivare devebpers to مولع رای امه بط
ول مور ror
Oreutey cuiowoted tests Por quoly یت
7 مد رل سوه و لو of the dave proarae os 3 (Pyikos soript
سل (
اوه ال با رای مه بط 7
م۱
ot und Route eV
7ت
صفحه 18:
Gxanple: Ordes wik Pyiwa ToterPaces
منت Gicrutatica GoPiane it OF+ or Porirad
۳ DS cz
ee
77 Cheoples Por hrgk-dePratica OP O-Grlver wi Pyikoa toterPaces
7 OR POO-One (http: //www.dlr.de/as)
7 OVER vkB-Ore (http: //elsa.onera. fr)
7 موه vio dave workPlow syste wil the .موه مساو(
&, fora ond
صفحه 19:
صفحه 20:
ee ae ما .چ
Prow dao مسا یموس
Ose vers
7 Whe upphcotica should hove ewbedded soriptiag Pucctiocraliy.
7 Che uppicaticn shoud use oo exterod code vorites ta (Pytsoa.
J Phe oppletiva shod wer oo exterad code written ia P hoa or rher keennnes
wk w ©, OF+, Pore.
‘Tov
7 رل
7 JERE
صفحه 21:
رل
۱
سول و سم
FJ Phen onde nce ta he da OO
7 Website: http://www. jython.org
7 Latest versiva: dia © .6©
7 ۳ tetas & questa, catch
ما و
7 مسا م۳
مها ه سا اه له 9
ی
صفحه 22:
رل
hava code 2( عاممم) عون
7 Creve Ppa code
import org.python.util.PythonInterpreter ;
import org.python.core.*;
iclass TestClass {
| public static void main(String[] args) {
try {
org.python.util.PythonInterpreter python =
new org.python.util.PythonInterpreter (); /
python.execfile("python_script.py");
} catch (Exception e) {
System.out.println(“Some error!");
صفحه 23:
رل
له ما Code Exavple O:
FJ Ose مسه
| from javax.swing import *
frame JFrame("Hello Jython")
label JLabel("Hello Jython!", JLabel. CENTER)
frame.add(label)
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE)
frame.setSize(200, 100)
ae oion (
صفحه 24:
ee ae ما .چ
1
dave Goobedded Ppikoa
FZ Cccbeds OP pho )مرول مس
AeterPace (U1) ia kev
7 yikes cede roc tt OP yhoo
7 Debsite:
http://jepp.sourceforge.net/
Finn eee ee
صفحه 25:
ee ae ما .چ
1
Code Exacrple
J Creve (“evckrte”) سس مره
‘Jep jep new Jep(false, SCRIPT_PATH, cl);
jep.eval("print ‘hello'"
j ‘Lose();
Jep je new Jep(false, SCRIPT_PATH, cl);
jep.runScript(SCRIPT_PATH + file);
صفحه 26:
ee ae ما .چ
@ovesstay dave Prow yoo
Ose vers
7 Che oppicaiva shoud wer oo اوه ول ام
7 Che upphcaticn shoud وا ول و ی
Doe
7 Wye
7 100
صفحه 27:
1 0
رل
موجه have to yhoo
<< یی oa crue level of bok (shart & (Pasa)
موجه امه لعبن)
FZ Grote ahaa Orid Docker
7 Debsite:
http://jpype.sourceforge.net
صفحه 28:
UPype
Onde @xexvpe: (1)
from jpype import *
# Start JVM
startJVM (path to jvm.dll, “-ea")
# Print "Hello World"
java. lang.System.out.println("Hello World")
# Shutdown JVM
: shutdownJVM()
صفحه 29:
UPype
Onde سا )6(
import jpype
# Start JVM
jpype.startJVM(path to jvm.dil, "-ea")
# Create reference to java package
javaPackage = jpype.JPackage("JavaPackageName
# Create reference to java class
javaClass = javaPackage. JavaClassName
# Create instance of java class
java0bject = javaClass()
# Call java methods
| JavaObject. JavaMethodName()
# Shutdown JVM
jpype.shutdownJVM()
صفحه 30:
1 0
00ل
@pbuceve's Code Bevercior
J O++ code cecerctor Por oli مرول
Brow O++/(Pykoo
FJ O+ object ter Pare Por wrapper 3
share thro vir KOA
F Crees cree OP yhoo
میس
و
ohare ond Orns, requires OF+
waver
7 Website:
http: //Lucene.apache.org
/pylucene/jcc
7 Pato رل
&, Frat eed Raub
صفحه 31:
ee ae ما .چ
00ل
عاممهء 2 Onde
7 Requirsvedt: )00( ومقدصامهه
import jec
# Start JVM
| jec.initVM(maxhea|
“2000m’
صفحه 32:
ال ۹
WOO Onde Gaxnople
Osicgy PW uced: Gearck buceur Tedder
7 Grarck Por Query" ti ی توس
rom lucene import QueryParser, IndexSearcher, StandardAnalyzer,
FSDirectory, Hit, VERSION, initVM, CLASSPATH
nitVM (CLASSPATH)
irectory = FSDirectory.getDirectory(“index”, False)
earcher = IndexSearcher(directory)
StandardAnalyzer ()
raw_input(“Query:")
‘query = QueryParser("contents", analyzer) .parse(command)
hits = searcher.search(query)
for hit in hits:
| doc = Hit.cast_(hit).getDocument()
print ‘path:', doc.get("path"), ‘name:', doc.get("name")
earcher.close()
۷ مایت اب ,&
صفحه 33:
ee ae ما .چ
Ihter-Provess Orwwnicaion
processes سل مها امه ملع (1۳0) موم موی و
امه و توا لت تج وت بت بو نع و
ZF Dyed (PO teckcines oe
revo proche vb (RPO) 7
wesenp _ 7
BPs ae مس سس ۳ 7
F Obert Request Broker (ORO) or
ام لا پوس مرس Z Oeb
7 0 drawback 5 the ceed Por سوه رح و وه طسو ,موه لمطللی Por
revisiraice ced locaicg oP recente objects
72 Dervieg Gervice Por CORBO
Z Oriversd Desorption, Oiscovery od Iterctios (DOO) Por Doty
Genices
&, Frat eed Raub
صفحه 34:
NG
Obert Request Orvker (OR®s)
CORBB
صفحه 35:
7 ۳ Oyo topleweutaiod trot works wil OPyikoa od dyke.
7 is alight wert CORO له قفوم tateroperable wit the stontard dav
ORG.
7 Whe developed of Poorb kos ected.
#6
)59 000 و لت O++ cad Pyékoo thot coc be used Prow OP phon.
The Pyke OR® (car OROpy) wee the OF+ teoplerecttion oF rac ORO,
per ORO te اه او لاب لوط رامش
Oebsie: http: //omniorb.sourceforge.net
NNN AN
&, Frat eed Raub
صفحه 36:
ee ae ما .چ
6 0060۵08
هه
DePretica Lorene (DL) مخت نا Dork! toterPare معا
‘module HelloWorld {
const string Message = "Hello CORBA World!"
interface Hello {
string hello_world();
1
صفحه 37:
ee ae ما .چ
0۵00008 Exavpe
@ytoa Gerver (Poort): ٩۱ماه ومسن جه" خا
import sys
# Fnorb modules.
from Fnorb.orb import BOA, CORBA
# Stubs and skeletons generated by ۰
import HelloWorld, HelloWorld_skel
class HelloWorldServer (HelloWorld_skel.Hello_skel)
1 ۰۲ 1016067121100 0۴ 6 ‘Hello' interface. ۳
def hello_world(self):
print HelloWorld.Message
return HelloWorld.Message
صفحه 38:
سس 006060
متا 2 :(ا<) چسه ما۳
lef main(argv)
# Initialise ORB and BOA
orb = CORBA.ORB_init(argv, CORBA.ORB_ID)
boa = BOA.BOA_init(argv, BOA.BOA_ID)
# Create object reference
obj = boa.create('fred', HelloWorldServer._FNORB_ID)
# Create an instance of the implementation class.
impl = HelloWorldServer()
# Activate the implementation
boa.obj_is_ready(obj, impl)
# Write the stringified object reference to a file
open('Server.ref', ‘w').write(orb.object_to_string(obj)) :
boa._fnorb_mainloop() # Start the event loop :
return 0
۷ مایت اب ,&
صفحه 39:
0۵06006 Cxacpe
devo Oliect
public class Client {
public static void main ( String args[] ) {
java.util.Properties props = System.getProperties();
try {
org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args,props)
org.omg.CORBA.Object obj = null;
java.io.BufferedReader in = new java.io.BufferedReader(
new java.io.FileReader(“Server.ref"));
String ref = in.readLine();
obj = orb.string_to_object(ref);
Hello hello = HelloHelper.narrow(obj);
hello.hello_world();
orb.destroy();
} catch (Exception e) { e.printStackTrace(); }
صفحه 40:
صفحه 41:
ee ae ما .چ
Oeb Services Por Pyar
Tokra GOBP ‘kkrwretee (LO)
FZ Por يتويب ان عمط COP tok oP cowekdercble qudy te he Loker
COP ‘kPresirwrre (LN),
&, tt nd Rar ee
صفحه 42:
Ober Qewwrte Object bibrates
Rewote Obievis (Pyrv) م۳
Oyrv tb sive to )مه اس( سب( حرط
٩۱ staple, very porble, oad works wil Whoa.
rege ts bua Derotay Gervice Por locates زان عم
رامش و ممظ) developed with سوه ولو releases.
لد لا لا لا
Grople ما 1 to Revie Obevts (SP1RO)
77 GPIRO teplew rcs oa OR® ced ts developed aso bridge betwee OP yhoo
رل لو
7 The developed kos rode.
ot und Route eV
&,
صفحه 43:
رل 2#
اوه ص هجو لت مات مضه و و با
صفحه 44:
Questions?
Mixing Python and Java
How Python and Java can communicate
and work together
EuroPython 2009 (June 30th 2009, Birmingham)
Andreas Schreiber <Andreas.Schreiber@dlr.de>
German Aerospace Center (DLR), Cologne, Germany
http://www.dlr.de/sc
Folie 1
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
Follow this presentation…
Live!
PowerPoint
to Twitter!
twitter.com/python_demo
Folie 2
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
Final Version of this Slides is
available on SlideShare
http://tr.im/ep09java
Folie 3
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
DLR
German Aerospace Center
Research Institution
Space Agency
Project Management Agency
Folie 4
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
Locations and employees
6000 employees across
29 research institutes and
facilities at
13 sites.
Hamburg
Bremen-
Trauen
Neustrelitz
Berlin-
Braunschweig
Goettingen
Offices in Brussels,
Paris and Washington.
Koeln
Bonn
Lampoldshausen
Stuttgart
Weilheim
Oberpfaffenhofen
Folie 5
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
Research Areas
Aeronautics
Space
Transport
Energy
Space Agency
Project Management Agency
Folie 6
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
Mixing Python and Java?
Is it all about
Jython
?
Folie 7
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
Mixing Python and Java?
Outline
Accessing Python from Java
Jython
JEPP
Accessing Java from Python
JPype
JCC
Inter-process communication
CORBA
SOAP
Other remote object libraries
Folie 8
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
Java
Why People are Using Java?
Widely used in many different application domains
industry/business, research, academia
Available on many different platforms
Good performance
good Garbage Collector (and no GIL)
Many, many libraries
E.g., for data base access, XML
processing, PDF generation, security,
or user interfaces
Availability of good documentation for
all aspects of Java programming
Very good development tools
Eclipse, NetBeans, IntelliJ IDEA, …
Folie 9
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
Python
Why People are Using Python?
Python in Research and Industry
Scientists and engineers don’t want to write software but just solve their
problems
If they have to write code, it must be as easy as possible
Reasons for Python?
“I want to design
planes,
not software!”
Very easy to learn and easy to use
( = steep learning curve)
Allows rapid development
( = short development time)
Inherent great maintainability
Folie 10
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
“
Python has the cleanest,
most-scientist- or engineer
friendly syntax and semantics.
-Paul F. Dubois
Paul F. Dubois. Ten good practices in scientific programming. Comp. In Sci. Eng., Jan/Feb 1999, pp.7-11
Folie 11
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
Why Mixing Java and Python?
Embedded scripting and more…
Many mature Java applications and frameworks exists
Lots of commercial and Open Source software systems and libraries
For example, The Eclipse Universe, Apache-Software, PortalFrameworks, Workflows systems, …
Common use cases
Add embedded (Python) scripting to Java applications
Use Java libraries from Python code
Folie 12
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
Why Mixing Java and Python?
Integration of Python code into Java applications…
Existing code or libraries exist either for Java or Python only
Effort to re-implement the functionalities could be very high
If the library is very well tested, it could be an enormous effort to reach a
comparable level of quality
Common use cases
Just use an existing library from the “other” language
Especially, use Python code (or C/Fortran/WHATEVER code with
Python wrappers) from Java
Its harder to wrap C codes in Java than in Python (see CTypes)
Folie 13
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
Example
QF-Test – Automated GUI Testing
Folie 14
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
Example
TENT – Software Integration and Workflow Management
Folie 15
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
Use Cases for Python Scripting (1)
Steering and controlling the program by user defined scripts
Applications are complex parameter variations or steering multidisciplinary coupled
simulations
Automation of repeating tasks
In most cases, this is called “macro” recording and replaying
Extending user interfaces
For example, with additional customized dialogs and other extensions
In Java, this requires scripts which use the Java GUI libraries (AWT, Swing, or
SWT)
Integration of additional legacy tools
Important and widely used for integration and workflow systems
End users can integrate external codes without changing the Java program itself
Folie 16
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
Use Cases for Python Scripting (2)
Interactive experimentation and debugging of the Java program
Can be easily done with an embedded interactive interpreter
Allows end users and software developers to debug and analyze the Java
program during runtime
Creating automated tests for quality assurance
Recording user actions during runtime of the Java program as a Python script
(“Journaling")
Editing and generalizing the recorded script
Replaying the script manually or automatically
Folie 17
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
Example: Codes with Python Interfaces
Numerical Simulation Software in C++ or Fortran
X-31
Eurofighter
Examples for high-definition CFD-Solver with Python interfaces
DLR TAU-Code (http://www.dlr.de/as)
ONERA elsA-Code (http://elsa.onera.fr)
Integration into Java workflow systems with the following techniques…
Folie 18
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
Python
Interpreter
Python
Python
Code
Code
Tools for
Python-Java-Integration
Python
Interpreter
Python
Python
Code
Code
JPype
JPype
Jython
Jython
JEPP
JEPP
Python
Python
Code
Code
JNI
Interface/Protokoll
Java
Java Code
Code
(Anwendung)
(Anwendung)
Python
Python
Code
Code
Java Virtual Machine (JVM)
Folie 19
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
Accessing Python from Java
Use cases
The application should have embedded scripting functionality.
The application should use an external code written in Python.
The application should use an external code written in Python or other languages
such as C, C++, Fortran.
Tools
Jython
JEPP
Folie 20
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
Jython
Complete re-implementation of the Python
interpreter in Java
Python code runs in the Java VM
Website: http://www.jython.org
Latest version: Jython 2.5
For details & questions, catch
Tobias Ivarsson
Frank Wierzbicki
Python
Code
Jython
Java
Application
Code
Java Virtual Machine
and others here at EuroPython
Folie 21
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
Jython
Code Example 1: Java code
Execute Python code
import org.python.util.PythonInterpreter ;
import org.python.core.*;
class TestClass {
public static void main(String[] args) {
try {
org.python.util.PythonInterpreter python =
new org.python.util.PythonInterpreter ();
python.execfile("python_script.py");
} catch (Exception e) {
System.out.println(“Some error!");
}
}
Folie 22
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
Jython
Code Example 2: Python code
Use Swing
from javax.swing import *
frame = JFrame("Hello Jython")
label = JLabel("Hello Jython!", JLabel.CENTER)
frame.add(label)
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE)
frame.setSize(200, 100)
frame.show()
Folie 23
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
JEPP
Java Embedded Python
Python Interpreter
Embeds CPython interpreter via Java Native
Interface (JNI) in Java
Python
Code
Python code runs in CPython
Website:
http://jepp.sourceforge.net/
JNI
JEPP
Java Application
Code
Java Virtual Machine
Folie 24
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
JEPP
Code Example
Execute (“evaluate”) Python statements
Jep jep = new Jep(false, SCRIPT_PATH, cl);
jep.eval("print 'hello'");
jep.close();
Execute a Python script file
Jep jep = new Jep(false, SCRIPT_PATH, cl);
jep.runScript(SCRIPT_PATH + file);
jep.close();
Folie 25
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
Accessing Java from Python
Use cases
The application should use an external Java application.
The application should use a Java library.
Tools
JPype
JCC
Folie 26
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
JPype
Java to Python Integration
Interface on native level of both (Java & Python)
Virtual Machines/Interpreters
Python Interpreter
Python
Application Code
Starts a Java Virtual Machine
JPype
Website:
http://jpype.sourceforge.net
JNI
Java Application
Code
Java Virtual Machine
Folie 27
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
JPype
Code Example (1)
Hello World
from jpype import *
# Start JVM
startJVM (path to jvm.dll, "-ea")
# Print "Hello World"
java.lang.System.out.println("Hello World")
# Shutdown JVM
shutdownJVM()
Folie 28
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
JPype
Code Example (2)
Call Java methods from Python
import jpype
# Start JVM
jpype.startJVM(path to jvm.dll, "-ea")
# Create reference to java package
javaPackage = jpype.JPackage("JavaPackageName")
# Create reference to java class
javaClass = javaPackage.JavaClassName
# Create instance of java class
javaObject = javaClass()
# Call java methods
javaObject.JavaMethodName()
# Shutdown JVM
jpype.shutdownJVM()
Folie 29
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
JCC
PyLucene's Code Generator
C++ code generator for calling Java
from C++/Python
C++ object interface for wrapping a
Java library via JNI
Generates complete CPython
extension
Supported on Mac OS X, Linux,
Solaris and Windows, requires C++
compiler
Website:
http://lucene.apache.org
/pylucene/jcc
Python Interpreter
Python
Code
Generated C++
Wrapper Code
JNI
JCC Code
Generator
Java Application
Code
pythonExtension()
Part of PyLucene
Java Virtual Machine
Folie 30
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
JCC
Code Example
Requirement: VM initialization
import jcc
# Start JVM
jcc.initVM(maxheap=‘2000m’, …)
Folie 31
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
JCC Code Example
Using PyLucene: Search Lucene Index
Search for „Query“ in directory „index“
from lucene import QueryParser, IndexSearcher, StandardAnalyzer,
FSDirectory, Hit, VERSION, initVM, CLASSPATH
initVM(CLASSPATH)
directory = FSDirectory.getDirectory(“index”, False)
searcher = IndexSearcher(directory)
analyzer = StandardAnalyzer()
command = raw_input("Query:")
query = QueryParser("contents", analyzer).parse(command)
hits = searcher.search(query)
for hit in hits:
doc = Hit.cast_(hit).getDocument()
print 'path:', doc.get("path"), 'name:', doc.get("name")
searcher.close()
Folie 32
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
Inter-Process Communication
Inter-process communication (IPC) is data exchange between different processes
on one or more computers connected by a network
Typical IPC techniques are
remote procedure calls (RPC)
message passing.
The most common APIs are
Object Request Broker (ORB) or
Web Services protocols based on XML.
A drawback is the need for additional services, such as a directory service for
registration and location of remote objects
Naming Service for CORBA
Universal Description, Discovery and Integration (UDDI) for Web
Services
Folie 33
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
Object Request Broker (ORBs)
CORBA
IDL
IDL Compiler
Generated
Java Code
(Stub)
Java Virtual Machine
ORB
Java
Application
Code
(Client)
Generated
Python Code
(Skeleton)
Python
Application
Code
(Server)
Python Interpreter
Folie 34
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
CORBA Implementations for Python
Fnorb
Pure Python implementation that works with CPython and Jython.
It is a light-weight CORBA implementation and interoperable with the standard Java
ORB.
The development of Fnorb has ended.
omniORB
An ORB implementation for C++ and Python that can be used from CPython.
The Python ORB (omniORBpy) uses the C++ implementation of omniORB.
omniORB is actively developed with regular releases.
Website: http://omniorb.sourceforge.net
Folie 35
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
CORBA Example
Interface
Hello World interface in Interface Definition Language (IDL)
module HelloWorld {
const string Message = "Hello CORBA World!";
interface Hello {
string hello_world();
};
};
Folie 36
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
CORBA Example
Python Server (Fnorb): Implementation of Interface
# Standard/built-in modules.
import sys
# Fnorb modules.
from Fnorb.orb import BOA, CORBA
# Stubs and skeletons generated by 'fnidl'.
import HelloWorld, HelloWorld_skel
class HelloWorldServer(HelloWorld_skel.Hello_skel):
""" Implementation of the 'Hello' interface. """
def hello_world(self):
print HelloWorld.Message
return HelloWorld.Message
Folie 37
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
CORBA Example
Python Server (Fnorb): Main Function
def main(argv):
# Initialise ORB and BOA
orb = CORBA.ORB_init(argv, CORBA.ORB_ID)
boa = BOA.BOA_init(argv, BOA.BOA_ID)
# Create object reference
obj = boa.create('fred', HelloWorldServer._FNORB_ID)
# Create an instance of the implementation class.
impl = HelloWorldServer()
# Activate the implementation
boa.obj_is_ready(obj, impl)
# Write the stringified object reference to a file
open('Server.ref', 'w').write(orb.object_to_string(obj))
boa._fnorb_mainloop() # Start the event loop
return 0
Folie 38
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
CORBA Example
Java Client
public class Client {
public static void main ( String args[] ) {
java.util.Properties props = System.getProperties();
try {
org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args,props);
org.omg.CORBA.Object obj = null;
java.io.BufferedReader in = new java.io.BufferedReader(
new java.io.FileReader(“Server.ref"));
String ref = in.readLine();
obj = orb.string_to_object(ref);
Hello hello = HelloHelper.narrow(obj);
hello.hello_world();
orb.destroy();
} catch (Exception e) { e.printStackTrace(); }
}
Folie 39
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
Web Services: SOAP
WSDL
WSDL Compiler
Python
Application
Code
(Client)
Generated
Python Code
(Stub)
Python Interpreter
Generated
Java Code
(Skeleton)
Java
Application
Code
(Server)
Servlet Container
Java Virtual Machine
Folie 40
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
Web Services for Python
Zolera SOAP Infrastructure (ZSI)
For Python the only remaining SOAP toolkit of considerable quality is the Zolera
SOAP Infrastructure (ZSI)
Folie 41
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
Other Remote Object Libraries
Python Remote Objects (Pyro)
Pyro is similar to Java's Remote Method Invocation (RMI).
It is simple, very portable, and works with Jython.
Brings its own Naming Service for locating remote objects.
Pyro is actively developed with regular new releases.
Simple Python Interface to Remote Objects (SPIRO)
SPIRO implements an ORB and is developed as a bridge between CPython
and Jython.
The development has ended.
Folie 42
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
Conclusions
I
Jython
… but there are alternatives which makes sense for certain use cases!
Folie 43
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009
Questions?
Contact
http://tr.im/schreiber
twitter.com/onyame
python@dlr.de
Folie 44
EuroPython 2009 > Andreas Schreiber > Mixing Python and Java > 01.07.2009