Berlin Brown's Weblog

All | General | Java

20061009 Monday October 09, 2006

Simple find a file name in python/jython

Through the use of python‘s glob library, this simple script mimics the ‘find‘ operation. Customize to your liking.

Example Results:

scanning=* ./\sql\ums\
scanning=* ./\sql\uw\

application parameters= ./ = *.txt
Number of files= 9
Reporting All Files:
./\conf\orig\x\ca\xtemp.txt
./\conf\orig\y\ca\AimdnldDesc.txt
./\conf\orig\y\ca\xtemp.txt
./\htdocs\ca\map\temp.txt
done

Recursive Glob in Python

Posted by berlinbrown ( Oct 09 2006, 05:32:38 PM EDT ) Permalink Comments [0]

20061003 Tuesday October 03, 2006

Jython, Struts, and Hibernate

While not yet published yet and still a little rough. here is a short article on creating CRUD based webapplications with Jython and Struts/HBM. Seamless integration of the technology.

Enjoy.

Wiki - Jython Web Application Development

Posted by berlinbrown ( Oct 03 2006, 04:47:34 PM EDT ) Permalink Comments [0]

20060928 Thursday September 28, 2006

Another jython example, with struts, hibernate and websphere

9/22/2006

Example Projects with Struts, Jython, Websphere

The following example presents source code with emphasis on
a couple of J2EE/Java areas.

- Example using Jython within a J2EE Framework, Application environment - Example tested with Websphere

To Run
You will need a J2EE Application Server or Servlet Container (Tomcat will work, but you might need to edit the jython code)

1. Download the libraries below.
2. Create the database (see the ‘db‘) directory

Why?

- Because Jython is nice to work with - Because Struts is nice to work with and the practices and patterns
have been tested thoroughly among the development community - Because Hibernate is nice to work with and the practices and patterns
have been tested thoroughly among the development community - Websphere, because it is fast and made by IBM

For Websphere 5.1.2

Because of the classloader issues; you need to export the hibernate ‘beans‘ within
a separate jar file while you can put everything else in the WAR file.

Place the bean jar file:

C:\Program Files\IBM\WebSphere Studio\Application Developer\v5.1.2\runtimes\base_v51\lib\app
In addition; copy to the web archive. So you will have to copies of the
bean jars out there. One is to appease jython, the other is to make Websphere
load the beans properly for hibernate.

Required

You must downloaded the following libaries; Hibernate/Struts/Jython
before running. The full list of libraries are included in the WEB-INF/lib
directory.

Just place them in the /WEB-INF/lib directory.

(email at berlin.brown at gmail.com for more info)

Full Source

Full Description and Source

Posted by berlinbrown ( Sep 28 2006, 02:03:20 AM EDT ) Permalink

20060925 Monday September 25, 2006

Jython and Struts

A very simple set of examples on using jython and struts:

Jython and Struts
Also read up on the web-application combination jy/struts/hiberate/websphere

Posted by berlinbrown ( Sep 25 2006, 07:38:43 PM EDT ) Permalink

Geek moments, dealing with Class loader issues

After a lot of research, there are four ways to fix classloader issues. One; wait for the next release. Two; get into the ins/outs of your particular appserver and pay vendor support for the solution. Three; write your own classloader. Four; my favorite, reflection.

Reflection is what I used to fix a classloading issue. It is probably bad code, but it works:

Object objJyPlugin = context.getAttribute(JythonUtilPlugin.PLUGIN_NAME_KEY);
log.info("Jy Executing=");
// Get the python interpreter, reflection code added due to classloading issues.
Class clJy1 = objJyPlugin.getClass().getClassLoader().loadClass("org.spirit.util.JythonUtilPlugin");
Method m = clJy1.getMethod("getInterpreter", null);
log.info("Method: " + m);
PythonInterpreter interp = (PythonInterpreter) m.invoke(objJyPlugin, null);
log.info(">>> Interpreter=" + interp);
Method m2 = clJy1.getMethod("getInternalName", null);
String intName = (String) m2.invoke(objJyPlugin, null);
log.info(">>> InternalName =" + intName);
Posted by berlinbrown ( Sep 25 2006, 06:10:32 PM EDT ) Permalink

20060924 Sunday September 24, 2006

More jython and midi creation

This is an update to my earlier post. Basically, I compacted things a little. Now, we can take an input midi file; extract the pitch information and output to a file that only has C/D/E/F/G/B ..whatever key note information and then play to midi output.

Jython Code Collection - see top on midi creation

