Java Writing Library Files

sys.path.insert 0, usrlocalapachelibpython import MySQLdb import Cookbook conn = Cookbook.connect print Connected conn.close print Disconnected sys.exit 0 Anot her way t o t ell Pyt hon where t o find m odule files is t o set t he PYTHONPATH environm ent variable. I f you set t hat variable t o include your m odule direct ory, script s t hat you run need not m odify sys.path . I t s also possible t o im port individual sym bols from a m odule using a from st at em ent : from Cookbook import connect This m akes t he connect rout ine available t o t he script wit hout t he need for t he m odule nam e, so youd use it like t his: conn = connect

2.4.7 Java

Java library files are sim ilar t o Java program s in m ost ways: • The class line in t he source file indicat es a class nam e. • The file should have t he sam e nam e as t he class wit h a .j ava ext ension . • You com pile t he .j ava file t o produce a .class file. However, unlike regular program files, Java library files have no main funct ion. I n addit ion, t he file should begin wit h a package ident ifier t hat specifies t he locat ion of t he class wit hin t he Java nam espace. A com m on convent ion is t o begin package ident ifiers wit h t he reverse dom ain of t he code aut hor; t his helps m ake ident ifiers unique and avoid conflict wit h classes writ t en by ot her aut hors. [ 2] I n m y case, t he dom ain is kit ebird.com , so if I w ant t o writ e a library file and place it under mcb wit hin m y dom ains nam espace, t he library should begin w it h a package st at em ent like t his: [ 2] Dom ain nam es proceed right t o left from m ore general t o m ore specific wit hin t he dom ain nam espace, whereas t he Java class nam espace proceeds left t o right from general t o specific. Thus, t o use a dom ain as t he prefix for a package nam e wit hin t he Java class nam espace, it s necessary t o reverse it . package com.kitebird.mcb; Java packages developed for t his book will be placed wit hin t he com.kitebird.mcb nam espace t o ensure t heir nam ing uniqueness. The following library file, Cookbook.j ava, defines a Cookbook class t hat im plem ent s a connect m et hod for connect ing t o t he cookbook dat abase. connect ret urns a Connection obj ect if it succeeds, and t hrows an except ion ot herwise. To help t he caller deal wit h failures, t he Cookbook class also defines getErrorMessage and printErrorMessage , ut ilit y rout ines t hat ret urn t he error m essage as a st ring or print it t o System.err . Cookbook.java - library file with utility routine for connecting to MySQL package com.kitebird.mcb; import java.sql.; public class Cookbook { Establish a connection to the cookbook database, returning a connection object. Throws an exception if the connection cannot be established. public static Connection connect throws Exception { String url = jdbc:mysql:localhostcookbook; String user = cbuser; String password = cbpass; Class.forName com.mysql.jdbc.Driver.newInstance ; return DriverManager.getConnection url, user, password; } Return an error message as a string public static String getErrorMessage Exception e { StringBuffer s = new StringBuffer ; if e instanceof SQLException JDBC-specific exception? { print general message plus any database-specific message s.append Error message: + e.getMessage + \n; s.append Error code: + SQLException e.getErrorCode + \n; } else { s.append e + \n; } return s.toString ; } Get the error message and print it to System.err public static void printErrorMessage Exception e { System.err.println Cookbook.getErrorMessage e; } } The rout ines wit hin t he class are declared using t he static keyword, which m akes t hem class m et hods rat her t han inst ance m et hods. That s because t he class is used direct ly rat her t han by creat ing an obj ect from it and invoking t he m et hods t hrough t he obj ect . To use t he Cookbook.j ava file, com pile it t o produce Cookbook.class, t hen inst all t he class file in a direct ory t hat corresponds t o t he package ident ifier. This m eans t hat Cookbook.class should be inst alled in a direct ory nam ed com kit ebird m cb or com \ kit ebird\ m cb under Windows t hat is locat ed under som e direct ory nam ed in your CLASSPATH set t ing. For exam ple, if CLASSPATH includes usr local apache lib j ava under Unix, you could inst all Cookbook.class in t he usr local apache lib j ava com kit ebird m cb direct ory. See Recipe 2.2 for m ore inform at ion about t he CLASSPATH variable. To use t he Cookbook class from wit hin a Java program , you m ust first im port it , t hen invoke t he Cookbook.connect m et hod. The following t est harness program , Harness.j ava, shows how t o do t his: Harness.java - test harness for Cookbook library class import java.sql.; import com.kitebird.mcb.Cookbook; public class Harness { public static void main String[ ] args { Connection conn = null; try { conn = Cookbook.connect ; System.out.println Connected; } catch Exception e { Cookbook.printErrorMessage e; System.exit 1; } finally { if conn = null { try { conn.close ; System.out.println Disconnected; } catch Exception e { String err = Cookbook.getErrorMessage e; System.out.println err; } } } } } Harness.j ava also shows how t o use t he error m essage rout ines from t he Cookbook class when a MySQL- relat ed except ion occurs. printErrorMessage t akes t he except ion obj ect and uses it t o print an error m essage t o System.err . getErrorMessage ret urns t he error m essage as a st ring. You can display t he m essage yourself, writ e it t o a log file, or what ever.

2.5 Issuing Queries and Retrieving Results