Powerful functions of JAR File Format

Source: Internet
Author: User
Most Java programmers are familiar with the basic operations on jar files. However, only a few programmers know the powerful functions of the JAR file format. In this article, the author discusses many functions and advantages of the jar format, including packaging, executable jar files, security, and indexing.
What is a jar file?
The jar file format is based on popular ZIP file formats and is used to aggregate many files into one file. Unlike ZIP files, Jar files are not only used for compression and release, but also for deployment and encapsulation of libraries, components, and plug-in programs, and can be directly used by tools such as compilers and JVM. Jar contains special files, such as manifests and deployment descriptor, to indicate how the tool handles specific jar.

A jar file can be used:

Used to publish and use Class Libraries
As a building unit for applications and extensions
As the deployment unit of components, applets, or plug-in programs
Used to package auxiliary resources associated with components
The jar file format provides many advantages and functions, many of which are not provided by traditional compression formats such as ZIP or tar. They include:

Security. You can add a digital signature to the JAR file. In this way, the tool that can identify the signature can selectively grant you software security privileges, which cannot be done by other files. It can also detect whether the code has been tampered.

Reduce the download time. If an applet is bound to a jar file, the browser can download the Applet Class file and related resources in an HTTP transaction, rather than opening a new connection to each file.

Compression. The jar format allows you to compress files to improve storage efficiency.

Transmission Platform extension. The Java extensionframework provides a method to add functions to the Java core platform, these extensions are packaged using jar files (Java 3D and javamail are examples of extensions developed by Sun ).

Pack seal. You can choose to seal the packages stored in the jar file to enhance the consistency and security of the version. Sealing a package means that all classes in the package must be found in the same JAR file.

Package version control. A jar file can contain data about the files it contains, such as vendor and version information.

Portability. The mechanism for processing jar files is the standard part of the core APIs of the Java platform.
Compressed and uncompressed jar
The jar tool (for details, see the jar tool) compresses files by default. Uncompressed jar files can generally be loaded faster than compressed jar files, because files need to be decompressed during the loading process, but uncompressed files may be downloaded over the network for a longer time.

META-INF directory
Most jar files contain a META-INF directory that is used to store package and extended configuration data such as security and version information. The Java 2 Platform recognizes and interprets the following files and directories in the META-INF directory to configure applications, extensions, and class loaders:

Manifest. MF. This manifest file defines data related to extensions and packages.

Index. List. This file is generated by the new option-I of the jar tool. It contains the location information of the package defined in the application or extension. It is part of the implementation of jarindex and is used by the class loader to accelerate the class loading process.

Xxx. SF. This is the signature file of the JAR file. The placeholder XXX identifies the signatory.

Xxx. DSA. The signature block file associated with the signature file, which stores the public signature used to sign the JAR file.
Jar Tool
To execute basic tasks in a jar file, use the Java archive tool (jar tool) provided as part of Java Development Kit ). Use the jar command to call the jar tool. Table 1 shows some common applications:

Table 1. Common jar tool usage and function commands
Use a separate file to create a jar file jar CF jar-file input-file...
Create a jar file jar CF jar-file Dir-name in a directory
Create an uncompressed JAR file jar CF0 jar-file Dir-name
Update a jar file jar UF jar-file input-file...
View the content of a jar file. Jar TF jar-File
Extract the content of a jar file. Jar XF jar-File
Extract the specified jar XF jar-file archived-file from a jar file...
Run Java-jar app. Jar

Executable jar
An executable JAR file is a self-contained Java application, which is stored in a specially configured JAR file, it can be directly executed by JVM without extracting files or setting the class path in advance. To run an application stored in a non-executable jar, you must add it to your class path and call the main class of the application by name. However, you can run an application without extracting the executable JAR file or knowing the main entry point. Executable jar can facilitate the release and execution of Java applications.

Create executable jar
It is easy to create an executable jar. First, put all application code in a directory. Assume that the main class in the application is com. mycompany. MyApp. sample. Create a jar file containing the application code and identify the main class. Therefore, create a file named manifest at a location (not in the application directory) and add the following line to it:

Main-class: COM. mycompany. MyApp. Sample

Then, create a jar file like this:

Jar CMF manifest executablejar. Jar application-Dir

All you need to do is executablejar. jar.

An executable jar must be referenced by the menifest file header. If the-jar option is used, the environment variable classpath and all the class paths specified in the command line are ignored by JVM.

Start executable jar
Now that we have packaged our application into an executable jar named executablejar. jar, we can use the following command to directly start the application from the file:

Java-jar executablejar. Jar

Pack Seal
Sealing a package in the jar file means that all classes defined in the package must be found in the same JAR file. This allows the package author to enhance version consistency between packaging classes. Sealing also provides a way to prevent code tampering.

To seal the package, add a name header to the package in the jar manifest file, and add the sealed header with the value of "true. Like an executable jar, you can seal a jar by specifying a manifest file with an appropriate Header element when creating the jar, as shown below:

Name: COM/samplepackage/
Sealed: True

The name header identifies the relative path name of the output packet. It ends with a "/" and is different from the file name. All headers before the first blank line after the name header apply to the file or package specified in the name header. In the above example, because the sealed header appears after the name header and there is no blank line in the middle, the sealed header will be interpreted as only applied to the package COM/samplepackage.

JVM throws a securityexception if you try to load a class in the sealing package from a place other than the JAR file where the sealing package is located.

Extended Packaging
Extended functions have been added to the Java platform, and the extended mechanism has been added to the JAR file format. The extension mechanism allows the JAR file to specify other jar files by using the class-path header in the manifest file.

Assume that extension1.jar and extension2.jar are two jar files in the same directory. The manifest file of extension1.jar contains the following headers:

Class-path: extension2.jar

This header indicates that the class in extension2.jar is the extension class of the class in extension1.jar. Classes in extension1.jar can call classes in extension2.jar, and do not require extension2.jar to be in the class path.

When loading the jar using the extension mechanism, JVM will efficiently and automatically add the jar referenced in the class-path header to the class path. However, the extension jar path is interpreted as a relative path, so in general, the extension jar must be stored in the same directory where the jar that references it is located.

For example, if the class extensionclient references the class extensiondemo, It is bundled in a jar file named extensionclient. jar, and the class extensiondemo is bundled in extensiondemo. jar. To enable extensiondemo. jar to be extended, you must list extensiondemo. jar in the class-path header of manifest of extensionclient. jar, as shown below:

Manifest-version: 1.0
Class-path: extensiondemo. Jar

In this manifest, the Class-path header value is extensiondemo. jar without a specified path, indicating that the extensiondemo. jar and extensionclient jar files are in the same directory.

Security in jar files
Jar files can be signed using the jarsigner tool or using Java. Security API directly. A signed JAR file is exactly the same as the original JAR file, but it updates its manifest and adds two files, one signature file and one signature block file to the META-INF directory.

The jar file is signed by a certificate stored in the keystore database. The certificate stored in the keystore is password-protected. You must provide this password to the jarsigner tool to sign the JAR file.

Figure 1. keystore Database

Each signatory of the jar is represented by a signature file with the. SF extension in the META-INF directory of the JAR file. The file format is similar to the manifest file-a set of RFC-822 headers. As shown below, its composition includes a main part, which includes information provided by the signatory, but not specifically for any specific JAR file items, and a series of separate items, these items must also be included in the menifest file. When verifying a signed JAR file, compare the digest value of the signature file with the digest value calculated for the corresponding items in the jar file.

Listing 1. manifest and signature files in the signature jar
Contents of signature file META-INF/manifest. MF

Manifest-version: 1.0
Created-by: 1.3.0 (Sun Microsystems Inc .)

Name: sample. Java
SHA1-Digest: 3 + ddyw8inictyg8zarhlfxx0w6g =

Name: sample. Class
SHA1-Digest: yj5yqhbzbj3sstnchjfqukfwemi =

Contents of signature file META-INF/James. SF

Signature-version: 1.0
SHA1-Digest-Manifest: hbstzojbuutj6qmidb90t8sjaom =
Created-by: 1.3.0 (Sun Microsystems Inc .)

Name: sample. Java
SHA1-Digest: qipmdrkurqckwnyili3jtrnia8q =

