`
leonzhx
  • 浏览: 794231 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Chapter 10. Deploying Applications and Applets

阅读更多

1.  A JAR (Java Archive) file can contain both class files and other file types such as image and sound files for packing your applications and delivering them to your users. It is compressed, using the ZIP compression format.

 

2.  An alternative to the ZIP format is the “pack200” compression scheme that is specifically tuned to compress class files more efficiently. See http://docs.oracle.com/ javase/1.5.0/docs/guide/deployment/deployment-guide/pack200.html for more information.

 

3.  The most common command to make a new JAR file:

jar cvf JARFileName File1 File2 . . .
 In general, the jar command has the following format:
jar options File1 File2 . . . 
while options are as follow:


  
4.  JAR file contains a manifest file that describes special features of the archive. The manifest file is called MANIFEST.MF and is located in a special META-INF subdirectory of the JAR file.

 

 

5.  The minimum legal manifest is:
    

Manifest-Version: 1.0
 

 

6.  The manifest entries are grouped into sections. The first section in the manifest is called the main section. It applies to the whole JAR file. Subsequent entries can specify properties of named entities such as individual files, packages, or URLs. Those entries must begin with a Name entry. Sections are separated by blank lines. i.e.:

 

Manifest-Version: 1.0
lines describing this archive

Name: Woozle.class
lines describing this file

Name: com/mycompany/mypkg/
lines describing this package
  

 

7.  To edit the manifest, place the lines that you want to add to the manifest into a text file. Then run

jar cfm JARFileName ManifestFileName . . .
 

 

8.  See http://docs.oracle.com/javase/7/docs/technotes/guides/jar for more information on the JAR and manifest file formats.

 

9.  You can use the e option of the jar command to specify the entry point of your program—the class that you would normally specify when invoking the java program launcher:

jar cvfe MyProgram.jar com.mycompany.mypkg.MainAppClass files-to-add
Alternatively, you can specify the main class of your program in the manifest, including a statement of the form
Main-Class: com.mycompany.mypkg.MainAppClass

 

10.  The last line in the manifest must end with a newline character. Otherwise, the manifest will not be read correctly.

 

11.  Users can simply start the program as:

 

java -jar MyProgram.jar
 

 

12.  To convert a runnable jar into .exe file , you can see www.javalobby.org/articles/java2exe for more details.

 

13.  The resource mechanism gives you the convenience for searching for files that aren’t class files on the class path, in an archive, or, for applets, on a web server. Here are the necessary steps:
    a)  Get the Class object of the class that has a resource.
    b)  If the resource is an image or audio file, call getResource(filename) to get the resource location as a URL. Then read it with the Applet.getImage or Applet.getAudioClip method.
    c)  For resources other than images or audio files, use the getResourceAsStream method to read the data in the file.
The point is that the class loader remembers how to locate the class, so it can then search for the associated resource in the same location.

 

14.  A resource name starting with a / is called an absolute resource name. It is located in the same way a class inside a package would be located. i.e. /corejava/title.txt is located in the corejava directory which may be a subdirectory of the class path, inside a JAR file, or, for applets, on a web server.

 

15.  To seal the package, put all classes of the package into a JAR file. By default, packages in a JAR file are not sealed. You can change that global default by placing the line

Sealed: true
into the main section of the manifest. You can also specify whether you want an individual package to be sealed or not:
Name: com/mycompany/util/
Sealed: true

Name: com/mycompany/misc/
Sealed: false

16.  Java Web Start applications have the following characteristics:
    a)  They are typically delivered through a browser. Once a Java Web Start application has been downloaded, it can be started without using a browser.
    b)  They do not live inside a browser window. The application is displayed in its own frame, outside the browser.
    c)  They do not use the Java implementation of the browser. The browser simply launches an external application whenever it loads a Java Web Start application descriptor. That is the same mechanism used to launch other helper applications such as Adobe Acrobat or RealAudio.
    d)  Digitally signed applications can be given arbitrary access rights on the local machine. Unsigned applications run in a “sandbox,” which prohibits potentially dangerous operations.

 

17.  To prepare an application for delivery by Java Web Start, package it in one or more JAR files. Then, prepare a descriptor file in the Java Network Launch Protocol (JNLP) format. (see www.oracle.com/technetwork/java/javase/javawebstart/index.html for detail) Place these files on a web server. You also need to ensure that your web server reports a MIME type of application/x-java-jnlp-file for files with extension .jnlp. Place the JAR file and the launch file on your web server so that the URL matches the codebase entry in the JNLP file:

<?xml version="1.0" encoding="utf-8"?>
<jnlp spec="1.0+" codebase="http://localhost:8080/calculator/" href="Calculator.jnlp">
  <information>
    <title>Calculator Demo Application</title>
    <vendor>Cay S. Horstmann</vendor>
    <description>A Calculator</description>
    <offline-allowed/>
  </information>
  <resources>
    <java version="1.6.0+"/>
    <jar href="Calculator.jar"/>
  </resources>
  <application-desc/>
</jnlp>

  

18.  If you don’t want to run a web server while you are testing your JNLP configuration, you can temporarily override the codebase URL in the launch file by running

javaws -codebase file://programDirectory JNLPfile

 

 

19.  You can have the installer offer to install desktop and menu shortcuts. Add these lines to the JNLP file:

<shortcut>
   <desktop/>
   <menu submenu="Accessories"/>
</shortcut>
 
You should also supply an icon for the menu shortcut and the launch screen. Oracle recommends that you supply a 32 × 32 and a 64 × 64 icon. Place the icon files on the web server, together with the JNLP and JAR files. Add these lines to the information section of the JNLP file:
<icon href="calc_icon32.png" width="32" height="32" />
<icon href="calc_icon64.png" width="64" height="64" />

 

 

20.  Programs in the sandbox have the following restrictions:
    a)  They can never run any local executable program.
    b)  They cannot read from or write to the local computer’s file system.
    c)  They cannot find out any information about the local computer, except for the Java version used and a few harmless operating system details. In particular, code in the sandbox cannot find out the user’s name, e-mail address, and so on.
    d)  Remotely loaded programs need user consent to communicate with any host other than the server from which they were downloaded; that server is called the originating host.
    e)  All pop-up windows carry a warning message. This message is a security feature to ensure that users do not mistake the window for a local application.

 

21.  To request to have all permissions of a desktop application, adding the following tags to the JNLP file:

<security>
   <all-permissions/>
</security>
 
To run outside the sandbox, the JAR files of a Java Web Start application must be digitally signed. A signed JAR file carries with it a certificate that indicates the identity of the signer.

 

 

22.  If you find that your users trust your application and your web infrastructure, go ahead and use a self-signed certificate. (See http://docs.oracle.com/javase/6/docs/technotes/guides/javaws/developersguide/development.html for details.)

 

23.  The JNLP API allows unsigned applications to run in the sandbox and at the same time access local resources in a secure way. The API provides the following services:
    a)  Loading and saving files
    b)  Accessing the clipboard
    c)  Printing
    d)  Downloading a file
    e)  Displaying a document in the default browser
    f)  Storing and retrieving persistent configuration information
    g)  Ensuring that only a single instance of an application executes
To access a service, use the ServiceManager, like this:

FileSaveService service = (FileSaveService) ServiceManager.lookup("javax.jnlp.FileSaveService");
This call throws an UnavailableServiceException if the service is not available.

 

 

24.  You must include the file javaws.jar in the class path if you want to compile programs that use the JNLP API. That file is included in the jre/lib subdirectory of the JDK.

 

25.  To save a file, provide suggestions for the initial path name and file extensions for the file dialog, the data to be saved, and a suggested file name:

service.saveFileDialog(".", new String[] { "txt" }, data, "calc.txt");
The data must be delivered in an InputStream.

 

 

26.  To read data from a file, use the FileOpenService instead. Its openFileDialog receives suggestions for the initial path name and file extensions for the file dialog and returns a FileContents object. You can then call the getInputStream and getOutputStream methods to read and write the file data. If the user didn’t choose a file, the openFileDialog method returns null.

 

27.  If you want to open a specific file, use the ExtendedService:

ExtendedService service = (ExtendedService) ServiceManager.lookup("javax.jnlp.ExtendedService");
FileContents contents =  service.openFile(new File("c:\\autoexec.bat"));
if (contents != null)
{
   OutputStream out = contents.getOutputStream();
   . . .
}
The user of your program must agree to the file access.

 

 

28.  To display a document in the default browser, use the BasicService interface. Note that some systems may not have a default browser.

BasicService service = (BasicService) ServiceManager.lookup("javax.jnlp.BasicService");
if (service.isWebBrowserSupported())
   service.showDocument(url);
else . . .

  

29.  PersistenceService lets an application store small amounts of configuration information and retrieve it when the application runs again. The mechanism is similar to HTTP cookies. The persistent store uses URLs as keys. The URLs don’t have to point to a real web resource. The service simply uses them as a convenient hierarchical naming scheme. For any given URL key, an application can store arbitrary binary data. For applications to be isolated from each other, each application can only use URL keys that start with its codebase (as specified in the JNLP file). For example, if an application is downloaded from http://myserver.com/apps, it can only use keys of the form http://myserver.com/apps/subkey1/subkey2/... Attempts to access other keys will fail. An application can call the getCodeBase method of the BasicService to find its codebase. Create a new key with the create method of the PersistenceService:

URL url = new URL(codeBase, "mykey");
service.create(url, maxSize);

To access the information associated with a particular key, call the get method. That method returns a FileContents object through which you can read and write the key data. 

FileContents contents = service.get(url);
InputStream in = contents.getInputStream();
OutputStream out = contents.getOutputStream(true); // true = overwrite

There is no convenient way to find out whether a key already exists or whether you need to create it. You can hope that the key exists and call get. If the call throws a FileNotFoundException, you need to create the key.

 

30.  If your applet contains Swing components, you must extend the JApplet class. Swing components inside a plain Applet don’t paint correctly.

 

31.  To execute the applet, carry out two steps:
    a)  Compile your Java source files into class files.
    b)  Create an HTML file that tells the browser which class file to load first and how to size the applet:

<applet code="applet/NotHelloWorld.class" width="300" height="300"></applet>

32.  You can use applet viewer to test your applet:

appletviewer NotHelloWorldApplet.html

The command-line argument for the applet viewer program is the name of the HTML file, not the class file. The applet viewer program shows you only the applet, not the surrounding HTML text. If your HTML file contains multiple applet tags, the applet viewer pops up multiple windows.

 

33.  If you make a change to your applet and recompile, you need to restart the browser so that it loads the new class files. Simply refreshing the HTML page will not load the new code. You can avoid the painful browser restart from the Java console. Launch the console and issue the x command, which clears the classloader cache. Under Windows, open the Java Plug-in control in the Windows control panel. Under Linux, run jcontrol and request that the Java console be displayed. The console will pop up whenever an applet is loaded.

 

34.  To convert a graphical Java application into an applet:
    a)  Make an HTML page with the appropriate tag to load the applet code.
    b)  Supply a subclass of the JApplet class. Make this class public. Otherwise, the applet cannot be loaded.
    c)  Eliminate the main method in the application. Do not construct a frame window for the application. Your application will be displayed inside the browser.
    d)  Move any initialization code from the frame window constructor to the init method of the applet. You don’t need to explicitly construct the applet object—the browser instantiates it for you and calls the init method.
    e)  Remove the call to setSize; for applets, sizing is done with the width and height parameters in the HTML file.
    f)  Remove the call to setDefaultCloseOperation. An applet cannot be closed; it terminates when the browser exits.
    g)  If the application calls setTitle, eliminate the call to the method. Applets cannot have title bars.
    h)  Don’t call setVisible(true). The applet is displayed automatically.

 

35.  applet tag looks like this:

<applet code="applet/NotHelloWorld.class" width="300" height="100"></applet>

As you have seen, the code attribute gives the name of the class file and must include the .class extension. The path name must match the package of the applet class and is taken relative to the codebase attribute, or relative to the current page if the codebase is not specified; the width and height attributes size the window that will hold the applet. Both are measured in pixels. The text between the <applet> and </applet> tags is displayed only if the browser cannot support java, however if the browser can support java and the administrator disabled applet, then the content of alt attribute will be shown. The code, width, and height attributes are required. If any are missing, the browser cannot load your applet.

 

36.  codebase attribute of applet tag is optional, it’s a URL for locating the class files. You can use an absolute URL, even to a different server.

 

37.  The archive attribute lists the JAR file or files containing classes and other resources for the applet. These files are fetched from the web server before the applet is loaded. This technique speeds up the loading process significantly because only one HTTP request is necessary to load a JAR file containing many smaller files. The JAR files are separated by commas.

 

38.  The object attribute lets you specify the name of a file that contains the serialized applet object. To display the applet, the object is deserialized from the file to return it to its previous state. When you use this attribute, the init method is not called, but the applet’s start method is called. Before serializing an applet object, you should call its stop method. This feature is useful for implementing a persistent browser that automatically reloads its applets and has them return to the same state that they were in when the browser was closed. Either code or object must be present in every applet tag.

 

39.  To access an applet from JavaScript, you first have to give it a name by its name attribute. You can then refer to the object as document.applets.appletname.

 

40.  In www.javaworld.com/javatips/jw-javatip80.html, Francis Lu uses JavaScript-to-Java communication to solve an age-old problem: how to resize an applet so that it isn’t bound by hardcoded width and height attributes.

 

41.  The object tag is part of the HTML 4.0 standard instead of applet tag. The key attribute in the object tag is the classid attribute which specifies the location of the object. Of course, object tags can load different kinds of objects, such as Java applets, ActiveX components, or the Java Plug-in itself. In the codetype attribute, you can specify the nature of the object:

<object codetype="application/java" classid="java:MyApplet.class" width="100" height="150">

The classid attribute can be followed by a codebase attribute that works exactly as it did with the applet tag.

 

42.  You can pass parameters to applet using HTML param tag:

<applet code="FontParamApplet.class" width="200" height="200">
   <param name="font" value="Helvetica"/>
</applet>

You can then pick up the value of the parameter using the getParameter method of the Applet class. You can call the getParameter method only in the init method of the applet, not in the constructor. When the applet constructor is executed, the parameters are not yet prepared. Parameters are always returned as strings and parameter name is case sensitive.

 

43.  The base URL is usually obtained by calling the getDocumentBase or getCodeBase method. The former gets the URL of the HTML page in which the applet is contained, the latter the URL of the applet’s codebase directory.

 

44.  To communicate with the browser, an applet calls the getAppletContext method. That method returns an object that implements an interface of type AppletContext. You can think of the concrete implementation of the AppletContext interface as a communication path between the applet and the ambient browser.

 

45.  If a web page contains multiple applets from the same codebase, they can communicate with each other. If you give name attributes to each applet in the HTML file, you can use the getApplet method of the AppletContext interface to get a reference to the applet. The getApplets method returns an Enumeration object which enumerates all applets on a web page.

 

46.  You can display a string in the status line at the bottom of the browser with the showStatus message. You can tell the browser to show a different web page with the showDocument method. If you only pass the URL to the showDocument method, it opens the new web page in the same window as your current page. You can pass in another String to indicate which window to show the specified page:
 

 
47.  A property map is a data structure that stores key/value pairs. Property maps are often used for storing configuration information. Property maps have three particular characteristics:
    a)  The keys and values are strings.
    b)  The set can easily be saved to a file and loaded from a file.
    c)  There is a secondary table for default values.

 

48.  The Java class that implements a property map is called Properties. Use the put method to set key/value pairs in the property map and use store method to save the list of properties to a file:

FileOutputStream out = new FileOutputStream("program.properties");
settings.store(out, "Program Properties");

The second argument is a comment that is included in the file.

 

49.  To load the properties from a file, use

FileInputStream in = new FileInputStream("program.properties");
settings.load(in);

50.  It is customary to store program properties in a subdirectory of the user’s home directory. The directory name is often chosen to start with a dot. To find the user’s home directory, you can call the System.getProperties method, which, as it happens, also uses a Properties object to describe the system information. Or you can call the System.getProperty to get a specific property value. The home directory has the key "user.home".

 

51.  The Properties class has two mechanisms for providing defaults. First, whenever you look up the value of a string, you can specify a default that should be used automatically when the key is not present.

String title = settings.getProperty("title", "Default title");

you can pack all the defaults into a secondary property map and supply that map in the constructor of your primary property map:

Properties defaultSettings = new Properties();
defaultSettings.put("width", "300");
defaultSettings.put("height", "200");
defaultSettings.put("title", "Default title");
. . .
Properties settings = new Properties(defaultSettings);

  

52.  You can find the names of the freely accessible system properties in the file security/java.policy in the directory of the Java runtime.

 

53.  Using property files has these disadvantages:
    a)  Some operating systems have no concept of a home directory, making it difficult to find a uniform location for configuration files.
    b)  There is no standard convention for naming configuration files, increasing the likelihood of name clashes as users install multiple Java applications.

 

54.  The Preferences class provides such a central repository in a platform-independent manner. In Windows, the Preferences class uses the registry for storage; on Linux, the information is stored in the local file system instead.

 

55.  The Preferences repository has a tree structure, with node path names such as /com/mycompany/myapp. The designers of the API suggest that the configuration node paths match the package names in your program. Each node in the repository has a separate table of key/value pairs that you can use to store numbers, strings, or byte arrays.

 

56.  For additional flexibility, there are multiple parallel trees. Each program user has one tree; an additional tree, called the system tree, is available for settings that are common to all users. To access a node in the tree, start with the user or system root:

Preferences root = Preferences.userRoot();

or

Preferences root = Preferences.systemRoot();

Then access the node by simply providing a node path name:

Preferences node = root.node("/com/mycompany/myapp");

A convenient shortcut gets a node whose path name equals the package name of a class:

Preferences node = Preferences.userNodeForPackage(obj.getClass());

or

Preferences node = Preferences.systemNodeForPackage(obj.getClass());

57.  Once you have a node, you can access the key/value table with methods

String get(String key, String defval)
int getInt(String key, int defval)
long getLong(String key, long defval)
float getFloat(String key, float defval)
double getDouble(String key, double defval)
boolean getBoolean(String key, boolean defval)
byte[] getByteArray(String key, byte[] defval)

You must specify a default value when reading the information, in case the repository data is not available.

 

58.  You can enumerate all keys stored in a node with the method

String[] keys()

There is currently no way to find out the type of the value of a particular key.

 

59.  You can export the preferences of a subtree (or, less commonly, a single node) by calling the methods

void exportSubtree(OutputStream out)
void exportNode(OutputStream out)

The data are saved in XML format. You can import them into another repository by calling

void importPreferences(InputStream in)
  • 大小: 206.8 KB
  • 大小: 69.4 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics