Jython
February 28, 2012
Jython servlet and JSP for AJAX slide presentations
Servlet Code:
from javax.servlet.http import HttpServlet from java.util import ArrayList from java.util import HashMap import re import string from just import just class presentationXML(HttpServlet): def doGet(self,request,response): self.doPost (request,response) def doPost(self,request,response): response.setContentType ("text/plain") presentation_id = request.getParameter('presentation_id') presentation = self.get_presentation(presentation_id) prezs = presentation.get('rows') top_slide = prezs.get(0) request.setAttribute("top_title", top_slide['title']) request.setAttribute("top_author", top_slide['author']) request.setAttribute("top_desc", top_slide['description']) slides = self.get_slides(presentation_id) rows = slides.get('rows') columns = slides.get('columns') request.setAttribute("columns", columns) request.setAttribute("rows", rows) disp = request.getRequestDispatcher('presentation.xml.jsp') disp.forward(request, response) def build_slide(self, slide): title = slide['title'] body = slide['body'] slide_list = "" for i in body.split("\n"): (tag, line) = i.split(':') slide_list = slide_list + "\n<" + tag + '><span class="red">»</span> ' + line + "</" + tag + ">" return {'title' : title, 'slide_list' : slide_list, 'example_url' : slide['example_url'] } def get_slides(self, pres_id): juice = just() reply = juice.sql("select * from slides.slide where presentation_id = " + str(pres_id) + " order by sort_order asc") slides = [] for row in reply['rows']: slide = self.build_slide(row) slides.append(slide) return( self.jhash(slides, ['title', 'slide_list', 'example_url' ]) ) def get_presentation(self, pres_id): juice = just() reply = juice.sql("select * from slides.presentation where presentation_id = " + str(pres_id) + "limit 1") return( self.jhash(reply['rows'], reply['columns']) ) def jhash(self, rows, columns): results = HashMap() jrows = ArrayList() jcols = ArrayList() for row in rows: res = HashMap() for col in columns: jcols.add(col) res.put(col, row[col]) jrows.add(res) results.put('columns', jcols) results.put('rows', jrows) return results
JSP:
<?xml version="1.0" encoding="UTF-8"?> <%@ page contentType="text/xml" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <?xml-stylesheet type="text/xsl" href="xslt/ajax-s-html.xml"?> <ajax-s> <pages> <page> <br/> <br/> <h2>${top_title}</h2> <h3>${top_desc}</h3> <h4><span class="red">»</span> ${top_author}</h4> </page> <c:forEach items="${rows}" var="row"> <page> <h2>${row['title']}</h2> <dl> <c:out value="${row['slide_list']}" escapeXml="false"/> </dl> <c:if test="${row['example_url'] != ''}"> <p style="text-align: right"><a target="__newwin" href="${row['example_url']}">e.g. <span class="red">»</span></a></p> </c:if> </page> </c:forEach> </pages> </ajax-s>
DB Query Bean
import re import string import com.ziclix.python.sql as sql class just: def sql(self, skewl): description, results = self.query(skewl) cols = [] final = {} final['rows'] = [] final['columns'] = [] for i in description: cols.append(i[0]) for i in results: row = list(i) r = {} count = 0 for c in row: r[cols[count]] = c count = count + 1 final['rows'].append(r) final['columns'] = cols return final def query(self, q): dburl, user, pw, drv = ("jdbc:postgresql://localhost:5432/roo","*****","*****","org.postgresql.Driver") db = sql.zxJDBC.connect(dburl, user, pw, drv) cursor = db.cursor() cursor.datahandler = sql.handler.PostgresqlDataHandler(cursor.datahandler) cursor.execute(q) columns = cursor.description results = cursor.fetchall() return (columns, results)
Posted by pj at 03:05 PM | Comments (0)
February 22, 2012
Request forwarding to JSP from Jython
Using JSP for HTML layout for a Jython ServletPosted by pj at 04:35 PM | Comments (0)
November 25, 2011
Jython and Django Trial
# cd /Users/paulhollands/jython2.5.2/bin
# django-admin.py startproject dss
# jython manage.py runserver
Validating models...
0 errors found
Django version 1.3.1, using settings 'dss.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[25/Nov/2011 23:00:47] "GET / HTTP/1.1" 200 2045
Posted by pj at 11:02 PM | Comments (0)
October 28, 2011
Jython and Django
Chapter 14: Web Applications With Django — Jython Book v1.0 documentation
Posted by pj at 10:00 PM | Comments (0)
March 15, 2009
My Jython Regex Servlet
The servlet:
from javax.servlet.http import HttpServlet import re import string class regexTest(HttpServlet): def doGet(self,request,response): self.doPost (request,response) def doPost(self,request,response): #param_names = request.getParameterNames() writer = response.getWriter() response.setContentType ("text/plain") try: expr = request.getParameterValues("expr")[0] except: final_hash = { "errors" : ['']} final_hash['errors'][0] = 'You must enter an expression.' writer.println(final_hash) sys.exit try: this_text = request.getParameterValues("text")[0] except: final_hash = { "errors" : ['']} final_hash['errors'][0] = 'You must enter some text.' writer.println(final_hash) sys.exit reg = regexTest() try: final_hash = reg.test_it(expr, this_text) except: final_hash = { "errors" : ['']} final_hash['errors'][0] = 'Failed to run test.' writer.println(final_hash) sys.exit #except: writer.println('') #writer.println('') writer.println(final_hash) #def __init__(self, text="Stuff"): # self.text = text def test_it(self, exp, text): final_hash = {} try: this_reg = re.compile(exp) except: final_hash['error'] = ['Your expression did not compile'] return final_hash #print this_reg this_match = this_reg.findall(text) final_hash["results"] = this_match if this_match: return final_hash else: final_hash['error'] = ['Your expression found no matches'] return final_hash #if __name__ == "__main__": # reg = regexTest() # print reg.test_it('[\d]+', 'These are words and phone 07590 574469')
The JSP with the JSON:
<%@ page contentType="text/html" %> <!-- %@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" % --> <html> <head> <link rel="stylesheet" href="styles.css" type="text/css" media="all"/> <script type="text/javascript" src="js/prototype.js"></script> <script type="text/javascript" src="js/set_date.js"></script> <script type="text/javascript"> function do_regex(){ if(($('text').value == '') || ($('regex').value == '')){ alert('You must enter some text and an expression'); return false; } var url = 'regexTest.py'; var params = '?text=' + escape($('text').value) + '&expr=' + escape($('regex').value); var myAjax = new Ajax.Request( url, { method: 'get', parameters: params, onComplete: show_response }); function show_response(this_request){ this_result = this_request.responseText; $('regex_here').value = this_result; } } </script> <title>Regular Expression Test Harness</title> </head> <body> <h2 style="margin-left: 1em;">Regex Test Harness</h2> <form action="#" method="post" style="width: 80%; margin: 2em; border: 1px solid #dcdcdc;"> <p style="margin-left: 1em;"> <label id="text_block_label" class="label_italic">Text <em class="astrix" id="text_mandatory" style="display: none;">*</em></label> <br/> <em id="text_outer"> <input type="text" name="text" id="text" class="four_c" value=""/> </em> </p> <p style="margin-left: 1em;"> <label id="regex_block_label" class="label_italic">Regex <em class="astrix" id="regex_mandatory" style="display: none;">*</em></label> <br/> <em id="regex_outer"> <input type="regex" name="regex" id="regex" class="four_c" value="" onblur="do_regex()"/> </em> <input type="button" value="Go»" class="button" onclick="do_regex()"/> </p> <form> <textarea style="height: 100px; width: 400px; margin: 1em; color: red;" id="regex_here"> </textarea> </form> </form> </body> </html>
Posted by pj at 10:01 PM | Comments (0)
March 09, 2009
Getting PyServlet and Jython working
After a couple of days of hairloss I put the following into the container web.xml:
<servlet> <servlet-name>PyServlet</servlet-name> <servlet-class>org.python.util.PyServlet</servlet-class> <param-name>python.home</param-name> <param-value>/usr/local/jython</param-value> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>PyServlet</servlet-name> <url-pattern>*.py</url-pattern> </servlet-mapping>
Also I had to link:
/usr/local/jython/Lib to /Library/Tomcat/Home/conf/common/lib/Lib
and do the same for my application lib directory.
Now my jylets work.
Posted by pj at 11:37 AM | Comments (0)
March 07, 2009
Jython Webapp Tutorial
Jython Webapp Tutorial - Part 1 - Writing Servlets in Jython
Posted by pj at 03:41 PM | Comments (0)
November 15, 2007
Jython FTP Client
I've lashed together the following in Jython:
To compile:
/Users/paulhollands/jython2.2.1/jythonc -j ftp_upload.jar --all ftp_upload.py
Posted by pj at 05:09 PM | Comments (0)
May 23, 2006
Jython servlet version of AsciiDammit
I've turned AsciiDammit.py
into a Jython servlet using Netbeans and Coyote.
Get the source curlyQuoteParser.py or get the .war
Quote.war.
You'll need Jython 2.1 in /usr/local/jython-2.1
Posted by pj at 03:39 PM | Comments (0)
May 22, 2006
Coyote project rolls Jython support into Netbeans
Coyote: Dynamic language support in NetBeans
Watch out though. It breaks a projects web.xml
by adding multiple <context-param/>
nodes when you make the project Jython enabled.
This needs to be fixed in the XML by hand.
Posted by pj at 10:59 AM | Comments (0)
November 01, 2005
Tutorial about servlets in Jython
Jython Webapp Tutorial - Part 1 - Writing Servlets in Jython
Posted by pj at 08:45 PM
June 15, 2005
Eclipse and Jython
Apparently there are Jython plug-ins for Eclipse too:
Posted by pj at 01:09 PM