Name: sample. Class
SHA1-Digest: pt2dyby8qxpcczv2nwplxd8p4g4 =

Digital Signature
A digital signature is the signed version of The. SF signature file. A digital signature file is a binary file and has the same file name as a. SF file, but its extension is different. There are different extensions based on the digital signature type-RSA, DSA, or PGP-and the certificate type used to sign the jar.

Keystore
To sign a jar file, you must first have a private key. The private key and Its Related Public Key Certificates are stored in a password-protected database named keystores. JDK includes tools for creating and modifying keystores. Each key in the keystore can be identified by an alias. It is usually the name of the signatory who owns the key.

All keystore items (key and trusted Certificate items) are accessed with a unique alias. The alias is specified when the keytool-genkey command is used to generate a key pair (Public Key and private key) and add an item in the keystore. The later keytool command must use the same alias to reference this item.

For example, to use the alias "James" to generate a new public/private key pair and wrap the public key into a self-signed certificate, run the following command:

Keytool-genkey-alias James-keypass jamespass
-Validity 80-keystore jameskeystore
-Storepass jameskeystorepass

This command sequence specifies an initial password "jamespass". Subsequent commands require this password when accessing the private key associated with the alias "James" in the keystore "jameskeystore. If the keystore "jameskeystore" does not exist, keytool automatically creates it.

Jarsigner Tool
The jarsigner tool uses keystore to generate or verify the digital signature of the JAR file.

Assume that the keystore "jameskeystore" is created as in the preceding example and contains a key named "James". You can use the following command to sign a jar file:

Jarsigner-keystore jameskeystore-storepass jameskeystorepass
-Keypass jamespass-signedjar ssample. Jar sample. Jar James

This command uses the password "jameskeystorepass" to extract the key with the alias "James" and the password "jamespass" from the keystore named "jameskeystore" and sample the key. JAR file signature, create a signed JAR -- ssample. jar.

The jarsigner tool can also verify a signed JAR file. This operation is much easier than signing a jar file. You only need to execute the following command:

Jarsigner-verify ssample. Jar

If the signed JAR file has not been tampered with, the jarsigner tool will tell you that the JAR file has passed verification. Otherwise, it will throw a securityexception, indicating which files have not passed verification.

You can also use Java. util. jar and Java. Security APIs to sign the jar program programmatically (for more information, see references ). You can also use tools like Netscape Object Signing tool.

Jar Index
If an application or applet is bundled into multiple jar files, the Class Loader uses a simple linear search algorithm to search for each element in the class path, this allows the class loader to download and open many jar files until it finds the desired class or resource. If the class loader tries to find a resource that does not exist, all jar files in the application or applet will be downloaded. For large network applications and applets, this will lead to slow startup, slow response, and a waste of bandwidth.

After JDK 1.3, the JAR File Format supports indexing to optimize the Class search process in network applications, especially the applet. The jarindex mechanism collects the content of all jar files defined in the applet or application, and stores the information in the index file of the first JAR file. After downloading the first JAR file, the Applet Class Loader efficiently loads the JAR file using the collected content. This directory information is stored in a simple text file named index. List in the META-INF directory of the root JAR file.

Create a jarindex
You can create a jarindex by specifying the-I option in the jar command. Assume that the directory structure is shown in:

Figure 2. jarindex

Run the following commands to create an index file for jarindex_main.jar, jarindex_test.jar, and jarindex_test1.jar:

Jar-I jarindex_main.jar jarindex_test.jar sampledir/jarindex_test1.jar

The format of the index. list file is very simple. It contains the name of the package or class contained in each indexed JAR file, as shown in Listing 2:

Listing 2. jarindex index. list file example

Jarindex-version: 1.0

Jarindex_main.jar
SP

Jarindex_test.jar
Sample

Sampledir/jarindex_test1.jar
Org
Org/Apache
Org/Apache/xerces
Org/Apache/xerces/framework
Org/Apache/xerces/framework/xml4j

Conclusion
The jar format is much larger than a compression format. It has many features that can improve efficiency, security, and organize Java applications. Because these functions have been built on the core platform-including compilers and class loaders-, developers can simplify and improve the development and deployment processes by using the JAR File Format capabilities.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.