Posted by berlinbrown ( Sep 24 2006, 12:39:16 AM EDT ) Permalink

20060923 Saturday September 23, 2006

More Jython Scripts (mid creation)
##
## Berlin Brown
## 9/22/2006
## Midi playing with java, jython, and jfugue
##
## Put jfugue.jar in your classpath and run accordingly
##
## Example.mid midi file will get created
##
from org.jfugue import *
from java.lang import System
import random
def frere_jacques():
    player = Player()
    # "Frere Jacques"
    pattern1 = Pattern("C5q D5q E5q C5q")
    # "Dormez-vus?"
    pattern2 = Pattern("E5q F5q G5h")
    # "Sonnez les matines"
    pattern3 = Pattern("G5i A5i G5i F5i E5q C5q")
    # "Ding ding dong"
    pattern4 = Pattern("C5q G4q C5h")
    # Put it all together
    song = Pattern()
    song.add(pattern1)
    song.add(pattern1)
    song.add(pattern2)
    song.add(pattern2)
    song.add(pattern3)
    song.add(pattern3)
    song.add(pattern4)
    song.add(pattern4)
    # Play the song!
    player.play(song)
    player.save(song, "example.mid")
    # End of Method
if __name__ == '__main__':
    print "running"
    frere_jacques()
    player = Player()
    pattern = Pattern("C D E F G A B")
    player.play(pattern)
    note_lookup = []
    note_lookup.append("C")
    note_lookup.append("D")
    note_lookup.append("E")
    note_lookup.append("F")
    note_lookup.append("G")
    note_lookup.append("A")
    note_lookup.append("B")
    print "Total Notes loaded >> ", len(note_lookup)    
    for n in range(20):
        all_notes = []
        for n in range(len(note_lookup)):
            note = random.choice(note_lookup)
            all_notes.append(note)
        note_str ='i '.join(all_notes)
        print "Playing >> %s" % note_str
        # Place the sequence
        pattern = Pattern(note_str)
        player.play(pattern)
    System.exit(0)
    print "done"
## End of the File

See More Here with the Jython Collection

Posted by berlinbrown ( Sep 23 2006, 01:24:00 AM EDT ) Permalink

20060921 Thursday September 21, 2006

Simplest Jython based Servlet Web Application

If you really want to throw together servlet code but don‘t want to go through the hassle of writing J2EE Enterprise, MVC2 systems; I really recommend investigating jython.

Basically, in 10 minutes you can write a jython oriented servlet. For example; this code was tested with websphere:

More Info

External Site, Sean McGrath Web Application

