=======================================================================
Packages and Jar Files                                         May 2006
=======================================================================

Java provides a number of mechanims for organizing classes into
packages and then making the available for use via jar files.

Packages in Java
---------------------

A package is simply a group of classes. Packages are a convenient
mechansim for organizing code and, in the case or team development
of code, separating the work of one developer from another.

Package and Files
---------------------

All of the source code files in a package must be located in a 
subdirectory that matches the full name of the package. For
example, source code files in the sub-directory 

     computer/

are put in the package computer. Simple put the statement

     package computer;

before the first executable statement in each source code file.
Similarly, files in computer/old would have the package name

     package computer.old;

Thus a hierarchy of directories will store a hierarchy of 
packages.

Note. To keep package names unique, Sun recomments that package
names be organized according to the organization in which the
code is being developed. Suppose, for example, that we are 
developing a "graphics" package under the auspecies of 

    http://www.cee.umd.edu

The corresponding package name would be:

    package edu.umd.cee.graphics;

Setting the CLASSPATH
---------------------

In most applications the hierarchy of source code files will not
branch from the root directory. Therefore, we need to tell java
where to find the hierarchy of packages.

In UNIX, the PATH environmental variable contains a list of
directories that will be searched to find an appropriate file.
The CLASSPATH environemt variable is to Java what PATH
is to UNIX.

In UNIX/Linux, you can explicitly type:

 setenv CLASSPATH /User/austin/ence200.d/java.d/package-and-jar.d/

or
 
 setenv CLASSPATH $PWD

For situations where packages are located in multiple subdirectory
hierarchies, a list of paths can be specified. Suppose, for example,
the directories are:

    /User/austin/project1
    /User/austin/project2

The appropriate command is:

 setenv CLASSPATH /User/austin/project1:/User/austin/project2

Directories are separated by a colon(:) in UNIX, a semi-colon (;)
in Windows.

Program Compilation
---------------------

With the CLASSPATH in place, simply type:

    javac *.java

and the source code files will be compiled.

Hints for Class Design
----------------------

1. Keep data private. This ensure that two variables with
   the same name, but in different packages will not have any
   unintended interactions.

==============================================================
Example 1. Apples: Fruit and Computers
=============================================================

Let's consider a program that draws upon classes in two
packages. The directory and source code file names are:

Package                  Directory and Source Code
--------------------------------------------------
Base directory
        package fruit 
                         /fruit/Apple.java
                         /fruit/Orange.java
        package computer 
                         /computer/Apple.java
--------------------------------------------------

The details of Apple.java and Orange.java are as follows:

/*
 *  ===================================================
 *  Apple.java: An apple is a piece of fruit...
 *  ===================================================
 */ 

package fruit;

public class Apple {

      // Constructor

      public Apple() {}

      // Return description the fruit...

      public String toString() {
         String s = "An Apple is a type of Fruit!!!";
         return s;
      }

      public static void main ( String [] args ) {
         Apple a = new Apple();
         System.out.println( a );
      }
}

/*
 *  ===================================================
 *  Orange.java: An orange is a piece of fruit...
 *  ===================================================
 */ 

package fruit;

public class Orange {

      // Constructor

      public Orange() {}

      // Return description the fruit...

      public String toString() {
         String s = "An Orange is a type of Fruit!!!";
         return s;
      }

      public static void main ( String [] args ) {
         Orange a = new Orange();
         System.out.println( a );
      }
}

For the computer package, Apple.java contains:

/*
 *  ===================================================
 *  Apple.java: Apple is a computer company ....
 *  ===================================================
 */ 

package computer;

public class Apple {

      // Constructor

      public Apple() {}

      // Return description the fruit...

      public String toString() {
         String s = "Apple is a computer company!!!";
         return s;
      }

      public static void main ( String [] args ) {
         Apple a = new Apple();
         System.out.println( a );
      }
}

The key point here is the Apple.java appears in both packages!
Finally, we have a test program that imports both packages
and then calls methods in the appropriate classes.

Here are the test program details:

/*
 *  ===================================================
 *  TestApple.java: The Apple Test program ....
 *  ===================================================
 */ 

import fruit.*;
import computer.*;

public class TestApple {
      public static void main ( String [] args ) {

         // Create an apple using the complete path name...

         fruit.Apple a = new fruit.Apple();
         System.out.println( a );

         // Create an orange using the abbreviated path name.

         Orange or = new Orange();
         System.out.println( or );

         // Create an apple computer object .....

         computer.Apple c = new computer.Apple();
         System.out.println( c );
      }
}

==============================================================

Program Compilation
---------------------

To compile the program, first we set the classpath: 

   setenv CLASSPATH $PWD

Then simply type:

   javac TestApple.java

