Explore the powerful functions of the 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 JAR file format.
Powerful functions. 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 the ZIP file, the JAR file is not only used for compression and release, but also used to deploy and encapsulate libraries, components, and plug-ins.
Tools such as JVM are used directly. 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
    Applet Class files and related resources, 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.
    Jar files (Java 3D and javamail are extensions developed by Sun ).

  • Pack seal.The package stored in the jar file can be selected

    SealEnhanced version consistency and security. Sealing a package means that all classes in the package must be 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

jarTool (for more information, see


jarTools

By default, files are compressed. Uncompressed
Generally, Jar files can 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. Java 2 platform identification and interpretation of META-INF
The following files and directories in the directory to configure applications, extensions, and class loaders:

  • Manifest. MF.This

    Manifest FileDefines data related to extensions and packages.

  • Index. List.This file is composed

    jarNew Tool options

    -iIt contains the location information of the package defined in the application or extension. It is
    A part of jarindex implementation, and the class loader is used to accelerate the class loading process.


  • Xxx. SF.

    This is the signature file of the JAR file. Placeholder

    XxxIdentifies 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 using jar files, use the Java archive tool provided as part of Java Development Kit.
(

jarTool ). Use

jarCommand call

jarTool. Table 1
Shows some common applications:

Table 1. Common

jarTool usage

Function Command
Create a jar file with a separate file Jar CF jar-file input-file...
Create a jar file using a directory Jar CF jar-file Dir-name
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 A specific file from a jar file Jar XF jar-file archived-file...
Run an application packaged as an executable JAR File Java-jar app. Jar


Executable jar

One

Executable jarA file is a self-contained Java application. It is stored in a specially configured JAR file and can be directly executed by JVM without extracting the file or setting the class path in advance. To run
The application in jar must be added to your class path, and the main class of the application must be called by name. However, you can run an application without extracting the executable JAR file or knowing the main entry point. Executable
Jar helps to easily publish and execute 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. You want to create
JAR file and identify the main class. To this end, create

manifestAnd 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 have to do is use

java -jarExecutablejar. jar.

An executable jar must be referenced by the menifest file header. If

-jarThe environment variables 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, you must add

NameHeader, and then add the value "true"


Sealed
Header. Like an executable jar, you can seal a jar by specifying a manifest file with an appropriate Header element when creating the jar.
Jar, as shown below:

Name: com/samplePackage/
Sealed: true

NameHeader to identify the relative path of the output packet. It ends with a "/" and is different from the file name. In

NameAll headers before the first blank line after the header are applied

NameThe file or package specified in the header. In the preceding example

SealedHeader appears in

Name
Header and no blank lines in the middle, so

SealedThe header will be interpreted as applying only to the package

com/samplePackage
.

JVM throws

SecurityException.

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

Class-PathSpecify other jar files.

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


Class-Path: extension2.jar


This header indicates that the classes in extension2.jar are

Extension class. Extension1.jar
You can call classes in extension2.jar without requiring them to be in the class path.

When loading the jar using the extension mechanism, the JVM will efficiently and automatically

Class-PathAdd the jar referenced in the 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, assume that

ExtensionClientReferenced class

ExtensionDemo, It is bundled in
In the JAR file of extensionclient. jar

ExtensionDemoThen it is bundled in extensiondemo. Jar
. To enable extensiondemo. jar to be extended, you must list extensiondemo. jar in extensionclient. jar.
Of the manifest

Class-PathHeader, as shown below:


Manifest-Version: 1.0
Class-Path: ExtensionDemo.jar


In this manifest

Class-PathThe value of the header 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 used

jarsignerTool or directly through

java.securityAPI
Signature. 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.

Jar files are stored in

KeystoreThe certificate signature in the database. The certificate stored in the keystore is password-protected and must be directed

jarsignerThe tool provides this password 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 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
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. Based on the digital signature type
-- RSA, DSA, or PGP -- and the certificate type used to sign the jar have different extensions.

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

keystoresIn a password-protected database. 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. Alias is in use

keytool -genkey
Command to generate the key pair (Public Key and private key) and specify it when adding an entry to the keystore. After

keytoolThe 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

keytoolIt is automatically created.

Jarsigner Tool

jarsignerThe 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 key
JAR file:

jarsigner -keystore jamesKeyStore -storepass jamesKeyStorePass 
-keypass jamespass -signedjar SSample.jar Sample.jar james

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

jarsignerThe tool can also verify a signed JAR file, which is much simpler than the signed JAR file. You only need to execute the following command:

jarsigner -verify SSample.jar

If the signed JAR file has not been tampered

jarsignerThe tool will tell you that the jar has passed the verification. Otherwise, it will throw

SecurityExceptionIndicates which files have not been verified.

You can also use

java.util.jarAnd

java.securityAPI signature by programming
Jar (for more information, see

References ). You can also use 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 makes it possible for the class loader to download and open many
JAR file until you find 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
Applet, which causes 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 is collected in
The content of all jar files defined in the applet or application, and the information is stored in the index file of the first JAR file. After downloading the first JAR file, the Applet
The Class Loader efficiently loads jar files using the collected content. This directory information is stored in a META-INF directory in the root JAR file named index. List
.

Create a jarindex

You can

jarSpecify

-iOption to create a jarindex. 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
So developers can use the JAR file format to simplify and improve the development and deployment process ..

References

  • You can refer to

    Original English.

  • See

    Jar
    The command line option document of the utility.

  • Raffi krikorian's article on onjava provides

    Programmatically
    Signing a jar file help.

  • Article"

    Java
    Web Start "(

    DeveloperworksSeptember 2001) describes how to use this technology to allow applications to specify the required
    Jar files and download them dynamically.

  • In


    Developerworks
    Java Technology Zone

    You can find hundreds of articles on various aspects of Java programming.

Author Profile

Pagadala
J. Suresh is a software engineer at IBM Global Services India. He specializes in Java technology, WebSphere
Application Server, WebSphere Studio Application Developer (wsad), Arba
Buyer. He participated in the IBM Redbook project of Websphere. You can use

Pjsuresh@in.ibm.com
Contact pagadala.

Palaniyappan
Thiagarajan is a software engineer at IBM Global Services India in Bangalore, India. He is IBM certified
IBM WebSphere Application Server v3.5 and IBM DB2 UDB v7.1 family
Fundamentals expert. You can use

Tpalaniy@in.ibm.com
Contact palaniyappan.

 

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.