SlideShare uma empresa Scribd logo
1 de 35
What do you mean it needs to be Java based? How Jython saved the day! Mark Rees Group CTO Century Software Holdings Berhad http://www.censof.com/ @hexdump42
Century Software (M) Sdn Bhd http://www.centurysoftware.com.my Develop & implement Financial Management Software Solutions Some of our applications use Python. Who?
From a tender document ” The application must be written in an industry standard enterprise programming framework. Please state which framework. ” The problem
Python! Our preferred answer
Java or .NET The expected answer
” The web application must run using an Enterprise Web Application Server. ” Another problem
Django, Pyramid, ... Our preferred answer
Websphere, JBoss, OAS... The expected answer
The solution
Jython Equivalent to Python Reference Version 2.5 Includes standard library
Installation java -jar jython_installer-2.5.2.jar
Pros Runs most existing Python code without mods No GIL Access to Java Libraries Cons Performance No C extensions Pros & Cons
Call Java Code from com.google.i18n.phonenumbers import PhoneNumberUtil class PhoneNumberi18n: def __init__(self, country, phonenumber): self.phone_number_util = PhoneNumberUtil.getInstance() self.raw_phone_number = phonenumber self.country = country self.phone_number = self.phone_number_util.parse(phonenumber, country) def is_valid_number(self): return self.phone_number_util.isValidNumber(self.phone_number) def format_as_international(self): return self.phone_number_util.format(self.phone_number, PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL) Let's format some phone numbers http://code.google.com/p/libphonenumber/
Jython has a GUI from  java.awt  import  BorderLayout from  javax.swing  import  JButton, JFrame, JPanel, JLabel class  SimpleGUI(object): def  __init__(self): self.frame  =  JFrame( 'Hello World' , defaultCloseOperation  =  JFrame.EXIT_ON_CLOSE, size  =  ( 400, 400 )) self.label  =  JLabel ( 'Hello World' ) self.panel  =  JPanel() self.button  =  JButton( 'Click Me' , actionPerformed=self.hello) self.panel.add(self.button) self.content_panel  =  self.frame.getContentPane() self.content_panel.setLayout(BorderLayout()) self.content_panel.add(self.label, BorderLayout.CENTER) self.content_panel.add(self.panel, BorderLayout.PAGE_END) self.frame.visible  =   True def  hello(self, event): self.label.setText( 'Hello user who clicked' )  if  __name__ = =   '__main__' : SimpleGUI()
Calling Jython from Java from com.censof.examples.interfaces import PersonType Class Person(Persontype) def __init__(self,name,gender): self.name = name self.gender = gender def getPersonName(self): return self.name Support for Java to use Jython classes It's not simple. Need jython class and interface. // Java interface for Person object package com.censof.examples.interfaces; public interface PersonType { public String getPersonName(); }
Calling Jython from Java package com.censof.examples.util; import com.censof.interfaces.PersonType; import org.python.core.PyObject; import org.python.core.PyString; import org.python.util.PythonInterpreter; public class PersonFactory { private PyObject personClass; PythonInterpreter interpreter = new PythonInterpreter(); interpreter.exec("from Person import Person"); personClass = interpreter.get("Person"); public PersonType create (String name, String location, String id) { PyObject personObject = personClass.__call__(new PyString(name), new PyString(gender), return (PersonType)buildingObject.__tojava__(PersonType.class); } } Then we need an object factory to coerce Jython  module into a Java class
Calling Jython from Java package com.censof.examples; import com.censof.examples.util.PersonFactory; import com.censof.examples.interfaces.PersonType; public class Main { private static void print(PersonType person) { System.out.println("Person: " + person.getPersonName(); } public static void main(String[] args) { PersonFactory factory = new PersonFactory(); print(factory.create("Mark", "male")); print(factory.create("Joanne", "female")); } } Now we can call the jython class from java. Told you it's not simple.
Jython Scripting from Java import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; public class JSRMain { public static void main(String[] args) throws ScriptException { ScriptEngine engine = new ScriptEngineManager().getEngineByName("python"); engine.eval("import sys"); engine.eval("print sys.path"); engine.put("who", "Mark"); engine.eval("print who"); engine.eval("sum = 2 + 2"); Object x = engine.get("sum"); System.out.println("sum: " + x); } } JSR-223 enabled dynamic languages to be callable via Java.
Jython Scripting from Java import org.python.core.PyException; import org.python.core.PyInteger; import org.python.core.PyString; import org.python.core.PyObject; import org.python.util.PythonInterpreter; public class Main { public static void main(String[] args) throws PyException { PythonInterpreter interp = new PythonInterpreter(); interp.exec("import sys"); interp.exec("print sys.path"); interp.set("who", new PyString("Mark")); interp.exec("print who"); interp.exec("sum = 2+2"); PyObject x = interp.get("sum"); System.out.println("sum: " + x); } } You can also use the PythonInterpreter directly.
zxJDBC – Python DBAPI bridge to JDBC export CLASSPATH=/usr/share/java/postgresql.jar from __future__ import with_statement from com.ziclix.python.sql import zxJDBC jdbc_url =  "jdbc:postgresql:wiki" username =  "postgres" password =  "secret" driver =  "org.postgresql.Driver" with zxJDBC.connect(jdbc_url, username, password, driver) as conn: with conn: with conn.cursor() as c: c.execute( "select * from pages" ) c.fetchone() Database Access
zxJDBC understands JNDI (Java Naming & Directory Interface) allowing access to managed JDBC connections. from com.ziclix.python.sql import zxJDBC factory =  "com.sun.jndi.fscontext.RefFSContextFactory" conn = zxJDBC.lookup( 'jdbc/postgresDS' , INITIAL_CONTEXT_FACTORY=factory) Database Access
Python ORM’s from  sqlalchemy  import  create_engine, Column, Integer, String, Text from  sqlalchemy.ext.declarative  import  declarative_base from  sqlalchemy.orm  import  sessionmaker engine = create_engine( 'postgresql+zxjdbc://postgres:secret@localhost/wiki' ) session = sessionmaker(bind=engine) Base = declarative_base() class   Page (Base): __tablename__ =  'pages ' id = Column(Integer, primary_key =  True ) name = Column(String) data = Column(Text) def   __init__ (self, name, data= None ): self.name = name self.data = data  def   __unicode__ (self): return   &quot;<Page(%s)&quot;  % (self.name,)
Java ORM’s You can utilise Hibernate for persistance. See: http://www.jython.org/jythonbook/en/1.0/DatabasesAndJython.html#hibernate
from javax.servlet.http import HttpServlet class MyJythonServlet (HttpServlet): def doGet(self,request,response): self.doPost (request,response) def doPost(self,request,response): toClient = response.getWriter() response.setContentType (&quot;text/html&quot;) toClient.println (&quot;<html><head><title>My Jython Servlet Demo</title>&quot; + &quot;<body><h1>Servlet Jython Servlet at&quot; + request.getContextPath() + &quot;</h1></body></html>&quot;) def getServletInfo(self): return &quot;A Simple Jython Servlet Demo&quot; Create web.xml, copy  jython script, jython.jar in the CLASSPATH. http://localhost:8080/MyJythonServlet/MyJythonServlet.py Do it the java way: Jython & the Web - Servlets
Do it the python way: modjy – WSGI compliant gateway for Jython def   handler (environ, start_response): start_response ('200 OK' , [( 'Content-Type', 'text/plain' )]) yield   'Hello World ' It's a java jvm, so there's still some xml: web.xml <web-app> <display-name>modjy demo application</display-name> <description>modjy WSGI demo application</description> <servlet> <servlet-name>modjy</servlet-name> <servlet-class>com.xhaus.modjy.ModjyJServlet</servlet-class> … .  <init-param> <param-name>app_filename</param-name> <param-value>helloworld.py</param-value> </init-param> …... Jython & the Web - modjy
Jython & the Web - django
pip install django Downloading/unpacking django Downloading Django-1.3.tar.gz (6.5Mb): 6.5Mb downloaded Running setup.py egg_info for package django Installing collected packages: django Running setup.py install for django Successfully installed django pip install django_jython==1.3.0b1 Downloading/unpacking django-jython==1.3.0b1 Downloading django-jython-1.3.0b1.tar.gz (42Kb): 42Kb downloaded Running setup.py egg_info for package django-jython Installing collected packages: django-jython Running setup.py install for django-jython Successfully installed django-jython In jython environment, install django: Then install django_jython Jython & the Web - django
django-admin.py startproject wiki cd wiki vi settings.py DATABASES = { 'default': { 'ENGINE': 'doj.backends.zxjdbc.postgresql',  #  'doj.backends.zxjdbc.  postgresql', 'doj.backends.zxjdbc.mysql', 'doj.backends.zxjdbc.sqlite3' or  ‘ doj.backends.zxjdbc.oracle'. … . } export CLASSPATH=/usr/share/java/postgresql.jar:$CLASSPATH jython manage.py syncdb jython manage.py runserver Validating models... 0 errors found Django version 1.3, using settings 'wiki.settings' Development server is running at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Then configure using zxjdbc for databases: Jython & the Web - django
vi settings.py # Add doj to INSTALLED_APPS INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', … . doj,) Thanks to modjy & django_jython we can deploy as a servlet: jython manage.py war –include-java-libs=/usr/share/java/postgresql.jar Copying WAR skeleton... Copying jython.jar... … . Copying postgresql.jar... Building WAR on /home/mark/swdev/jython-pycon-apac-2011/django_wiki/wiki.war... Finished. Now you can copy wiki.war to whatever location your application server wants it. Create WAR for deployment: Jython & the Web - django
Jython & the Web - pyramid
Most things work of of the box under Jython Database access thanks to SQLAlchemy snakefight handles deployment under Java servlet containers. Works with any paster based web app. http://pypi.python.org/pypi/snakefight Jython & the Web - pyramid
YES Did Jython really save the day?
Jython Website http://www.jython.org/ The Definitive Guide to Jython Book http://www.jythonbook.com / Resources
http://djangopony.com/ http://www.felixlaflamme.com/2011/03/16/pyramid-web-application-framework/  Credits for images used
Q & A

Mais conteúdo relacionado

Mais procurados

Programming with Python - Basic
Programming with Python - BasicProgramming with Python - Basic
Programming with Python - BasicMosky Liu
 
Come With Golang
Come With GolangCome With Golang
Come With Golang尚文 曾
 
Ekon 25 Python4Delphi_MX475
Ekon 25 Python4Delphi_MX475Ekon 25 Python4Delphi_MX475
Ekon 25 Python4Delphi_MX475Max Kleiner
 
PyPy 1.2: snakes never crawled so fast
PyPy 1.2: snakes never crawled so fastPyPy 1.2: snakes never crawled so fast
PyPy 1.2: snakes never crawled so fastPyCon Italia
 
Inroduction to golang
Inroduction to golangInroduction to golang
Inroduction to golangYoni Davidson
 
A Better Python for the JVM
A Better Python for the JVMA Better Python for the JVM
A Better Python for the JVMTobias Lindaaker
 
Pascal script maxbox_ekon_14_2
Pascal script maxbox_ekon_14_2Pascal script maxbox_ekon_14_2
Pascal script maxbox_ekon_14_2Max Kleiner
 
Python Testing Fundamentals
Python Testing FundamentalsPython Testing Fundamentals
Python Testing Fundamentalscbcunc
 
EKON 25 Python4Delphi_mX4
EKON 25 Python4Delphi_mX4EKON 25 Python4Delphi_mX4
EKON 25 Python4Delphi_mX4Max Kleiner
 
Seattle useR Group - R + Scala
Seattle useR Group - R + ScalaSeattle useR Group - R + Scala
Seattle useR Group - R + ScalaShouheng Yi
 
Python Programming Essentials - M28 - Debugging with pdb
Python Programming Essentials - M28 - Debugging with pdbPython Programming Essentials - M28 - Debugging with pdb
Python Programming Essentials - M28 - Debugging with pdbP3 InfoTech Solutions Pvt. Ltd.
 
Sour Pickles
Sour PicklesSour Pickles
Sour PicklesSensePost
 

Mais procurados (20)

Programming with Python - Basic
Programming with Python - BasicProgramming with Python - Basic
Programming with Python - Basic
 
Doing the Impossible
Doing the ImpossibleDoing the Impossible
Doing the Impossible
 
Android antipatterns
Android antipatternsAndroid antipatterns
Android antipatterns
 
Come With Golang
Come With GolangCome With Golang
Come With Golang
 
Ekon 25 Python4Delphi_MX475
Ekon 25 Python4Delphi_MX475Ekon 25 Python4Delphi_MX475
Ekon 25 Python4Delphi_MX475
 
PyPy 1.2: snakes never crawled so fast
PyPy 1.2: snakes never crawled so fastPyPy 1.2: snakes never crawled so fast
PyPy 1.2: snakes never crawled so fast
 
Inroduction to golang
Inroduction to golangInroduction to golang
Inroduction to golang
 
Lombok
LombokLombok
Lombok
 
Project Lombok!
Project Lombok!Project Lombok!
Project Lombok!
 
Python Flavors
Python FlavorsPython Flavors
Python Flavors
 
Modern Python Testing
Modern Python TestingModern Python Testing
Modern Python Testing
 
A Better Python for the JVM
A Better Python for the JVMA Better Python for the JVM
A Better Python for the JVM
 
Intro dotnet
Intro dotnetIntro dotnet
Intro dotnet
 
Perl Modules
Perl ModulesPerl Modules
Perl Modules
 
Pascal script maxbox_ekon_14_2
Pascal script maxbox_ekon_14_2Pascal script maxbox_ekon_14_2
Pascal script maxbox_ekon_14_2
 
Python Testing Fundamentals
Python Testing FundamentalsPython Testing Fundamentals
Python Testing Fundamentals
 
EKON 25 Python4Delphi_mX4
EKON 25 Python4Delphi_mX4EKON 25 Python4Delphi_mX4
EKON 25 Python4Delphi_mX4
 
Seattle useR Group - R + Scala
Seattle useR Group - R + ScalaSeattle useR Group - R + Scala
Seattle useR Group - R + Scala
 
Python Programming Essentials - M28 - Debugging with pdb
Python Programming Essentials - M28 - Debugging with pdbPython Programming Essentials - M28 - Debugging with pdb
Python Programming Essentials - M28 - Debugging with pdb
 
Sour Pickles
Sour PicklesSour Pickles
Sour Pickles
 

Semelhante a What do you mean it needs to be Java based? How jython saved the day.

jBPM5 in action - a quickstart for developers
jBPM5 in action - a quickstart for developersjBPM5 in action - a quickstart for developers
jBPM5 in action - a quickstart for developersKris Verlaenen
 
HRServicesPOX.classpathHRServicesPOX.project HRSer.docx
HRServicesPOX.classpathHRServicesPOX.project  HRSer.docxHRServicesPOX.classpathHRServicesPOX.project  HRSer.docx
HRServicesPOX.classpathHRServicesPOX.project HRSer.docxadampcarr67227
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_ods
 
Non Conventional Android Programming (English)
Non Conventional Android Programming (English)Non Conventional Android Programming (English)
Non Conventional Android Programming (English)Davide Cerbo
 
Non Conventional Android Programming En
Non Conventional Android Programming EnNon Conventional Android Programming En
Non Conventional Android Programming Enguest9bcef2f
 
Learning Java 4 – Swing, SQL, and Security API
Learning Java 4 – Swing, SQL, and Security APILearning Java 4 – Swing, SQL, and Security API
Learning Java 4 – Swing, SQL, and Security APIcaswenson
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Guillaume Laforge
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingVisual Engineering
 
ActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group PresentationActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group Presentationipolevoy
 
Object Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in PythonObject Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in PythonPython Ireland
 
JavaEE Security
JavaEE SecurityJavaEE Security
JavaEE SecurityAlex Kim
 
Testing of javacript
Testing of javacriptTesting of javacript
Testing of javacriptLei Kang
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Edureka!
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best PracticesYekmer Simsek
 

Semelhante a What do you mean it needs to be Java based? How jython saved the day. (20)

Griffon @ Svwjug
Griffon @ SvwjugGriffon @ Svwjug
Griffon @ Svwjug
 
Tuto jtatoo
Tuto jtatooTuto jtatoo
Tuto jtatoo
 
jBPM5 in action - a quickstart for developers
jBPM5 in action - a quickstart for developersjBPM5 in action - a quickstart for developers
jBPM5 in action - a quickstart for developers
 
HRServicesPOX.classpathHRServicesPOX.project HRSer.docx
HRServicesPOX.classpathHRServicesPOX.project  HRSer.docxHRServicesPOX.classpathHRServicesPOX.project  HRSer.docx
HRServicesPOX.classpathHRServicesPOX.project HRSer.docx
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Applets
AppletsApplets
Applets
 
Non Conventional Android Programming (English)
Non Conventional Android Programming (English)Non Conventional Android Programming (English)
Non Conventional Android Programming (English)
 
Non Conventional Android Programming En
Non Conventional Android Programming EnNon Conventional Android Programming En
Non Conventional Android Programming En
 
Learning Java 4 – Swing, SQL, and Security API
Learning Java 4 – Swing, SQL, and Security APILearning Java 4 – Swing, SQL, and Security API
Learning Java 4 – Swing, SQL, and Security API
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
 
ActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group PresentationActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group Presentation
 
Object Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in PythonObject Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in Python
 
JavaEE Security
JavaEE SecurityJavaEE Security
JavaEE Security
 
Testing of javacript
Testing of javacriptTesting of javacript
Testing of javacript
 
Os Johnson
Os JohnsonOs Johnson
Os Johnson
 
dJango
dJangodJango
dJango
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best Practices
 
Oop lecture2
Oop lecture2Oop lecture2
Oop lecture2
 

Mais de Mark Rees

Porting a legacy app to python 3
Porting a legacy app to python 3Porting a legacy app to python 3
Porting a legacy app to python 3Mark Rees
 
Relational Database Access with Python
Relational Database Access with PythonRelational Database Access with Python
Relational Database Access with PythonMark Rees
 
Seeing with Python presented at PyCon AU 2014
Seeing with Python presented at PyCon AU 2014Seeing with Python presented at PyCon AU 2014
Seeing with Python presented at PyCon AU 2014Mark Rees
 
Seeing with Python - Pycon SG 2014
Seeing with Python - Pycon SG 2014Seeing with Python - Pycon SG 2014
Seeing with Python - Pycon SG 2014Mark Rees
 
Pypy is-it-ready-for-production-the-sequel
Pypy is-it-ready-for-production-the-sequelPypy is-it-ready-for-production-the-sequel
Pypy is-it-ready-for-production-the-sequelMark Rees
 
PyPy - is it ready for production
PyPy - is it ready for productionPyPy - is it ready for production
PyPy - is it ready for productionMark Rees
 
Relational Database Access with Python ‘sans’ ORM
Relational Database Access with Python ‘sans’ ORM  Relational Database Access with Python ‘sans’ ORM
Relational Database Access with Python ‘sans’ ORM Mark Rees
 

Mais de Mark Rees (7)

Porting a legacy app to python 3
Porting a legacy app to python 3Porting a legacy app to python 3
Porting a legacy app to python 3
 
Relational Database Access with Python
Relational Database Access with PythonRelational Database Access with Python
Relational Database Access with Python
 
Seeing with Python presented at PyCon AU 2014
Seeing with Python presented at PyCon AU 2014Seeing with Python presented at PyCon AU 2014
Seeing with Python presented at PyCon AU 2014
 
Seeing with Python - Pycon SG 2014
Seeing with Python - Pycon SG 2014Seeing with Python - Pycon SG 2014
Seeing with Python - Pycon SG 2014
 
Pypy is-it-ready-for-production-the-sequel
Pypy is-it-ready-for-production-the-sequelPypy is-it-ready-for-production-the-sequel
Pypy is-it-ready-for-production-the-sequel
 
PyPy - is it ready for production
PyPy - is it ready for productionPyPy - is it ready for production
PyPy - is it ready for production
 
Relational Database Access with Python ‘sans’ ORM
Relational Database Access with Python ‘sans’ ORM  Relational Database Access with Python ‘sans’ ORM
Relational Database Access with Python ‘sans’ ORM
 

Último

A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 

Último (20)

A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 

What do you mean it needs to be Java based? How jython saved the day.

  • 1. What do you mean it needs to be Java based? How Jython saved the day! Mark Rees Group CTO Century Software Holdings Berhad http://www.censof.com/ @hexdump42
  • 2. Century Software (M) Sdn Bhd http://www.centurysoftware.com.my Develop & implement Financial Management Software Solutions Some of our applications use Python. Who?
  • 3. From a tender document ” The application must be written in an industry standard enterprise programming framework. Please state which framework. ” The problem
  • 5. Java or .NET The expected answer
  • 6. ” The web application must run using an Enterprise Web Application Server. ” Another problem
  • 7. Django, Pyramid, ... Our preferred answer
  • 8. Websphere, JBoss, OAS... The expected answer
  • 10. Jython Equivalent to Python Reference Version 2.5 Includes standard library
  • 11. Installation java -jar jython_installer-2.5.2.jar
  • 12. Pros Runs most existing Python code without mods No GIL Access to Java Libraries Cons Performance No C extensions Pros & Cons
  • 13. Call Java Code from com.google.i18n.phonenumbers import PhoneNumberUtil class PhoneNumberi18n: def __init__(self, country, phonenumber): self.phone_number_util = PhoneNumberUtil.getInstance() self.raw_phone_number = phonenumber self.country = country self.phone_number = self.phone_number_util.parse(phonenumber, country) def is_valid_number(self): return self.phone_number_util.isValidNumber(self.phone_number) def format_as_international(self): return self.phone_number_util.format(self.phone_number, PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL) Let's format some phone numbers http://code.google.com/p/libphonenumber/
  • 14. Jython has a GUI from java.awt import BorderLayout from javax.swing import JButton, JFrame, JPanel, JLabel class SimpleGUI(object): def __init__(self): self.frame = JFrame( 'Hello World' , defaultCloseOperation = JFrame.EXIT_ON_CLOSE, size = ( 400, 400 )) self.label = JLabel ( 'Hello World' ) self.panel = JPanel() self.button = JButton( 'Click Me' , actionPerformed=self.hello) self.panel.add(self.button) self.content_panel = self.frame.getContentPane() self.content_panel.setLayout(BorderLayout()) self.content_panel.add(self.label, BorderLayout.CENTER) self.content_panel.add(self.panel, BorderLayout.PAGE_END) self.frame.visible = True def hello(self, event): self.label.setText( 'Hello user who clicked' ) if __name__ = = '__main__' : SimpleGUI()
  • 15. Calling Jython from Java from com.censof.examples.interfaces import PersonType Class Person(Persontype) def __init__(self,name,gender): self.name = name self.gender = gender def getPersonName(self): return self.name Support for Java to use Jython classes It's not simple. Need jython class and interface. // Java interface for Person object package com.censof.examples.interfaces; public interface PersonType { public String getPersonName(); }
  • 16. Calling Jython from Java package com.censof.examples.util; import com.censof.interfaces.PersonType; import org.python.core.PyObject; import org.python.core.PyString; import org.python.util.PythonInterpreter; public class PersonFactory { private PyObject personClass; PythonInterpreter interpreter = new PythonInterpreter(); interpreter.exec(&quot;from Person import Person&quot;); personClass = interpreter.get(&quot;Person&quot;); public PersonType create (String name, String location, String id) { PyObject personObject = personClass.__call__(new PyString(name), new PyString(gender), return (PersonType)buildingObject.__tojava__(PersonType.class); } } Then we need an object factory to coerce Jython module into a Java class
  • 17. Calling Jython from Java package com.censof.examples; import com.censof.examples.util.PersonFactory; import com.censof.examples.interfaces.PersonType; public class Main { private static void print(PersonType person) { System.out.println(&quot;Person: &quot; + person.getPersonName(); } public static void main(String[] args) { PersonFactory factory = new PersonFactory(); print(factory.create(&quot;Mark&quot;, &quot;male&quot;)); print(factory.create(&quot;Joanne&quot;, &quot;female&quot;)); } } Now we can call the jython class from java. Told you it's not simple.
  • 18. Jython Scripting from Java import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; public class JSRMain { public static void main(String[] args) throws ScriptException { ScriptEngine engine = new ScriptEngineManager().getEngineByName(&quot;python&quot;); engine.eval(&quot;import sys&quot;); engine.eval(&quot;print sys.path&quot;); engine.put(&quot;who&quot;, &quot;Mark&quot;); engine.eval(&quot;print who&quot;); engine.eval(&quot;sum = 2 + 2&quot;); Object x = engine.get(&quot;sum&quot;); System.out.println(&quot;sum: &quot; + x); } } JSR-223 enabled dynamic languages to be callable via Java.
  • 19. Jython Scripting from Java import org.python.core.PyException; import org.python.core.PyInteger; import org.python.core.PyString; import org.python.core.PyObject; import org.python.util.PythonInterpreter; public class Main { public static void main(String[] args) throws PyException { PythonInterpreter interp = new PythonInterpreter(); interp.exec(&quot;import sys&quot;); interp.exec(&quot;print sys.path&quot;); interp.set(&quot;who&quot;, new PyString(&quot;Mark&quot;)); interp.exec(&quot;print who&quot;); interp.exec(&quot;sum = 2+2&quot;); PyObject x = interp.get(&quot;sum&quot;); System.out.println(&quot;sum: &quot; + x); } } You can also use the PythonInterpreter directly.
  • 20. zxJDBC – Python DBAPI bridge to JDBC export CLASSPATH=/usr/share/java/postgresql.jar from __future__ import with_statement from com.ziclix.python.sql import zxJDBC jdbc_url = &quot;jdbc:postgresql:wiki&quot; username = &quot;postgres&quot; password = &quot;secret&quot; driver = &quot;org.postgresql.Driver&quot; with zxJDBC.connect(jdbc_url, username, password, driver) as conn: with conn: with conn.cursor() as c: c.execute( &quot;select * from pages&quot; ) c.fetchone() Database Access
  • 21. zxJDBC understands JNDI (Java Naming & Directory Interface) allowing access to managed JDBC connections. from com.ziclix.python.sql import zxJDBC factory = &quot;com.sun.jndi.fscontext.RefFSContextFactory&quot; conn = zxJDBC.lookup( 'jdbc/postgresDS' , INITIAL_CONTEXT_FACTORY=factory) Database Access
  • 22. Python ORM’s from sqlalchemy import create_engine, Column, Integer, String, Text from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker engine = create_engine( 'postgresql+zxjdbc://postgres:secret@localhost/wiki' ) session = sessionmaker(bind=engine) Base = declarative_base() class Page (Base): __tablename__ = 'pages ' id = Column(Integer, primary_key = True ) name = Column(String) data = Column(Text) def __init__ (self, name, data= None ): self.name = name self.data = data def __unicode__ (self): return &quot;<Page(%s)&quot; % (self.name,)
  • 23. Java ORM’s You can utilise Hibernate for persistance. See: http://www.jython.org/jythonbook/en/1.0/DatabasesAndJython.html#hibernate
  • 24. from javax.servlet.http import HttpServlet class MyJythonServlet (HttpServlet): def doGet(self,request,response): self.doPost (request,response) def doPost(self,request,response): toClient = response.getWriter() response.setContentType (&quot;text/html&quot;) toClient.println (&quot;<html><head><title>My Jython Servlet Demo</title>&quot; + &quot;<body><h1>Servlet Jython Servlet at&quot; + request.getContextPath() + &quot;</h1></body></html>&quot;) def getServletInfo(self): return &quot;A Simple Jython Servlet Demo&quot; Create web.xml, copy jython script, jython.jar in the CLASSPATH. http://localhost:8080/MyJythonServlet/MyJythonServlet.py Do it the java way: Jython & the Web - Servlets
  • 25. Do it the python way: modjy – WSGI compliant gateway for Jython def handler (environ, start_response): start_response ('200 OK' , [( 'Content-Type', 'text/plain' )]) yield 'Hello World ' It's a java jvm, so there's still some xml: web.xml <web-app> <display-name>modjy demo application</display-name> <description>modjy WSGI demo application</description> <servlet> <servlet-name>modjy</servlet-name> <servlet-class>com.xhaus.modjy.ModjyJServlet</servlet-class> … . <init-param> <param-name>app_filename</param-name> <param-value>helloworld.py</param-value> </init-param> …... Jython & the Web - modjy
  • 26. Jython & the Web - django
  • 27. pip install django Downloading/unpacking django Downloading Django-1.3.tar.gz (6.5Mb): 6.5Mb downloaded Running setup.py egg_info for package django Installing collected packages: django Running setup.py install for django Successfully installed django pip install django_jython==1.3.0b1 Downloading/unpacking django-jython==1.3.0b1 Downloading django-jython-1.3.0b1.tar.gz (42Kb): 42Kb downloaded Running setup.py egg_info for package django-jython Installing collected packages: django-jython Running setup.py install for django-jython Successfully installed django-jython In jython environment, install django: Then install django_jython Jython & the Web - django
  • 28. django-admin.py startproject wiki cd wiki vi settings.py DATABASES = { 'default': { 'ENGINE': 'doj.backends.zxjdbc.postgresql', # 'doj.backends.zxjdbc. postgresql', 'doj.backends.zxjdbc.mysql', 'doj.backends.zxjdbc.sqlite3' or ‘ doj.backends.zxjdbc.oracle'. … . } export CLASSPATH=/usr/share/java/postgresql.jar:$CLASSPATH jython manage.py syncdb jython manage.py runserver Validating models... 0 errors found Django version 1.3, using settings 'wiki.settings' Development server is running at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Then configure using zxjdbc for databases: Jython & the Web - django
  • 29. vi settings.py # Add doj to INSTALLED_APPS INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', … . doj,) Thanks to modjy & django_jython we can deploy as a servlet: jython manage.py war –include-java-libs=/usr/share/java/postgresql.jar Copying WAR skeleton... Copying jython.jar... … . Copying postgresql.jar... Building WAR on /home/mark/swdev/jython-pycon-apac-2011/django_wiki/wiki.war... Finished. Now you can copy wiki.war to whatever location your application server wants it. Create WAR for deployment: Jython & the Web - django
  • 30. Jython & the Web - pyramid
  • 31. Most things work of of the box under Jython Database access thanks to SQLAlchemy snakefight handles deployment under Java servlet containers. Works with any paster based web app. http://pypi.python.org/pypi/snakefight Jython & the Web - pyramid
  • 32. YES Did Jython really save the day?
  • 33. Jython Website http://www.jython.org/ The Definitive Guide to Jython Book http://www.jythonbook.com / Resources
  • 35. Q & A

Notas do Editor

  1. Allowed us to use our existing python code with no or min code change
  2. Allowed us to use our existing python code with no or min code change Haven&apos;t found that only Python 2.5 support an issue Works with virtualenv, easy_install, pip etc
  3. Need Java JRE 5 or 6 installed Download jython installer jar from http://www.jython.org/downloads.html
  4. Performance Startup time an issue but less impact for long running processes Replace Python code with calls to Java libs where speedup necessary
  5. Needed to format phone numbers, looked for existing code. Found libphonenumber, Google&apos;s common Java library for parsing, formatting, storing and validating international phone numbers, at the time, no Python library (there is now :-]). Java code must be in CLASSPATH
  6. Cpython has tcl/tk as it ’ s ” standard ” GUI. Does anyone use it about from IDLE Jython ’ s GUI is what ships with Java AWT/Swing. a It ’ s a nice GUI toolkit and Jython makes it esy to use.
  7. jython.jar must be in CLASSPATH Also JSR-223 only works with jython 2.5.1+
  8. Support prior to Jython 2.5.1 Allows access to Python Objects
  9. zxJDBC was contributed by Brian Zimmer,a Jython committer. This API was written to enable Jython developers to have the capability of working with databases using techniques that more closely resembled the Python DB API. Originally a standaolne package it is now part of the Jython distribution
  10. Thanks to zxjdbc, SQLAlchemy runs great under Jython. With exception of jdbc uri, the rest of the code is identical to CPython.
  11. Jython script must be the same name as the class Create MyJythonServlet sub directory in Tomcat webapps directory. Copy web.xml to WEB-INF directory in the MyJythonServlet directory.
  12. . Created by Alan Kennedy during early days of WSGI PEP 333.Now part of jython distribution.
  13. django_jython Development server runs under jython
  14. Support zxjdbc support added by django_jython package.
  15. New command war added by django_jython means no need to create web.xml or package as war file manually. Gotcha: If there is already a jython.jar &amp; cachedir in server lib, you will get a ” maximum recursion depth exceeded ” error. Two options: 1. Have separate jython.jars per app (default for doj) or 2. Use –shared-war doj war creation option.
  16. Limitations – cannot use AST based template languages – no Chameleon, use Jinja2 or Mako Snakefight to package
  17. Running inside WebSphere Using JasperReports Scripting workflow systems