The files before and after compilation are as follows:

   Before Compilation              After Compilation
   -------------------------------------------------
   TestApple.java                     TestApple.java
   fruit/Apple.java                 fruit/Apple.java
   fruit/Orange.java               fruit/Orange.java
   computer/Apple.java           computer/Apple.java
                                     TestApple.class
                                   fruit/Apple.class
                                  fruit/Orange.class
                                computer/Apple.class
   -------------------------------------------------

Notice that the import statements

  import fruit.*;
  import computer.*;

in TestApple.java allow the java compiler to find and
compile the Apple.java and Orange.java source code 
files in directories fruit and computer.

Running the program
---------------------

   java TestApple


=======================================================================
Jar Files
=======================================================================

A JAR file is simply a ZIP file that contains classes, possibly 
other files that a program may need (e.g., image and sound files),
and a manifest file describing the special features of the archive.

All of these files can be downloaded with a single HTTP request to the
the server. Use of the ZIP compression format reduces the download
time.

Creating Jar files
---------------------------------

The most common command for creating a new JAR file has the format:

    java cvf NameOfJARFile File1 File2 File3 ....

The "cvf" command line argument says:

   1. We wish to create (c) a JAR file.
   2. We wish the command to be verbose (v).
   3. We are designating the filename of the JAR file.

Example 1. From the base directory 

    java cvf Fruit.jar fruit/Apple.class fruit/Orange.class

creates a the JAR file Fruit.jar. An equivalent command is

    java cvf Fruit.jar fruit/*.class

In either case, the output is:

Script started on Sat May  6 13:50:53 2006
prompt >>
prompt >> jar cvf Fruit.jar fruit/Apple.class fruit/Orange.class
added manifest
adding: Apple.class(in = 537) (out= 352)(deflated 34%)
adding: Orange.class(in = 540) (out= 352)(deflated 34%)
prompt >>
prompt >> exit
Script done on Sat May  6 13:51:31 2006

Inspecting the Contents of a JAR File
-------------------------------------

The syntax for inspecting the contents of the JAR file is:

    jar tvf NameOfJARFile 

Here the command line options "vf" are as previously explained.
The command line option "t" indicates that we want to see the
table of contents for the jar file. e.g.,

    jar tvf Fruit.jar

produces the output:

Script started on Sat May  6 13:57:49 2006
prompt >>
prompt >> jar tvf Fruit.jar
     0 Sat May 06 13:51:24 EDT 2006 META-INF/
    70 Sat May 06 13:51:24 EDT 2006 META-INF/MANIFEST.MF
   537 Fri May 05 18:39:14 EDT 2006 Apple.class
   540 Fri May 05 18:39:14 EDT 2006 Orange.class
prompt >>
prompt >> exit
Script done on Sat May  6 13:58:07 2006

Using the code within a JAR file
-------------------------------------

To use the code within a jar file we follow the syntax:

   java -cp path-to-the-jar-file class-containing-the-main-method

Example. For our fruit application, both the Apple and Orange classes
have main methods. Now suppose that the Fruit.jar file is moved to
a bin directory (i.e., relative to the base directory, the JAR file
is located in bin/Fruit.jar). To run the class file from the base
directory

   java -cp bin/Fruit.jar Apple.class

Extracting the Contents from a JAR file
---------------------------------------

Syntax:

   java xvf NameOfTarFile

Example.

   java xvf Fruit.jar

prompt >>
prompt >> jar xvf Fruit.jar
  created: META-INF/
extracted: META-INF/MANIFEST.MF
extracted: Apple.class
extracted: Orange.class
prompt >>

The MANIFEST.MF file is located in the META-INF sub-directory.

JAR Files as Applications
------------------------------------------

You can run JAR-packaged applications with the Java interpreter.
The basic command is:

   prompt >> java -jar jar-file

The -jar flag tells the interpreter that the application is
packaged in the JAR file format. You can only specify one JAR file,
which must contain all the application-specific code.
Before this command will work, however, the runtime environment
needs to know which class within the JAR file is the
application's entry point.

To indicate which class is the application's entry point,
you must add a Main-Class header to the JAR file's manifest.
The header takes the form:

Main-Class: classname

The header's value, classname, is the name of the class that's
the application's entry point.

Example.

The contents of mainclass.mf are:

1. Main-Class: fruit.Apple
2.

It's important to have a black line in mainclass.mf
Now, type:

prompt >> jar cmf mainclass.mf Fruit.jar fruit/*.class
prompt >> java -jar Fruit.jar
An Apple is a type of Fruit!!!
prompt >> 

=======================================================================
References

1. Horstmann C., Core Java: Volume 1-Fundamentals. (Version  1.4),
   Prentice-Hall, 2003.

=======================================================================