Java Setup Utility Code
/*
* Original Created on Mar 21, 2005
*
* $Id$
*
* Author: Berlin Brown
*
* Original Package: org.spirit.jy
* Original Project: JyNetwork
* 2:59:25 PM
*
* Revisions:
*
* <del>-</del>-------  <del>-</del>----------------
* 9/21/2006Revisiting Application
*
*/
package org.spirit.jy;
import ../../page/java.io.IOException.css;
import ../../page/java.io.File.css;
import ../../page/java.util.Enumeration.css;
import ../../page/javax.servlet.ServletException.css;
import ../../page/javax.servlet.ServletContext.css;
import ../../page/javax.servlet.http.HttpServlet.css;
import ../../page/javax.servlet.http.HttpServlet.cssRequest;
import ../../page/javax.servlet.http.HttpServlet.cssResponse;
import ../../page/org.apache.commons.logging.Log.css;
import ../../page/org.apache.commons.logging.Log.cssFactory;
import ../../page/org.python.util.PythonInterpreter.css;
import ../../page/../../page/org.python.core.Py.cssSystemState.css;
import ../../page/org.python.core.Py.css;
import ../../page/org.python.core.Py.cssException;
import ../../page/org.python.core.Py.cssString;
import ../../page/java.util.Properties.css;
import ../../page/java.util.Hashtable.css;
import ../../page/java.io.PrintWriter.css;
/**
* Python Servlet Setup Utilities;  Setup your web application
* environment for use with jython.
*
* This application was tested with WSAD 5.1.2.  Make sure that you created
* a dynamic web-application project such that you have the following directory
* structure (modify for your appropriate Application Server):
*  JavaSource
* org.spirit.jy
* NewPyServlet.java
*  WebContent
* <em></em> META-INF
* <em></em> WEB-INF
* <i></i> classes
* <i></i> lib
* web.xml
* SimpleAction.py (at root in WebContent directory)
*
* <p><b>External Dir Structure Needed (jython/python home)</b>
*  <p>
*  python.home = C:/projects2/Downloads5/jy
*  contains 'jython.jar'
*
* @author berlin.brown
*
*/
public class NewPyServlet extends HttpServlet {
private static Log logger = LogFactory.getLog(NewPyServlet.class.getName());
private PythonInterpreter interp;
private Hashtable cache = new Hashtable();
private String rootPath;
/**
* Hardcoded absolute path to your JYTHON home
*/
private String PY_HOME_ABSOLUTE  = "C:/projects2/Downloads5/jy";
///==============================================================
///
/// <b> Methods </b>
///
///==============================================================
public void init() {
rootPath = getServletContext().getRealPath("/");
if (!rootPath.endsWith(File.separator))
rootPath += File.separator;
Properties props = new Properties();
// Context parameters
ServletContext context = getServletContext();
Enumeration e = context.getInitParameterNames();
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
props.put(name, context.getInitParameter(name));
} /// end of the while //
// Config parameters
e = getInitParameterNames();
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
props.put(name, getInitParameter(name));
} /// end of while
if ((props.getProperty("python.home")  null) && (System.getProperty("python.home") </notextile> null)) {
//props.put("python.home", rootPath <ins> "WEB-INF" </ins> File.separator + "lib");
props.put("python.home", PY_HOME_ABSOLUTE);
} // end of if
PythonInterpreter.initialize(System.getProperties(), props, new String[0]);
reset();
PySystemState sys = Py.getSystemState();
PySystemState.add_package("javax.servlet");
PySystemState.add_package("javax.servlet.http");
PySystemState.add_package("../../page/javax.servlet.js");
PySystemState.add_package("../../page/javax.servlet.js.tagext");
PySystemState.add_classdir(rootPath <ins> "WEB-INF" </ins> File.separator + "classes");
// May be deprecated
// PySystemState.add_extdir(rootPath <ins> "WEB-INF" </ins> File.separator + "lib", true);
PySystemState.add_extdir(rootPath <ins> "WEB-INF" </ins> File.separator + "lib");
} /// end of the method //
public void reset() {
interp = new PythonInterpreter(null, new PySystemState());
cache.clear();
PySystemState sys = Py.getSystemState();
sys.path.append(new PyString(rootPath));
String modulesDir = rootPath <ins> "WEB-INF" </ins> File.separator + "jython";
sys.path.append(new PyString(modulesDir));
} /// end of the method //
///
/// Get and Post Methods
///
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
} /// end of the method //
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String spath = ((HttpServletRequest) request).getServletPath();
if (spath  null || spath.length() </notextile> 0) {
spath = ((HttpServletRequest) request).getPathInfo();
} /// end of the if //
try {
///
/// This will get calling servlet name
/// For now assume, the root directory is webapps/ROOT
///
String rpath = getServletContext().getRealPath(spath);
String rootPath = getServletContext().getRealPath("/");
interp.execfile(rootPath <ins> "/" </ins> "SimpleAction.py");
interp.set("req", request);
interp.set("res", response);
interp.exec("simpl = SimpleAction()");
interp.exec("simpl.doPost(req, res)");
} catch (PyException e) {
logger.error(e);
throw new ServletException("## ERR ## Could not create " <ins> "Jython servlet - " </ins> e.getMessage());
} /// end of the try - catch //
} /// end of the method //
} /// end of the class //
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app id="WebApp">
<display-name>webtest</display-name>
<servlet>
<servlet-name>NewPyServlet</servlet-name>
<display-name>NewPyServlet</display-name>
<servlet-class>org.spirit.jy.NewPyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestReconnectServlet</servlet-name>
<url-pattern>/TestReconnectServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>TestWeb</servlet-name>
<url-pattern>/TestWeb</url-pattern>
</servlet-mapping>
</web-app>
Posted by berlinbrown ( Sep 21 2006, 05:21:16 PM EDT ) Permalink

20060730 Sunday July 30, 2006

Java developers have fun in Atlanta

I wrote some quick reviews of some local clubs/bars in Atlanta. Check them out here and then google them.

atlanta-one-line-bar-review-for-major.html

Posted by berlinbrown ( Jul 30 2006, 07:28:31 PM EDT ) Permalink

20060619 Monday June 19, 2006

Rails Application Source Released

I want to discuss it a little more but, the botverse application is released under a lesser-gnu license:

http://www.newspiritcompany.com/botverse_src.html

Posted by berlinbrown ( Jun 19 2006, 09:01:22 PM EDT ) Permalink