330 likes | 586 Views
Java without Java. Casey Durfee casey.durfee@spl.org CODI 2006. Why should I care?. You want to get things done …or you just want more time to goof off You know Horizon will never perfectly meet your library’s needs You don’t have $$$ for custom work
E N D
Java without Java Casey Durfee casey.durfee@spl.org CODI 2006
Why should I care? • You want to get things done • …or you just want more time to goof off • You know Horizon will never perfectly meet your library’s needs • You don’t have $$$ for custom work • You want to understand why software isn’t perfect • You want the bragging rights of having seen the geekiest presentation at CODI.
But I can’t… • Don’t sell yourself short! Plenty of other people will be happy to do it for you • Don’t worry about what you’re “supposed” to be able to do
Lack of Social Skills a Plus! • Be lazy and easily annoyed; take it personally • Lazy: always look for an easier way • Easily annoyed: If something doesn’t work right, don’t just learn to ignore it! • Take it personally: If you don’t fix it, nobody will • Don’t take any guff: It’s just a computer. Don’t forget who’s boss • Laziness, impatience, hubris (the 3 Perl virtues)
What’s an API? • Tools to interface with someone else’s software • Examples • Flickr, Google, Amazon, etc. • Horizon APIs will make it easier to extend Horizon without knowing too much about how it works behind the scenes
Intro to Java • The Platform (great) • OS independent • Fast • Powerful • 3rd party support (good) • Lots of stuff you can use • Isn’t going anywhere
Intro to Java (continued) • The language (ehh…) • Wordy • Fussy • Complex • Steep learning curve • Good for engineers • The programmers ($$$)
The Virtual Machine, II • Java is translated into platform-independent instructions for a Virtual Machine first public class helloWorld extends java.lang.Object{ public helloWorld(); Code: 0: aload_0 1: invokespecial #1; //Method java/lang/Object."<init>":()V 4: return public static void main(java.lang.String[]); Code: 0: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream; 3: ldc #3; //String Good morning 5: invokevirtual #4; //Method java/io/PrintStream.println:(Ljava/lang/Str ing;)V 8: return } • Write Once, Run Anywhere (OS independent)
What that Means • Java is a platform • Java is a language • You can use the platform without the language • You can program in Java without programming in Java
Java Example • Say good morning public class goodMorning { public static void main( String[] args ) { System.out.println(“Good morning”); } } • Ugh… why can’t I just do print “Good morning”
Java example II import javax.mail.*; import javax.mail.internet.*; import java.util.Properties; public class sendEmail { public static void emailSender() { Properties properties = System.getProperties(); properties.put("mail.smtp.host", "mail1.spl.org"); Session session = Session.getInstance( properties, null ); InternetAddress toAddress = null; Address fromAddress = null; try { toAddress = new InternetAddress( "casey.durfee@spl.org", "Casey Durfee" ); fromAddress = new InternetAddress("test@spl.org", "SPL TEST"); } catch (Exception e ) { e.printStackTrace(); System.exit(1); } try { MimeMessage mimeMessageOn = new MimeMessage(session); mimeMessageOn.setFrom(fromAddress); mimeMessageOn.setSubject( "Java test" ); mimeMessageOn.setText( "Isn't java fun?" ); mimeMessageOn.addRecipient(Message.RecipientType.TO, toAddress); Transport.send( mimeMessageOn ); } catch( Exception e ) { e.printStackTrace(); } } public static void main(String[] args ){ emailSender(); } }
There’s got to be an easier way • Java: 38 lines, 894 characters! • Hard to remember all that stuff • Still easier than serials prediction patterns • Sending an email is not rocket science! (See: your spam folder) • This should take 4 lines, tops. • Tell it we wanna send an email • Get a connection to the email server • Send the email • Close the connection to the server
An Easier Way • Sending an email in 4 lines… import smtplib server = smtplib.SMTP('mail1.spl.org') server.sendmail( "test@spl.org", ["casey.durfee@spl.org"], "From: test@spl.org\r\nTo: casey.durfee@spl.org\r\n\r\nSubject:Isn't java not fun?") server.close() • That may seem like gibberish but at least there’s less of it
Python and Ruby • Versatile, easy to use languages • Come with great tools for building websites (Ruby on Rails, Django) • Popular with the kids • Simple and compact • Will be around for a while
Jython and JRuby • Generate java bytecode without you programming in Java • Java virtual machine doesn’t know or care that you didn’t write it in Java • Can use Java libraries and tools without writing any Java • Much easier to learn and use than Java
Other JVM languages • Groovy (complex, weird) • Rhino (javascript) • NetRexx ( Rexx ) • Nice (Slightly less annoying version of Java) • Quercus (PHP, closed source, can't use java within PHP) • ColdFusion MX
Which should I choose? • Pick between Python and Ruby first • Neither one is a bad choice • Neither one will cost you a dime • I like them both • …but I’m more productive with Python • ...and Python's a lot simpler (less to remember)
Quick Jython Example 1 • Let's make a graphical user interface: # jython from java.lang import * from javax.swing import * window = JFrame("jython demo") button = JButton("hello world") window.contentPane.add( button ) window.pack() window.show() #jruby require 'java' include_class ['javax.swing.JFrame', 'javax.swing.JButton'] window = JFrame.new "JRuby Demo" button = JButton.new "hello world" window.contentPane.add button window.pack window.show
Reading a MARC record (using marc4j) jython >>> from org.marc4j import * >>> from java.io import * >>> inStream = FileInputStream("spl.marc") >>> marcReader = MarcStreamReader( inStream ) >>> marcRecord = marcReader.next() >>> print marcRecord LEADER 01265nam 2200337 a 4500 001 ocm62127695 003 OCoLC 005 20060817030408.0 008 050921s2006 nyu c 000 1 eng 010 $a 2005027306 020 $a0316057533 (trade pbk.) 024 3 $a9780316057530 040 $aDLC$cDLC$dBAKER$dUOK 042 $alcac ... jruby require 'java' include_class ['org.marc4j.MarcStreamReader', 'java.io.FileInputStream'] inStream = FileInputStream.new "spl.marc" marcReader = MarcStreamReader.new inStream marcRecord = marcReader.next p marcRecord LEADER 01265nam 2200337 a 4500 001 ocm62127695 003 OCoLC 005 20060817030408.0 008 050921s2006 nyu c 000 1 eng 010 $a 2005027306 020 $a0316057533 (trade pbk.) 024 3 $a9780316057530 040 $aDLC$cDLC$dBAKER$dUOK 042 $alcac ...
Z39.50 query w/Jython (using Jafer) Does a Z39.50 query and print out results as XML. from org.jafer.zclient import * from org.jafer.util.xml import DOMFactory, XMLSerializer from org.jafer.query import * from java.lang import * from java.io import StringWriter z = ZClient() z.setHost("z3950.loc.gov") z.setPort(7090) query = QueryBuilder() numHits = z.submitQuery( query.getNode("author", "Durfee")) z.setRecordCursor(1) sw = StringWriter() XMLSerializer.out( z.getCurrentRecord().getXML(), "xml", sw ) z.close() print sw
Z39.50 Query results <?xml version="1.0" encoding="UTF-8" standalone="no"?> <mods xmlns="http://www.loc.gov/mods/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.loc.gov/mods/ http://www.loc.gov/standards/mods/mods.xsd"> <title>Analytic philosophy and phenomenology /</title> <name type="personal">Durfee, Harold A.1920-</name> <typeOfResource>text</typeOfResource> <genre> <controlledValue>bibliography</controlledValue> </genre> <publication> <placeOfPublicationCode authority="marc">ne </placeOfPublicationCode> <placeOfPublication>The Hague :</placeOfPublication> <publisher>Nijhoff,</publisher> <issuance>monographic</issuance> </publication> <date type="issued">1976.</date> <language authority="iso 639-2b">eng</language> <formAndPhysicalDescription> <extent>viii, 277 p. ;24 cm.</extent> </formAndPhysicalDescription> <note>Includes index.</note> ...
Less Quick Jython Example • Let’s create a report of circulation statistics and email it out as an Excel spreadsheet • We’ll use a couple of java tools to make our lives easier • Spring (http://www.springframework.org/ ) for database connection • POI (http://jakarta.apache.org/poi/ ) to generate spreadsheet • SPL-developed convenience functions • Same # of lines as Java email program
from spl.Horizon import DBWrapper from spl.misc import poi from spl.email import easyEmailSender import time conn = DBWrapper.DBWrapperFromProperties("horizon") checkoutsAndRenewalsQuery = """select sum(total) from stat_summary where location in ( '%(location)s' ) and stat_category = 'cko' and year = %(year)d and month = %(month)d and day = %(day)d""" checkinsQuery = """select sum(total) from stat_summary where location in ('%(location)s') and stat_category = 'cki' and year = %(year)d and month = %(month)d and day = %(day)d""" newBorrQuery = """select sum(total) from stat_summary where location in ('%(location)s') and stat_category = 'bordel' and year = %(year)d and month = %(month)d and day = %(day)d and stat_subcategory in ( '1', '3')""" LOCATIONS_TO_RUN_FOR = [ 'bea', 'bal', 'cen'] results = [ [ "Date", "Location", "Checkouts and Renewals", "Checkins", "New Borrowers"] ] date = time.strftime("%m-%d-%Y") month,day,year = date.split("-") for locationOn in LOCATIONS_TO_RUN_FOR: params = { 'location' : locationOn, 'year' : year, 'month' : month, 'day' : day } numCheckouts = conn.queryForInt( checkoutsAndRenewalsQuery % params ) numCheckins = conn.queryForInt( checkinsQuery % params ) numNewBorrowers = conn.queryForInt( newBorrQuery % params ) results.append( [ date, locationOn, numCheckouts, numCheckins, numNewBorrowers] ) fileName = "spl-circ-stats-%s.xls" % date poi.writeSpreadsheet( fileName , results ) sender = easyEmailSender.easyEmailSender("casey.durfee@spl.org", "Casey Durfee", "circ stats for %s" % date, "see attached spreadsheet" ) sender.setFileName( fileName, "statistics spreadsheet") sender.sendMessage()
Where do I go from here? • Learn Python or Ruby first • Even if you never use Jython/JRuby, it will be worth your time • Learn a little bit about Java • If only so you will know how good you have it • Don’t wait for the 8.0 APIs to be released
“At my local Barnes and Noble, there is a huge wall of Java books just waiting to tip over and crush me one day. And one day it will. At the rate things are going, one day that bookcase will be tall enough to crush us all. It might even loop the world several times, crushing previous editions of the same Java books over and over again.” --Why, Why’s (poignant) Guide to Ruby
Getting Started with Python • How to Think like a Computer Scientist Using Python (beginning) : http://www.ibiblio.org/obp/thinkCSpy/ • Dive Into Python (advanced) http://www.diveintopython.org/ • Learning Python (ISBN 0596002815 ) • Jython Essentials ( ISBN 0596002475 ) • http://www.jython.org
Getting Started With Ruby • Programming Ruby: The Pragmatic Programmers’ Guide : online at http://www.rubycentral.com/book/ (ISBN 0974514055 ) • Why’s (poignant) guide to Ruby : http://poignantguide.net/ruby/ • http://www.jruby.org
Useful Java APIs • Jafer (Z39.50): http://www.jafer.org • Marc4j (MARC reader): http://marc4j.tigris.org • POI (create MS Word/Excel files): http://jakarta.apache.org/poi