Results 1 to 1 of 1
  1. #1
    Java Exam is offline Member
    Join Date
    Dec 2011
    Posts
    64
    Rep Power
    0

    Default Tutorial:Review of Java Packages and JAR Files for the Java Certificate Exam

    In this article, we will review Java packages and the JAR files used in applications and applets. We will look at how java classes are grouped into packages and then how all of the java classes are packed into JAR files for deployment. This is the final article of a series of articles to help you prepare for the java associate exam. If you have gone through the other twelve articles of this series, you should be fully prepared for the Java Associate Exam.

    Understanding Java Packages

    Java Packages are key to the organization of the standard classes as well as your programs. They influence the names that you are able to use for classes, the variables and the methods contained in the classes. A package is basically a uniquely named collection of classes. The primary reason for grouping classes within packages is to avoid possible name clashes with other classes when you are using prewritten classes in an application. The names used for classes in one package do not interfere with the names of classes in another package or your program due to the class names in a package all being qualified by the package name. Every class in Java is contained in a package, including all those you have defined in your programs. For example, the String class you have been using is in the java.lang package, so the full name of the class is java.lang.String. You have been able to use the unqualified name because all the classes in the java.lang package are always available in your program code; there's an implicit import statement in effect for all the names in the java. lang package.

    All of the standard classes in Java are contained within a set of packages, and each package contains classes that are related in some way. The package that contains most of the standard classes that you have used so far is called java.lang, so called because the classes in this package provide Java language–related support. You haven't seen any explicit reference to java.lang in your code either, because this package is automatically available to your programs. Things are arranged this way because some of the classes in java.lang, such as String, are used in every program. If you use a class from the other packages containing standard classes, you need either to use the fully qualified name of the class or to explicitly import the full class name into your program.

    Packaging Up Your Classes

    The purpose of discussing packages is because all of your classes are located within named packages. Just add a package statement as the first statement in the source file containing the class definition. This must always be the first statement. Only comments or blank Wings can precede the package statement. A package statement consists of the keyword package followed by the package name and is terminated by a semicolon. If you want the classes in a package to be accessible outside the package, you must declare the class using the keyword public in the first Wing of your class definition. Class definitions that aren't preceded by the keyword of public are accessible only from methods in classes that belong to the same package. An example is shown in the listing below:

    Java Code: Example of Class with Package Definition
    package Aircraft;
    	public class Wing {
// Details of the class definition
    }
    Each class that you want to include in the package Aircraft must contain the same package statement at the beginning, and you must save all the files for the classes in the package in a directory with the same name as the package Aircraft. Note the use of the public keyword in the definition of the Wing class. This makes the class accessible generally. If you omit the public keyword from the class definition, the class is accessible only from methods in classes that are in the Aircraft package.

    Java Packages and the Directory Structure

    Java Packages are actually a little more complicated than they appear at first sight, because a package is intimately related to the directory structure in which it is stored. You already know that the definition of a class with the name ClassName must be stored in a file with the name ClassName.java, and that all the files for classes within a package PackageName must be included in a directory with the name PackageName. You can compile the source for a class within a package and have the .class file that is generated stored in a different directory, but the directory name must still be the same as the package name.

    As you can determine from the existence of the java.lang package that contains the String class, a package can have a composite name that is a combination of two or more simple names. You can specify a package name as any sequence of names separated by periods. For example, you might have developed several collections of classes dealing with Aircraft, perhaps one that works with Airplanes and another with Helicopters. In this case you might include the class Airplane in a package with the statement
    package Aircraft.Airplane; and the class for circles in a package using the statement

    Java Code: Syntax for Java Package in Class Airplane
    package Aircraft.Airplane;
    In this situation, the files containing the classes in the Aircraft.Helicopter packages are expected to be in the directory Helicopter and the files containing the classes in the Aircraft.Airplane packages are expected to be in the directory Airplane. Both of these directories must be subdirectories of a directory with the name Aircraft. In general, you can have as many names as you like separated by periods to identify a package, but the package name must reflect the directory structure in which the package is stored.

    Compiling Java Packages

    Compiling the classes in a package can be a bit tricky unless you are clear on how you go about it. I'll describe what you need to do assuming you are using the JDK under Microsoft Windows. The path to the package directory must be explicitly made known to the compiler in the value that is set for CLASSPATH, even when the current directory is the one containing the package. The easiest way to specify CLASSPATH is by using the classpath option when you invoke the compiler.

    If the Point and Wing classes were not interrelated, you could still compile the two source files or, indeed, any number of source files, in the Aircraft package with the following command:
    Java Code: Command for Compiling a Package
    javac -classpath “C:\JavaExamples” *.java
    Accessing Java Packages

    How you access java packages when you are compiling a program that uses a package depends on where you have put it. There are a couple of options here. The first, but not the best, is to leave the .class files for the classes in the package in the directory with the package name.

    If you are using the JDK, you can always specify where your packages can be found by using the -classpath option when you execute the Java compiler or the interpreter. This has the advantage that it applies only for the current compilation or execution, so you can easily set it to suit each run. The command to compile MyProgram.java defining the classpath to include C:\MySource and C:\MyPackages would be:

    Java Code: Command to compile MyProgram
    javac –classpath “C:\MySource;C:\MyPackages” MyProgram.java
    The compiler will find files in the current directory without specifying a period in the classpath as long as the files are not in a package. The directory containing the package directory must appear in the classpath. If you don't set the classpath, or you set it incorrectly, Java is not able to find the classes in any new packages you might create. If you omit the period from the -classpath string when executing your program, you get a message to the effect that main() cannot be found and your program does not run. Another way to make your packages available after you have compiled them is by making them extensions to the set of standard packages.

    Packing Your Java Programs in JAR Files

    The Java™ Archive (JAR) file format enables you to bundle multiple files into a single archive file. Typically a JAR file contains the class files and auxiliary resources associated with applets and applications. The figure below shows a JAR File comprised of 3 java files:

    Tutorial:Review of Java Packages and JAR Files for the Java Certificate Exam-d12-jarfile.jpg
    Figure: JAR File

    The JAR file format provides many benefits:
    • Security: You can digitally sign the contents of a JAR file. Users who recognize your signature can then optionally grant your software security privileges it wouldn't otherwise have.
    • Decreased download time: If your applet is bundled in a JAR file, the applet's class files and associated resources can be downloaded to a browser in a single HTTP transaction without the need for opening a new connection for each file.
    • Compression: The JAR format allows you to compress your files for efficient storage.
    • Packaging for extensions: The extensions framework provides a means by which you can add functionality to the Java core platform, and the JAR file format defines the packaging for extensions. By using the JAR file format, you can turn your software into extensions as well.
    • Package Sealing: Packages stored in JAR files can be optionally sealed so that the package can enforce version consistency. Sealing a package within a JAR file means that all classes defined in that package must be found in the same JAR file.
    • Package Versioning: A JAR file can hold data about the files it contains, such as vendor and version information.
    • Portability: The mechanism for handling JAR files is a standard part of the Java platform's core API.


    Using JAR Files

    JAR files are packaged using the ZIP file format. This enable you to use them for tasks such as lossless data compression, archiving, decompression, and archive unpacking. These tasks are among the most common uses of JAR files, and provide many JAR file benefits using only these basic features. For the more advanced functionality provided by the JAR file format such as electronic signing, you'll first need to become familiar with the fundamental operations.

    To perform basic tasks with JAR files, use the Java Archive Tool provided as part of the Java Development Kit. The Java Archive tool is invoked by using the jar command, this tutorial refers to it as 'the Jar tool'. Next let’s look at the common JAR file operations:

    Creating a JAR File

    The basic format of the command for creating a JAR file is:

    Java Code: Command to create a JAR file
    jar cf jar-file input-file(s)
    The options and arguments used in this command are:
    • The c option indicates that you want to create a JAR file.
    • The f option indicates that you want the output to go to a file rather than to stdout.
    • jar-file is the name that you want the resulting JAR file to have. You can use any filename for a JAR file. By convention, JAR filenames are given a .jar extension, though this is not required.
    • The input-file(s) argument is a space-separated list of one or more files that you want to include in your JAR file. The input-file(s) argument can contain the wildcard * symbol. If any of the "input-files" are directories, the contents of those directories are added to the JAR archive recursively.

    The c and f options can appear in either order, but there must not be any space between them. This command will generate a compressed JAR file and place it in the current directory. The command will also generate a default manifest file for the JAR archive.

    Viewing the Contents of a JAR File

    The basic format of the command for viewing the contents of a JAR file is:

    Java Code: Command to view contents of a JAR file
    jar tf jar-file
    The options and argument used in this command are the following:
    • The t option indicates that you want to view the table of contents of the JAR file.
    • The f option indicates that the JAR file whose contents are to be viewed is specified on the command Wing.
    • The jar-file argument is the path and name of the JAR file whose contents you want to view.

    The t and f options can appear in either order, but there must not be any space between them. This command will display the JAR file's table of contents to stdout. You can optionally add the verbose option, v, to produce additional information about file sizes and last-modified dates in the output.

    Extracting the Contents of a JAR File

    The basic command to use for extracting the contents of a JAR file is:

    Java Code: Command to extract contents of a JAR file
    jar xf jar-file [archived-file(s)]
    The options and argument used in this command are the following:
    • The x option indicates that you want to extract files from the JAR archive.
    • The f options indicates that the JAR file from which files are to be extracted is specified on the command Wing, rather than through std-in.
    • The jar-file argument is the filename (or path and filename) of the JAR file from which to extract files.
    • archived-file(s) is an optional argument consisting of a space-separated list of the files to be extracted from the archive. If this argument is not present, the Jar tool will extract all the files in the archive.

    As usual, the order in which the x and f options appear in the command doesn't matter, but there must not be a space between them. When extracting files, the Jar tool makes copies of the desired files and writes them to the current directory, reproducing the directory structure that the files have in the archive. The original JAR file remains unchanged.

    Updating a JAR File

    The Jar tool provides a u option which you can use to update the contents of an existing JAR file by modifying its manifest or by adding files.
    The basic command for adding files has this format:

    XML Code: Command to extract contents of a JAR file
    jar uf jar-file input-file(s)
    The options and argument used in this command are the following:
    • The u option indicates that you want to update an existing JAR file.
    • The f option indicates that the JAR file to update is specified on the command Wing.
    • jar-file is the existing JAR file that's to be updated.
    • input-file(s) is a space deliminated list of one or more files that you want to add to the Jar file.

    Any files already in the archive having the same pathname as a file being added will be overwritten. When creating a new JAR file, you can optionally use the -C option to indicate a change of directory.

    Working with Manifest Files

    JAR files support a wide range of functionality, including electronic signing, version control, package sealing, and others. What gives a JAR file this versatility? The answer is the JAR file's manifest. The manifest is a special file that can contain information about the files packaged in a JAR file. By modifying the "meta" information that the manifest contains, you enable the JAR file to serve a variety of purposes.

    Understanding the Default Manifest

    When a JAR file is created, it automatically receives a default manifest file. There can be only one manifest file in an archive, and it always has the pathname

    XML Code: Understanding the Default Manifest
    META-INF/MANIFEST.MF
    When one creates a JAR file, the default manifest file will simply contain the following:

    XML Code: The default manifest for a JAR File
    Manifest-Version: 1.0
    Created-By: 1.6.0 (Sun Microsystems Inc.)
    The name of a header is separated from its value by a colon. The default manifest conforms to version 1.0 of the manifest specification and was created by the 1.6.0 version of the JDK. The manifest also can contain information about the other files that are packaged in the archive. What file information should be recorded in the manifest depends on how you intend exactly to use the JAR file. The default manifest makes no assumptions about what information it should record about other files. Digest information is not included in the default manifest.

    Modifying a Manifest File

    You use the m command-line option to add custom information to the manifest during creation of a JAR file. This section describes the m option. The Jar tool automatically puts a default manifest with the pathname META-INF/MANIFEST.MF into any JAR file you create. You can enable special JAR file functionality, such as package sealing, by modifying the default manifest. Typically, modifying the default manifest involves adding special-purpose headers to the manifest that allow the JAR file to perform a particular desired function.

    To modify the manifest, you need to first prepare a text file containing the information you wish to add to the manifest. Then use the Jar tool's m option to add the information in your file to the manifest. The basic command has the following format:

    XML Code: Command to Modify Manifest File
    jar cfm jar-file manifest-addition input-file(s)
    Setting an Application's Entry Point

    If you have an application bundled in a JAR file, you need some way to indicate which class within the JAR file is your application's entry point. You provide this information with the Main-Class header in the manifest, which has the general form:

    XML Code: Main Class Header in Manifest File
    Main-Class: classname
    The value classname is the name of the class that is your application's entry point.
    Recall that the entry point is a class having a method with signature

    Java Code: Entry Point for Method
    public*static*void*main(String[]*args)
    After you have set the Main-Class header in the manifest, you then run the JAR file using the following form of the java command:

    Java Code: Java JAR Command
    java -jar JAR-name
    The main method of the class specified in the Main-Class header is executed.

    Adding Classes to the JAR File's Classpath

    You may need to reference classes in other JAR files from within a JAR file.
    For example, in a typical situation an applet is bundled in a JAR file whose manifest references a different JAR file (or several different JAR files) that serves as utilities for the purposes of that applet.

    You specify classes to include in the Class-Path header field in the manifest file of an applet or application. The Class-Path header takes the following form:

    XML Code: Class-Path Header
    Class-Path: jar1-name jar2-name directory-name/jar3-name
    By using the Class-Path header in the manifest, you can avoid having to specify a long -classpath flag when invoking Java to run the your application.

    Setting Package Version Information

    You may need to include package version information in a JAR file's manifest. You provide this information with the following headers in the manifest:

    Tutorial:Review of Java Packages and JAR Files for the Java Certificate Exam-d12-tablemanifestheader.jpg
    Table: Headers in the Manifest

    One set of such headers can be assigned to each package. The versioning headers should appear directly beneath the Name header for the package. This example shows all the versioning headers:

    XML Code: Package Version Information
    Name: java/util/
    Specification-Title: Java Utility Classes
    Specification-Version: 1.2
    Specification-Vendor: Example Tech, Inc.
    Implementation-Title: java.util
    Implementation-Version: build57
    Implementation-Vendor: Example Tech, Inc.
    Sealing Packages within a JAR File

    Packages within JAR files can be optionally sealed, which means that all classes defined in that package must be archived in the same JAR file. You might want to seal a package, for example, to ensure version consistency among the classes in your software.
    You seal a package in a JAR file by adding the Sealed header in the manifest, which has the general form:

    XML Code: Sealed Header Manifest
    Name: myCompany/myPackage/
    Sealed: true
    The value myCompany/myPackage/ is the name of the package to seal.
    Note that the package name must end with a "/".

    Sealing JAR Files

    If you want to guarantee that all classes in a package come from the same code source, use JAR sealing. A sealed JAR specifies that all packages defined by that JAR are sealed unless overridden on a per-package basis. To seal a jar file, use the Sealed manifest header with the value true. For example,

    XML Code: Sealed Manifest Header Value
    Sealed: true
    specifies that all packages in this archive are sealed unless explicitly overridden for particular packages with the Sealed attribute in a manifest entry.

    Signing and Verifying JAR Files
    You can optionally sign a JAR file with your electronic "signature." Users who verify your signature can grant your JAR-bundled software security privileges that it wouldn't ordinarily have. Conversely, you can verify the signatures of signed JAR files that you want to use.

    Understanding Signing and Verification

    The Java™ platform enables you to digitally sign JAR files. You digitally sign a file for the same reason you might sign a paper document with pen and ink -- to let readers know that you wrote the document, or at least that the document has your approval.

    When you sign a letter, for example, everyone who recognizes your signature can confirm that you wrote the letter. Similarly when you digitally sign a file, anyone who "recognizes" your digital signature knows that the file came from you. The process of "recognizing" electronic signatures is called verification.

    The ability to sign and verify files is an important part of the Java platform's security architecture. Security is controlled by the security policy that's in force at runtime. You can configure the policy to grant security privileges to applets and to applications. For example, you could grant permission to an applet to perform normally forbidden operations such as reading and writing local files or running local executable programs. If you have downloaded some code that's signed by a trusted entity, you can use that fact as a criterion in deciding which security permissions to assign to the code.

    The Java platform enables signing and verification by using special numbers called public and private keys. Public keys and private keys come in pairs, and they play complementary roles.

    The private key is the electronic "pen" with which you can sign a file. As its name implies, your private key is known only to you so that no one else can "forge" your signature. A file signed with your private key can be verified only by the corresponding public key.
    Public and private keys alone, however, aren't enough to truly verify a signature. Even if you've verified that a signed file contains a matching key pair, you still need some way to confirm that the public key actually comes from the signer that it purports to come from.

    One more element, therefore, is required to make signing and verification work. That additional element is the certificate that the signer includes in a signed JAR file. A certificate is a digitally signed statement from a recognized certification authority that indicates who owns a particular public key. A certification authority are entities (typically firms specializing in digital security) that are trusted throughout the industry to sign and issue certificates for keys and their owners. In the case of signed JAR files, the certificate indicates who owns the public key contained in the JAR file.

    When you sign a JAR file your public key is placed inside the archive along with an associated certificate so that it's easily available for use by anyone wanting to verify your signature.

    To summarize digital signing:
    1. The signer signs the JAR file using a private key.
    2. The corresponding public key is placed in the JAR file, together with its certificate, so that it is available for use by anyone who wants to verify the signature.


    Digests and the Signature File

    When you sign a JAR file, each file in the archive is given a digest entry in the archive's manifest. Here's an example of what such an entry might look like:

    XML Code: Digest Entry for Signed JAR File
    Name: test/classes/ClassOne.class
    SHA1-Digest: TD1GZt8G11dXY2p4olSZPc5Rj64=
    The digest values are hashes or encoded representations of the contents of the files as they were at the time of signing. A file's digest will change if and only if the file itself changes.

    When a JAR file is signed, a signature file is automatically generated and placed in the JAR file's META-INF directory, the same directory that contains the archive's manifest. Signature files have filenames with an .SF extension. Here is an example of the contents of a signature file:

    XML Code: Contents for a Signed File
    Signature-Version: 1.0
    SHA1-Digest-Manifest: h1yS+K9T7DyHtZrtI+LxvgqaMYM=
    Created-By: 1.6.0 (Sun Microsystems Inc.)
    
    Name: test/classes/ClassOne.class
    SHA1-Digest: fcav7ShIG6i86xPepmitOVo4vWY=
    
    Name: test/classes/ClassTwo.class
    SHA1-Digest: xrQem9snnPhLySDiZyclMlsFdtM=
    
    Name: test/images/ImageOne.gif
    SHA1-Digest: kdHbE7kL9ZHLgK7akHttYV4XIa0=
    
    Name: test/images/ImageTwo.gif
    SHA1-Digest: mF0D5zpk68R4oaxEqoS9Q7nhm60=
    For more information about signature files on the Manifest Format page of the JDK documentation.

    The Signature Block File

    In addition to the signature file, a signature block file is automatically placed in the META-INF directory when a JAR file is signed. Unlike the manifest file or the signature file, signature block files are not human-readable.
    • The signature block file contains two elements essential for verification:
    • The digital signature for the JAR file that was generated with the signer's private key
    • The certificate containing the signer's public key, to be used by anyone wanting to verify the signed JAR file

    Signature block filenames typically will have a .DSA extension indicating that they were created by the default Digital Signature Algorithm. Other filename extensions are possible if keys associated with some other standard algorithm are used for signing.

    Signing JAR Files

    You use the JAR Signing and Verification Tool to sign JAR files. You invoke the JAR Signing and Verification Tool by using the jarsigner command, so we'll refer to it as "Jarsigner" for short.

    To sign a JAR file, you must first have a private key. Private keys and their associated public-key certificates are stored in password-protected databases called keystores. A keystore can hold the keys of many potential signers. Each key in the keystore can be identified by an alias which is typically the name of the signer who owns the key. The key belonging to James Kirk might have the alias "kirk", for example.

    The basic form of the command for signing a JAR file is the following:

    XML Code: Contents for a Signed File
    jarsigner jar-file alias
    In this command:
    • jar-file is the pathname of the JAR file that's to be signed.
    • alias is the alias identifying the private key that's to be used to sign the JAR file, and the key's associated certificate.


    The Jarsigner tool will prompt you for the passwords for the keystore and alias. This form of the command assumes the keystore is to be used is in a file named .keystore in your home directory. It will create signature and signature block files with names x.SF and x.DSA respectively, where x is the first eight letters of the alias, all converted to upper case. This command will overwrite the original JAR file with the signed JAR file.
    In practice, you may want to use this command in conjunction with one or more of these options, which must precede the jar-file pathname. The options are shown in the table below:


    Tutorial:Review of Java Packages and JAR Files for the Java Certificate Exam-d12-tablejarsigneroptions.jpg
    Table:JAR Signer Options

    Verifying Signed JAR Files

    Typically, verification of signed JAR files will be the responsibility of your Java™ Runtime Environment. Your browser will verify signed applets that it downloads. Signed applications invoked with the -jar option of the interpreter will be verified by the runtime environment.
    However, you can verify signed JAR files yourself by using the Jarsigner tool. You might want to do this, for example, to test a signed JAR file that you've prepared. The basic command to use for verifying a signed JAR file is the following:

    XML Code: Command to Verify Signed JAR Files
    jarsigner -verify jar-file
    This command will verify the JAR file's signature and ensure that the files in the archive haven't changed since it was signed. You'll see the following message if the verification is successful:

    XML Code: Message Shown for Verified Signed JAR Files
    jar verified
    If you try to verify an unsigned JAR file, the following message results:

    XML Code: Message Shown for Unverified Signed JAR Files
    jar is unsigned. (signatures missing or not parsable)
    If the verification fails, an appropriate message is displayed. For example, if the contents of a JAR file have changed since the JAR file was signed, a message similar to the following will result if you try to verify the file:

    XML Code: Message for Modified Contents of Signed JAR Files
    jarsigner: java.lang.SecurityException: invalid SHA1 
    signature file digest for test/classes/Manifest.class
    Using JAR-related APIs

    The Java platform contains several classes for use with JAR files. Some of these APIs are:
    • The java.util.jar package
    • The java.net.JarURLConnection class
    • The java.net.URLClassLoader class


    Please see Java documentation on the JarClassLoader and the JarRunner Class for more information.

    Summary

    The Java Archive (JAR) File and its tools enable use to bundle multiple files and other resources connected to applications and applets. The is alot more that you can learn on the effective use of JARs for your deployments. Most of this will be covered in the next series for the Java Developer Exam. As for the Java Associate Certification Exam, if you have gone through this series, you should be ready. Good Luck!
    Last edited by Java Exam; 12-29-2012 at 09:02 PM.

Similar Threads

  1. Replies: 0
    Last Post: 05-05-2012, 02:36 PM
  2. Replies: 0
    Last Post: 04-11-2012, 05:06 PM
  3. Replies: 0
    Last Post: 04-06-2012, 08:24 PM
  4. Replies: 0
    Last Post: 03-26-2012, 01:11 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •