Making use of Java libraries from Jython
- Install the JDK and set the JAVA_HOME to the adecuate location
- Install Jython. I installed it under C:\javalibs\jython2.5.2
- If you are using 3rd party libraries don't forget to add them to the CLASSPATH. For this example I used HTTPUnit
- You may want yo add the Jython batch files to your PATH (C:\javalibs\jython2.5.2\jython.bat)
- Create your Jython source file
1 from java.lang import Math
2 from java.lang import System as javasystem
3 from com.meterware.httpunit import (
4 GetMethodWebRequest,
5 WebConversation,
6 )
7
8 def test1():
9 print Math.max(4, 7)
10 print Math.pow(10,5)
11 print Math.round(8.75)
12 print Math.abs(9.765)
13 print Math.abs(-9.765)
14
15 javasystem.out.println("Hello")
16
17 def test2():
18 url = 'http://example.com/resource/'
19 wc = WebConversation()
20 req = GetMethodWebRequest(url)
21
22 req.setHeaderField("User-Agent", "Unknown")
23 res = wc.getResponse(req)
24
25 print res.getText()
26 print res.text #same as previous, but shorter
27
28 def run():
29 test1()
30 test2()
31
32 if __name__ == '__main__':
33 run()
34
- Execute the file
The first part of the output came demonstrated the use of the Java Math library, part of the JSDK
C:\javalibs\jython2.5.2>jython.bat test.py 7 100000.0 9 9.765 9.765 Hello
The second and more verbose section came from usage of the HTTPUnit library:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><head>
...
<div class="logo"></div>
</div>
</body>
</html>
HttpWebResponse [url=http://example.com/resource/; headers=
CONTENT-TYPE: text/html;charset=UTF-8
CACHE-CONTROL: no-transform
CONNECTION: keep-alive
TRANSFER-ENCODING: chunked
X-POWERED-BY: Servlet/3.0 JSP/2.2 (GlassFish Server Open Source Edition XXX Java/Sun Microsystems Inc./1.6)
X-POWERED-BY: JSF/2.0
SERVER: nginx/X.X.X
DATE: Fri, 28 Oct 2011 14:50:03 GMT
SET-COOKIE: JSESSIONID=b0060a11d05d8477c83471ba3a88; Path=/resource; HttpOnly ]All updates to this tutorial will be posted in my blog
Created by Cesar C. Desales, October 2011
