+ All Categories
Home > Documents > Java Web Start 1.4.2 Developer Guide - Oracle | Integrated ... · PDF fileJava Web Start 1.4.2...

Java Web Start 1.4.2 Developer Guide - Oracle | Integrated ... · PDF fileJava Web Start 1.4.2...

Date post: 02-Mar-2018
Category:
Upload: nguyenminh
View: 226 times
Download: 1 times
Share this document with a friend
33
Java Web Start 1.4.2 Developer Guide Overview Java Web Start Technology Where to Find Java Web Start Technology Desktop and Server Requirements Setting up the Web Site Introduction Basic Steps Creating the Web Page That Launches the Application Introduction Detecting if Java Web Start is installed on Netscape Detecting if Java Web Start is installed on IE, and if so, the version number Launching the application if Java Web Start is Installedor providing a link for auto-install or general download page
Transcript

Java Web Start 1.4.2 DeveloperGuide

Overview

Java Web Start Technology

Where to Find Java Web Start Technology

Desktop and Server Requirements

Setting up the Web Site

IntroductionBasic Steps

Creating the Web Page That Launchesthe Application

IntroductionDetecting if Java Web Start is installed on NetscapeDetecting if Java Web Start is installed on IE, and if so, theversion numberLaunching the application if Java Web Start is Installed�orproviding a link for auto-install or general download page

Creating an auto-install page

Application DevelopmentConsiderations

IntroductionRetrieving Resources from JAR filesSecurity and Code SigningSigning JAR Files with a Test CertificateHow to Encode JNLP FilesDynamic Download of HTTPS Certificates

Packaging an Application for EasyDeployment

JNLP File Syntax

IntroductionThe jnlp ElementThe security ElementThe resources ElementThe application-desc ElementThe applet-desc Element

JNLP API Examples

IntroductionUsing a BasicService ServiceUsing a ClipboardService ServiceUsing a DownloadService ServiceUsing a FileOpenService ServiceUsing a FileSaveService ServiceUsing a PrintService ServiceUsing a PersistenceService ServiceUsing FileContentsUsing a JNLPRandomAccessFile

Appendices:Converting JNLP Files to Work With This ReleaseFAQ (Not available in PDF)JNLP API (JavaDoc) (Not available in PDF)

Overview

Java Web Start TechnologyJava Web Start is a helper application that gets associated with a Web browser. When a user clicks on alink that points to a special launch file (JNLP file), it causes the browser to launch Java Web Start, whichthen automatically downloads, caches, and runs the given Java Technology-based application. The entireprocess is typically completed without requiring any user interaction, except for the initial single click.

JNLP URLs are also directly openable from the JAWS Application Manager and can be bookmarked.Moreover, they may be .html or .jnlp files.

From a technology standpoint, Java Web Start has a number of key benefits that make it an attractiveplatform to use for deploying applications:

Java Web Start is built exclusively to launch applications written to the Java 2 SE platform. Thus,a single application can be made available on a Web server and then deployed on a wide variety ofplatforms, including Windows 98/NT/2000/ME/XP, Linux, and the SolarisTM OperatingEnvironment. The Java platform has proven to be a very robust, productive, and expressivedevelopment platform, leading to a significant cost savings due to minimized development andtesting costs.

Java Web Start supports multiple revisions of the Java 2 platform, Standard Edition. Thus, anapplication can request a particular version of the platform it requires, such as J2SETM 1.4.0.Several applications can run at the same time on different platform revisions without causingconflicts, and Java Web Start can automatically download and install a revision of the platform ifan application requests a version that is not installed on the client system.

Java Web Start allows applications to be launched independently of a Web browser. This can beused for off-line operation of an application, where launching through the browser is ofteninconvenient or impossible. The application can also be launched through desktop shortcuts,making launching the Web-deployed application similar to launching a native application.

Java Web Start takes advantage of the inherent security of the Java Platform. Applications are bydefault run in a protective environment (sandbox) with restricted access to local disk and networkresources. It allows the user to safely run applications from sources that are not trusted.

Applications launched with Java Web Start are cached locally. Thus, an already-downloadedapplication is launched on par with a traditionally installed application.

The technology underlying Java Web Start is the Java TM Network Launching Protocol & API (JNLP).This technology is currently under development via the Java Community Process (JCP). Java Web Start

is the reference implementation (RI) for the JNLP specification. The JNLP technology defines, amongother things, a standard file format that describes how to launch an application called a JNLP file.

Where to find Java Web StartSee the Java Web Start web site, http://java.sun.com/products/javawebstart/, for availability of Java WebStart downloads. The JNLP specification can be found athttp://java.sun.com/aboutJava/communityprocess/jsr/jsr_056_jnlp.html.

Requirements

Desktop/Client requirements:

The client machine requires support for the Java Runtime Environment (JRE), version 1.2.2 or later. JavaWeb Start is available for Windows 98/NT/2000/ME/XP, the Solaris Operating Environment, and Linux.

See the README document for details.

Server requirements:

Applications can be deployed from any standard Web server. In order to use Java Web Start, the Webserver must be configured with support for a new MIME type as explained below.

Setting Up the Web Site

IntroductionJava Web Start leverages existing Internet technology, such as the HTTP protocol and Web servers, soexisting infrastructure for deploying HTML-based contents can be reused to deploy JavaTechnology-based applications using Java Web Start.

In order to deploy your application to client machines, you must make sure that all files containing yourapplication are accessible through a Web server. This typically amounts to copying one or more JARfiles, along with a JNLP file, into the Web server's directories. The set-up required for enabling the Website to support Java Web Start is very similar to deploying HTML-based contents. The only caveat is thata new MIME type needs to be configured for the Web server.

Basic Steps1. Configure the Web server to use the Java Web Start MIME type

Configure the Web server so that all files with the .jnlp file extension are set to theapplication/x-java-jnlp-file MIME type.

Most Web browsers use the MIME type returned with the contents from the Web server to determinehow to handle the particular content. The server must return application/x-java-jnlp-fileMIME type for JNLP files in order for Java Web Start to be invoked.

Each Web server has a specific way in which to add MIME types. For example, for the Apache Webserver you must add the following line to the .mime.types configuration file:

application/x-java-jnlp-file JNLP

Check the documentation for the specifics of your Web server.

2. Create a JNLP file for the application

The easiest way to create this file is to modify an existing JNLP file to your requirements.

The syntax and format for the JNLP file is described in a later section.

3. Make the application accessible on the Web server

Ensure your application's JAR files and the JNLP file are accessible at the URLs listed in the JNLP file.

4. Create the web page that launches the application

See the next chapter, Creating the Web Page that launches the Application, for details on step 4.

Creating the Web Page That Launches theApplication

This chapter includes the following topics:

Introduction●

Detecting if Java Web Start is installed on Netscape●

Detecting if Java Web Start is installed on IE, and if so, the version number●

Launching the application if Java Web Start is Installed�or providing a link for auto-install or general download page●

Creating an auto-install page●

Introduction

In order for an application to be launched from a web page via JNLP, the page must include a link to the JNLP file. E.g., to be able tolaunch application app.jnlp on a web site http://www.yyy.zzz, the page needs to include the following link:

<a href=http://www.yyy.zzz/app.jnlp>Launch the application</a>

It may be the case, however, that JAWS is not installed on the user's computer. Thus the page needs to include logic (scripts) to takeaccount of this. In fact, the page should include logic for the following:

Detect if Java Web Start (JAWS) is installed

If so, launch the application.●

If not, detect if user is running IE on Window.

If so, provide link to a page that can auto-install the JRE for Windows❍

If not, provide a link to the general download page for the SDK/JRE.❍

The scripts, and the HTML for the auto-install page, are discussed below.

Detecting if JAWS is installed on Netscape

Here is the first script that should be run on a web page for launching an application via JNLP:

<SCRIPT LANGUAGE="JavaScript">var javawsInstalled = 0;var javaws12Installed = 0; var javaws142Installed=0;isIE = "false";if (navigator.mimeTypes && navigator.mimeTypes.length) { x = navigator.mimeTypes['application/x-java-jnlp-file']; if (x) { javawsInstalled = 1; javaws12Installed=1; javaws142Installed=1; }}else { isIE = "true";}</SCRIPT>

This script looks at the navigator.mimeTypes object and the navigator.mimeTypes.length var to decide if the

browser is Netscape or IE. If length is 0, it is assumed the browser is IE, as with IE the navigator.mimeTypes array isdefined but always empty. If length is non-zero, then the browser is assumed to by Netscape and the JNLP MIME type is checked tosee if it exists on Netscape. If so, javawsInstalled, javaws12Installed, and javaws142Installed are all set to 1.With Netscape it is not possible to determine which particular version of JAWS is installed, so all three variables are set to 1.

Detecting if JavaWeb Start is installed on IE, and if so, the version

The above JavaScript should be followed by a VBScript that sets variables related to Internet Explorer browers:

<SCRIPT LANGUAGE="VBScript">on error resume nextIf isIE = "true" Then If Not(IsObject(CreateObject("JavaWebStart.isInstalled"))) Then javawsInstalled = 0 Else javawsInstalled = 1 End If If Not(IsObject(CreateObject("JavaWebStart.isInstalled.2"))) Then javaws12Installed = 0 Else javaws12Installed = 1 End If If Not(IsObject(CreateObject("JavaWebStart.isInstalled.3"))) Then javaws142Installed = 0 Else javaws142Installed = 1 End If End If</SCRIPT>

This VBScript is executed if the variable isIE from the preceeding JavaScript is "true"; i.e., if the end-user's browser is InternetExplorer. This script instantiates the isInstalled COM object in JavaWebStart.dll, and this object determines two things:

whether the client machine has any version of JAWS installed;●

whether the client machine has version 1.2 of JAWS installed;●

whether the client machine has versions 1.4.2 of JAWS installed.●

After the above two scripts have been executed, the variables javawsInstalled, javaws12Installed, andjavaws142Installed will be set to either 1 or 0, as follows:

Browser javawsInstalled javaws12Installed javaws142InstalledInternetExplorer

1 if any version of JAWS isinstalled; 0 otherwise.

1 if JAWS 1.2 is installed; 0otherwise.

1 if JAWS 1.4.2 is installed; 0otherwise.

NetscapeNavigator

1 if any version of JAWS isinstalled; 0 otherwise.

1 if any version of JAWS isinstalled; 0 otherwise.

1 if any version of JAWS isinstalled; 0 otherwise.

Launching the application if JAWS is Installed�or providing a link for auto-install orgeneral download page

An additional JavaScript can be used to decide whether to:

provide a link to the application's jnlp file (i.e., JAWS is installed);●

initiate auto-download of JRE 1.4.2, which includes JAWS (i.e., JAWS is not installed and the user is running IE onWindows);

or provide a link to the general download page for the 1.4.2 SDK/JRE (i.e., JAWS is not installed and the user is not runningIE on Windows).

The following JavaScript handles these scenarios:

<SCRIPT LANGUAGE="JavaScript">

/* Note that the logic below always launches the JNLP application *if the browser is Gecko based. This is because it is not possible *to detect MIME type application/x-java-jnlp-file on Gecko-based browsers. */if (javawsInstalled || (navigator.userAgent.indexOf("Gecko") !=-1)) { document.write("<a href=http://www.yyy.zzz/app.jnlp>Launch the application</a>");} else { document.write("Click "); document.write("<a href=http://dlres.java.sun.com/PluginBrowserCheck? pass=http://www.yyy.zzz/download.html& fail=http://java.sun.com/j2se/1.4.2/download.html>here</a> "); document.write("to download and install JRE 1.4.2 and the application.");}</SCRIPT>

Notes:The script only uses javawsInstalled, not javaws12Installedor javaws142Installed.

1.

The line breaks following '?' and '&' are for readability purposes only; in anactual script there should be no breaks in the href string.

2.

If javawsInstalled is 1, indicating that JAWS is already available on the client, then the script provides a link to theapplication's jnlp file. If JAWS is not installed on the client, the script instead provides a link to the PluginBrowserCheckprogram on the java.sun.com web site. PluginBrowserCheck checks whether the client uses Internet Explorer on aMicrosoft Windows platform. If so, PluginBrowserCheck sends the user to the auto-install pagehttp://www.yyy.zzz/download.html. (See the next section, Creating an auto-install page, for how to create an auto-installpage for IE running on Windows.) If PluginBrowserCheck determines the user is not using Internet Explorer on MicrosoftWindows, the user is redirected to the 1.4.2 JRE general download page on java.sun.com.

Creating an auto-install page

Note:For a complete list of JRE releases that can be autodownloaded via a .cab file,as mentioned below, see Autodownload Files (Windows Only).

The download.html file should be staged on the server side. It contains special OBJECT and PARAM tags that will download tothe client an auto-installer for J2RE 1.4.2. Along with JAWS, an ActiveX control will be downloaded to the client. The ActiveXcontrol will launch the application using the newly installed JAWS. Here is a sample download.html file:

<HTML><BODY><OBJECTCODEBASE="http://java.sun.com/products/plugin/autodl/jinstall-1_4_2-windows-i586.cab" CLASSID="clsid:5852F5ED-8BF4-11D4-A245-0080C6F74284" HEIGHT=0 WIDTH=0><PARAM NAME="app" VALUE="http://www.yyy.zzz/app.jnlp"><PARAM NAME="back" VALUE="true"><!-- Alternate HTML for browsers which cannot instantiate the object --><A HREF="http://java.sun.com/j2se/1.4.2/download.html">Download Java Web Start</A></OBJECT></BODY></HTML>

This OBJECT tag fetches a .cab file that contains an auto-installer for JRE 1.4.2. (Note that this .cab file will not be availableuntil the GA release of the 1.4.2 SDK/JRE.) The PARAM tags specify the location of the application's jnlp file so that it may beautomatically launched after the JRE is installed on the client.

Application Development Considerations

This chapter includes the following topics:

Introduction●

Retrieving Resources from JAR files●

Security and Code Signing●

Signing JAR Files With a Test Certificate●

How to Encode JNLP Files●

Dynamic Download of HTTPS Certificates●

Introduction

Developing applications for deployment with Java Web Start is generally the same as developingstand-alone applications for the Java 2 platform. For instance, the entry point for the application is thestandard public static void main(String[] argv).

However, in order to support Web deployment�automatic download and launching of an application�andto ensure that an application can run in a secure sandbox, there are some additional considerations:

An application must be delivered as a set of JAR files.●

All application resources, such as files and images must be stored in JAR files; and they must bereferenced using the getResource mechanism in the Java 2 platform (see below).

If an application is written to run in a secure sandbox, it must follow these restrictions:

No access to local disk.❍

All JAR files must be downloaded from the same host.❍

Network connections are enabled only to the host from which the JAR files are downloaded.❍

No security manager can be installed.❍

No native libraries may be used.❍

Limited access to system properties. The application has read/write access to all systemproperties defined in the JNLP File, as well as read-only access to the same set of propertiesthat an Applet has access to.

An application is allowed to use the System.exit call. ●

An application that needs unrestricted access to the system will need to be delivered in a set ofsigned JAR files. All entries in each JAR file must be signed.

Retrieving Resources from JAR files

Java Web Start only transfers JAR files from the Web server to the client machine. It determines whereto store the JAR files on the local machine. Thus, an application cannot use disk-relative references toresources such as images and configuration files.

All application resources must be retrieved from the JAR files specified in the resources section ofthe JNLP file, or retrieved explicitly using an HTTP request to the Web server. Storing resources in JARfiles is recommended, since they will be cached on the local machine by Java Web Start.

The following code example shows how to retrieve images from a JAR file:

// Get current classloader ClassLoader cl = this.getClass().getClassLoader(); // Create icons Icon saveIcon = new ImageIcon(cl.getResource("images/save.gif")); Icon cutIcon = new ImageIcon(cl.getResource("images/cut.gif")); ...

The example assumes that the following entries exist in one of the JAR files for the application:

images/save.gifimages/cut.gif

Security and Code Signing

Java Web Start addresses the security issues:

Protecting users against malicious code (intentional & unintentional) that may affect local files;●

Protecting enterprises against code that may attempt to access or destroy data on networks.●

Applications launched with Java Web Start are, by default, run in a restricted environment where theyhave limited access to local computing resources, such as storage devices and the local network. In thissandbox environment, Java Web Start can guarantee that a downloaded and potentially untrustedapplication cannot compromise the security of the local files or the network.

An additional security feature supported by Java Web Start is digital code signing. If an application beinginvoked is delivered in one or more signed JAR files, Java Web Start will verify that the contents of theJAR file have not been modified since they were signed. If verification of a digital signature fails, JavaWeb Start will not run the application, since it may have been compromised by a third-party.

The support for code signing is important for both users and for application service providers. Thisservice makes it possible for users to verify that an application comes from a trusted source. Because theapplication service provider signs the code, both can be ensured that no other party can impersonate theapplication on the Web. A signed application that is trusted by the user can also request additional systemprivileges, such as access to a local disk.

Java Web Start presents a dialog displaying the application's origin, based on the signer's certificate,before the application is launched. This allows the user to make an informed decision about whether or

not to grant additional privileges to the downloaded code.

By including the following settings in the JNLP file, an application can request full access to a clientsystem if all its JAR files are signed :

<security> <all-permissions/></security>

The implementation of code signing in Java Web Start is based on the security API in the core Java 2Platform. The Java 2 SE JRE 1.4.2 supports code signing with the SHA1withDSA and MD5withRSAalgorithms.

Developers sign code for use with Java Web Start in the same way as for Java Applets�by using thestandard jarsigner tool from the Java 2 SE SDK. The documentation for the jarsigner toolprovides examples of how to sign code and create test certificates, and it discusses other issues related tosigning.

Java Web Start also supports use of the Netscape signtool used with SDK/JRE 1.4.2. See theNetscape Web site for details: http://developer.netscape.com/software/signedobj/

Signing JAR Files With a Test Certificate

Here are the steps needed to sign a JAR file with a test certificate:

1. Make sure that you have an SDK 1.4.2 keytool and jarsigner in your path. These tools arelocated in the SDK bin directory.

2. Create a new key in a new keystore as follows:

keytool -genkey -keystore myKeystore -alias myself

You will get prompted for a information about the new key, such as password, name, etc.This will create the myKeystore file on disk.

3. Then create a self-signed test certificate as follows:

keytool -selfcert -alias myself -keystore myKeystore

This will prompt for the password. Generating the certificate may take a few minutes.

4. Check to make sure that everything is okay. To list the contents of the keystore, use this command:

keytool -list -keystore myKeystore

It should list something like:

Keystore type: jksKeystore provider: SUN

Your keystore contains 1 entry:

myself, Tue Jan 23 19:29:32 PST 2001, keyEntry,Certificate fingerprint (MD5):C2:E9:BF:F9:D3:DF:4C:8F:3C:5F:22:9E:AF:0B:42:9D

5. Finally, sign the JAR file with the test certificate as follows:

jarsigner -keystore myKeystore test.jar myself

Repeat this step with all of your JAR files.

Note that a self-signed test certificate should only be used for internal testing, since it does not guaranteethe identity of the user and therefore cannot be trusted. A trust-worthy certificate can be obtained from acertificate authority, such as VeriSign or Thawte, and should be used when the application is put intoproduction.

How to Encode JNLP Files

Beginning with Java Web Start version 1.2, JNLP files may be encoded in any character encodingsupported by the J2SE platform. (See the J2SE documentation for a list of supported encodings.)

To encode a JNLP file, specify an encoding in the XML prolog of that file. For example, the followingline indicates that the JNLP file will be encoded in UTF-16.

<?xml version="1.0" encoding="utf-16"?>

The XML prolog itself must be UTF-8-encoded.

Dynamic Download of HTTPS Certificates

Beginning with 1.4.2, Java Web Start dynamically imports certificates in much the same way as browsersdo. In order to make this work, Java Web Start now sets its own https handler, using thejava.protocol.handler.pkgs system properties, to initialize defaults forSSLSocketFactory and HostnameVerifier. It sets the defaults withHttpsURLConnection.setDefaultSSLSocketFactory andHttpsURLConnection.setDefaultHostnameVerifier.

If your application uses those two method, make sure they are called after the Java Web Start httpshandler is initialized, otherwise your custom handler will be replaced by the Java Web Start defaulthandler. You can ensure that your own customized SSLSocketFactory andHostnameVerifiter are used by doing either of the following:

Installing your own https handler, which will completely replace the Java Web Start https handler(for more information, see A New Era for Java Protocol Handlers);

1.

Calling HttpsURLConnection.setDefaultSSLSocketFactory orHttpsURLConnection.setDefaultHostnameVerifier only after the first https urlobject is created, which will execute the Java Web Start https handler initialization code first.

2.

Packaging an Application for EasyDeployment

The Developer's Pack contains a servlet that can be used to bundle a JNLP-deployed application in aWeb Archive (WAR) file. See Packaging JNLP Applications in a Web Archive

JNLP File Syntax

This chapter covers the following topics:

Introduction●

Example●

JNLP Elements

jnlp Element❍

information Element❍

security Element❍

resources Element❍

application-desc Element❍

applet-desc Element❍

IntroductionThe format used in this release is that specified in the Java Network Launching Protocol and API (JNLP)Specification v1.0.1. This document describes the most commonly used elements of a JNLP file. For acomplete description of the format, refer to the specification.

The JNLP file is an XML document. The following shows a complete example of a JNLP file.

Example<?xml version="1.0" encoding="utf-8"?><!-- JNLP File for SwingSet2 Demo Application --><jnlp spec="1.0+" codebase="http://my_company.com/jaws/apps" href="swingset2.jnlp"> <information> <title>SwingSet2 Demo Application</title> <vendor>Sun Microsystems, Inc.</vendor> <homepage href="docs/help.html"/> <description>SwingSet2 Demo Application</description> <description kind="short">A demo of the capabilities of the Swing

Graphical User Interface.</description> <icon href="images/swingset2.jpg"/> <icon kind="splash" href="images/splash.gif"/> <offline-allowed/> </information> <security> <all-permissions/> </security> <resources> <j2se version="1.4.2"/> <jar href="lib/SwingSet2.jar"/> </resources> <application-desc main-class="SwingSet2"/></jnlp>

The example shows the basic outline of the document. The root element is jnlp, which has foursubelements: information, security, resources, and application-desc. In addition, JavaWeb Start also supports launching Applets by using the applet-desc element. The elements aredescribed in more detail below.

JNLP Elements

jnlp Element

spec attribute: This attribute must be 1.0 or higher to work with this release. The defaultvalue is "1.0+". Thus, it can typically be omited.

codebase attribute: All relative URLs specified in href attributes in the JNLP file areusing this URL as a base.

href attribute: This is a URL pointing to the location of the JNLP file itself. Java WebStart requires this attribute to be set in order for the application to be included in theApplication Manager.

information Element

title element: The name of the application.

vendor element: The name of the vendor of the application.

homepage element: Contains a single attribute, href, which is a URL locating the homepage for the Application. It is used by the Application Manager to point the user to a Webpage where more information about the application can be found.

description element: A short statement about the application. Description elements areoptional. The kind attribute defines how the description should be used. It can have one ofthe following values:

one-line: If a reference to the application is going to appear on one row in a list or atable, this description will be used.

short: If a reference to the application is going to be displayed in a situation wherethere is room for a paragraph, this description is used.

tooltip: If a reference to the application is going to appear in a tooltip, this descriptionis used.

Only one description element of each kind can be specified. A description element without akind is used as a default value. Thus, if Java Web Start needs a description of kind short,and it is not specified in the JNLP file, then the text from the description without an attributeis used.

All descriptions contain plain text. No formatting, such as with HTML tags, is supported.

icon element: Contains an HTTP URL to an image file in either GIF or JPEG format. Theicons are used to represents the application

during launch when Java Web Start presents the application to the user;●

in the Application Manager;●

in desktop shortcuts.●

A 64x64 icon is shown during download; in the Application Manager and in desktopshortcuts a 32x32 icon is used. Java Web Start automatically resizes an icon to theappropriate size.

Optional width and height attributes can be used to indicate the size of the images.

The optional kind="splash" attribute may be used in an icon element to indicate thatthe image is to be used as a "splash" screen during the launch of an application. If the JNLPfile does not contain an icon element with a kind="splash" attribute, but does containanother icon tag, Java Web Start will display a splash screen consisting of the imagespecified by the icon element on the left and the application's title and vendor on the right.

If the JNLP file does not contain any icon images, the splash image will consist of theapplication's title and vendor, as taken from the JNLP file.

A splash image will be surrounded by a border defined by Java Web Start.

The first time an application is launched following the addition or modification of the iconelement in the JNLP file, the old splash image will still be displayed. The new splash imagewill appear on the second and subsequent launches of the application.

offline-allowed element: The optional offline-allowed element indicates if theapplication can be launched offline.

Applications not marked offline in the JNLP file will not be launched by the ApplicationManager. By default Application Manager only launches an application if the client systemis online.

The offline-allowed element also controls how Java Web Start checks for an update

to an application. If the element is not specified�i.e., the application is required to be onlineto run�Java Web Start will always check for an updated version before launching theapplication. And if an update is found, the new application will be downloaded andlaunched. Thus, it is guaranteed that the user always runs the latest version of theapplication. The application, however, must be run online.

If offline-allowed is specified, Java Web Start will also check to see if an update isavailable. However, if the application is already downloaded the check will timeout after afew seconds, in which case the cached application will be launched instead. Given areasonable fast server connection, the lastest version of the application will usually be run,but it is not guaranteed. The application, however, can be run offline.

security Element

Each application is, by default, run in a restricted execution environment, similar to theApplet sandbox. The security element can be used to request unrestricted access.

If the all-permissions element is specified, the application will have full access to theclient machine and local network. If an application requests full access, then all JAR filesmust be signed. The user will be prompted to accept the certificate the first time theapplication is launched.

resources Element

The resources element is used to specify all the resources, such as Java class files, nativelibraries, and system properties, that are part of the application. A resource definition can berestricted to a specific operating system, architecture, or locale using the os, arch, andlocale attributes.

The resources element has six different possible subelements: jar, nativelib, j2se,property, package, and extension. The package and extension elements arenot discussed in this developer's guide. See the Java Network Launching Protocol and API(JNLP) Specification v1.0.1 for details.

A jar element specifies a JAR file that is part of the application's classpath. For example:

<jar href="myjar.jar"/>

The jar file will be loaded into the JVM using a ClassLoader object. The jar file willtypically contain Java classes that contain the code for the particular application, but canalso contain other resources, such as icons and configuration files, that are available throughthe getResource mechanism.

A nativelib element specifies a JAR file that contains native libraries. For example:

<nativelib href="lib/windows/corelib.jar"/>

The JNLP client must ensure that each file entry in the root directory of the JAR file (i.e., /)can be loaded into the running process using the System.loadLibrary method. Each

entry must contain a platform-dependent shared library with the correct naming convention,e.g., *.dll on Windows or lib*.so on Solaris/Linux. The application is responsible fordoing the actual call to System.loadLibrary.

Native libraries would typically be included in a resources element that is geared towarda particular operating system and architecture. For example:

<resources os="SunOS" arch="sparc"> <nativelib href="lib/solaris/corelibs.jar"/> </resource>

By default, jar and nativelib resources will be downloaded eagerly, i.e., they aredownloaded and available locally to the JVM running the application before the applicationis launched. The jar and nativelib elements also allow a resource to be specified aslazy. This means the resource does not have to be downloaded onto the client systembefore the application is launched.

The download attribute is used to control whether a resource is downloaded eagerly orlazily. For example:

<jar href="sound.jar" download="lazy"/> <nativelib href="native-sound.jar" download="eager"/>

The j2se element specifies what Java 2 SE Runtime Environment (JRE) versions anapplication is supported on, as well as standard parameters to the Java Virtual Machine. Ifseveral JREs can are specified, this indicates a prioritized list of the supported JREs, withthe most preferred version first. For example:

<j2se version="1.3" initial-heap-size="64m"/> <j2se version="1.4+"/>

The version attribute refers, by default, to a platform (specification) version of the Java 2platform. Currently defined platform version are 1.2, 1.3, and 1.4. (A platform version mayoptionally contain a micro version number; e.g., 1.4.2.)

Exact product versions (implementation versions) may also be specified�e.g., 1.3.1_01 or1.4.2-beta by Sun Microsystems, Inc.�by including the href attribute. E.g.,

<j2se version="1.3.1_01"href="http://java.sun.com/products/autodl/j2se"/

or

<j2se version="1.4.2-beta"href="http://java.sun.com/products/autodl/j2se"/>

If a platform version is specified (i.e., no href attribute is provided), Java Web Start willnot consider an installed non-FCS (i.e., milestone) JRE as a match. E.g., a request of theform

<j2se version="1.4+">

would not consider an installed 1.4.1-ea or 1.4.2-beta JRE as a match for the request.Starting with 1.3.0, a JRE from Sun Microsystems, Inc., is by convention a non-FCS(milestone) JRE if there is a dash (-) in the version string.

The property element defines a system property that will be available through theSystem.getProperty and System.getProperties methods. It has two requiredattributes: name and value. For example:

<property name="key" value="overwritten"/>

application-desc Element

The application element indicates that the JNLP file is launching an application (asopposed to an applet). The application element has an optional attribute, main-class,which can be used to specify the name of the application's main class, i.e., the class thatcontains the public static void main(String argv[]) method whereexecution must begin.

The main-class attribute can be omitted if the first JAR file specified in the JNLP filecontains a manifest file containing the main class.

Arguments can be specified to the application by including one or more nested argumentelements. For example:

<application-desc main-class="Main"> <argument>arg1</argument> <argument>arg2</argument> </application-desc>

applet-desc Element

Java Web Start has support for launching Java applets. This support provides easy migrationof existing code to Java Web Start.

An applet is launched using the applet-desc element instead of theapplication-desc element. For example:

<applet-desc documentBase="http://..." name="TimePilot" main-class="TimePilot.TimePilotApp" width="527" height="428"> <param name="key1" value="value1"/> <param name="key2" value="value2"/> </applet-desc>

The JAR files that make up the applet are described using the resources element as for

applications. The documentBase must be provided explicitly since a JNLP file is notembedded in an HTML page. The rest of the attributes correspond to the respective HTMLapplet tag elements.

The main-class attribute is used instead of the code attribute. The main-classattribute is assigned the name of the Applet class (without the .class extension). Thisattribute can be omitted if the Applet class can be found from the Main-Class manifestentry in the main JAR file.

Note: Applets must be packaged in JAR files in order to work with Java Web Start.

JNLP API Examples

This chapter includes the following topics:

Introduction●

Using a BasicService Service●

Using a ClipboardService Service●

Using a DownloadService Service●

Using a FileOpenService Service●

Using a FileSaveService Service●

Using a PrintService Service●

Using a PersistenceService Service●

Using FileContents●

Using a JNLPRandomAccessFile●

Introduction

The JNLP API is designed to provide additional information to the application that would otherwise not be available usingthe standard Java 2 SE API. The following code examples show how the following services can be used: BasicService,ClipboardService, DownloadService, FileOpenService, FileSaveService, PrintService, andPersistenceService.

The public classes and interfaces in the JNLP API are included in the jnlp.jar file. This JAR file must be included in theclasspath when compiling source files that use the JNLP API. For example on Windows:

javac -classpath .;jnlp.jar *.java

The jnlp.jar file is included in the JNLP Developers Pack.

Using a BasicService Service

The javax.jnlp.BasicService service provides a set of methods for querying and interacting with the environmentsimilar to what the AppletContext provides for a Java Applet.

The showURL method uses the JNLP API to direct the default browser on the platform to show the given URL. The methodreturns true if the request succeeds, otherwise false.

import javax.jnlp.*; ...

// Method to show a URL boolean showURL(URL url) { try { // Lookup the javax.jnlp.BasicService object BasicService bs =(BasicService)ServiceManager.lookup("javax.jnlp.BasicService"); // Invoke the showDocument method

return bs.showDocument(url); } catch(UnavailableServiceException ue) { // Service is not supported return false; } }

Using a ClipboardService Service

The javax.jnlp.ClipboardService service provides methods for accessing the shared system-wide clipboard, evenfor applications that are running in the restricted execution environment.

Java Web Start will warn the user of the potential security risk of letting an untrusted application access potentiallyconfidential information stored in the clipboard, or overwriting contents stored in the clipboard.

import javax.jnlp; ...

private ClipboardService cs;

try { cs = (ClipboardService)ServiceManager.lookup ("javax.jnlp.ClipboardService"); } catch (UnavailableServiceException e) { cs = null; }

if (cs != null) { // set the system clipboard contents to a string selection StringSelection ss = new StringSelection("Java Web Start!"); cs.setContents(ss); // get the contents of the system clipboard and print them Transferable tr = cs.getContents(); if (tr.isDataFlavorSupported(DataFlavor.stringFlavor)) { try { String s = (String)tr.getTransferData(DataFlavor.stringFlavor); System.out.println("Clipboard contents: " + s); } catch (Exception e) { e.printStackTrace(); } } }

Using a DownloadService Service

The javax.jnlp.DownloadService service allows an application to control how its own resources are cached.

The service allows an application to determine which of its resources are cached, to force resources to be cached, and toremove resources from the cache.

import javax.jnlp.*; ...

DownloadService ds;

try { ds = (DownloadService)ServiceManager.lookup("javax.jnlp.DownloadService"); } catch (UnavailableServiceException e) { ds = null; }

if (ds != null) {

try { // determine if a particular resource is cached URL url = newURL("http://java.sun.com/products/javawebstart/lib/draw.jar"); boolean cached = ds.isResourceCached(url, "1.0"); // remove the resource from the cache if (cached) { ds.removeResource(url, "1.0"); } // reload the resource into the cache DownloadServiceListener dsl = ds.getDefaultProgressWindow(); ds.loadResource(url, "1.0", dsl); } catch (Exception e) { e.printStackTrace(); } }

Using a FileOpenService Service

The javax.jnlp.FileOpenService service provides methods for importing files from the local disk, even forapplications that are running in the restricted execution environment.

This interface is designed to provide the same kind of of disk access to potentially untrusted Web-deployed applications thata Web developer has when using HTML. HTML forms support the inclusion of files by displaying a file open dialog.

import javax.jnlp.*; ...

FileOpenService fos;

try { fos = (FileOpenService)ServiceManager.lookup("javax.jnlp.FileOpenService"); } catch (UnavailableServiceException e) { fos = null; }

if (fos != null) { try { // ask user to select a file through this service FileContents fc = fos.openFileDialog(null, null); // ask user to select multiple files through this service FileContents[] fcs = fos.openMultiFileDialog(null, null); } catch (Exception e) { e.printStackTrace();

} }

Using a FileSaveService Service

The javax.jnlp.FileSaveService service provides methods for exporting files to the local disk, even forapplications that are running in the restricted execution environment.

This interface is designed to provide the same level of disk access to potentially untrusted Web-deployed applications that aWeb browser provides for contents that it is displaying. Most browsers provide a Save As... dialog as part of their userinterface.

import javax.jnlp.*; ...

FileSaveService fss; FileOpenService fos;

try { fos = (FileOpenService)ServiceManager.lookup("javax.jnlp.FileOpenService"); fss = (FileSaveService)ServiceManager.lookup ("javax.jnlp.FileSaveService"); } catch (UnavailableServiceException e) { fss = null; fos = null; }

if (fss != null && fos != null) { try { // get a file with FileOpenService FileContents fc = fos.openFileDialog(null, null); // one way to save a file FileContents newfc = fss.saveFileDialog(null, null, fc.getInputStream(), "newFileName.txt"); // another way to save a file FileContents newfc2 = fss.saveAsFileDialog(null, null, fc);

} catch (Exception e) { e.printStackTrace(); } }

Also see Using FileContents.

Using a PrintService Service

The javax.jnlp.PrintService service provides methods for access to printing, even for applications that are runningin the restricted execution environment.

Using this service, an application can submit a print job. Java Web Start will then show this request to the user and, ifaccepted, queue the request to the printer.

import javax.jnlp.*; ...

PrintService ps;

try { ps = (PrintService)ServiceManager.lookup("javax.jnlp.PrintService"); } catch (UnavailableServiceException e) { ps = null; }

if (ps != null) { try { // get the default PageFormat PageFormat pf = ps.getDefaultPage();

// ask the user to customize the PageFormat PageFormat newPf = ps.showPageFormatDialog(pf);

// print the document with the PageFormat above ps.print(new DocToPrint()); } catch (Exception e) { e.printStackTrace(); } }

// Code to construct the Printable Document class DocToPrint implements Printable { public int print(Graphics g, PageFormat pageformat, int PageIndex){ // code to generate what you want to print } }

Using a PersistenceService Service

The javax.jnlp.PersistenceService service provides methods for storing data locally on the client system, evenfor applications that are running in the restricted execution environment.

The service is designed to be somewhat similar to that which the cookie mechanism provides to HTML-based applications. Cookies allow a small amount of data to be stored locally on the client system. That data can be securely managed by thebrowser and can only be retrieved by HTML pages which originate from the same URL as the page that stored the data.

import javax.jnlp.*; ...

PersistenceService ps; BasicService bs;

try { ps =

(PersistenceService)ServiceManager.lookup("javax.jnlp.PersistenceService"); bs = (BasicService)ServiceManager.lookup("javax.jnlp.BasicService"); } catch (UnavailableServiceException e) { ps = null; bs = null; }

if (ps != null && bs != null) {

try { // find all the muffins for our URL URL codebase = bs.getCodeBase(); String [] muffins = ps.getNames(url);

// get the attributes (tags) for each of these muffins. // update the server's copy of the data if any muffins // are dirty int [] tags = new int[muffins.length]; URL [] muffinURLs = new URL[muffins.length]; for (int i = 0; i < muffins.length; i++) { muffinURLs[i] = new URL(codebase.toString() + muffins[i]); tags[i] = ps.getTag(muffinURLs[i]); // update the server if anything is tagged DIRTY if (tags[i] == PersistenceService.DIRTY) { doUpdateServer(muffinURLs[i]); } }

// read in the contents of a muffin and then delete it FileContents fc = ps.get(muffinURLs[0]); long maxsize = fc.getMaxLength(); byte [] buf = new byte[fc.getLength()]; InputStream is = fc.getInputStream(); long pos = 0; while((pos = is.read(buf, pos, buf.length - pos)) > 0) { // just loop } is.close();

ps.delete(muffinURLs[0]);

// re-create the muffin and repopulate its data ps.create(muffinURLs[0], maxsize); fc = ps.get(muffinURLs[0]); // don't append OutputStream os = fc.getOutputStream(false); os.write(buf); os.close();

} catch (Exception e) { e.printStackTrace(); } }

void doUpdateServer(URL url) {

// update the server's copy of the persistent data // represented by the given URL ... ps.setTag(url, PersistenceService.CACHED); }

Using FileContents

javax.jnlp.FileContents objects encapsulate the name and contents of a file. An object of this class is used by theFileOpenService, FileSaveService and PersistenceService. Here is an example of how an instance of aFileContents can be used to read from and write to a file:

import javax.jnlp.*; ...

FileOpenService fos;

//Initialize fos (see Using a FileOpenService Service example) ...

if (fos != null) {

try {

// get a FileContents object to work with from the // FileOpenService FileContents fc = fos.openFileDialog(null, null);

// get the InputStream from the file and read a few bytes byte [] buf = new byte[fc.getLength()]; InputStream is = fc.getInputStream(); int pos = 0; while ((pos = is.read(buf, pos, buf.length - pos)) > 0) { // just loop } is.close();

// get the OutputStream and write the file back out if (fc.canWrite()) { // don't append OutputStream os = fc.getOutputStream(false); os.write(buf); }

} catch (Exception e) { e.printStackTrace(); } }

Using a JNLPRandomAccessFile

Instances of javax.jnlp.JNLPRandomAccessFile support both reading and writing to a random access file. Arandom access file behaves like a large array of bytes stored in the file system. Here is an example of how an instance of aJNLPRandomAccessFile can be used to write to a random access file:

import javax.jnlp.*; ...

FileOpenService fos;

//Initialize fos (see Using a FileOpenService Service example) ...

if (fos != null) { try { // ask the user to choose a file to open FileContents fc = fos.openFileDialog(null, null);

// attempt to increase the maximum file length long grantedLength = fc.getLength(); if (grantedLength + 1024 > fc.getMaxLength()) { // attempt to increase the maximum file size defined by // the client grantedLength = fc.setMaxLength(grantedLength + 1024); }

// if we were able to increase the maximum allowable file size, // get a JNLPRandomAccessFile representation of the file, and // write to it if (fc.getMaxSize() > fc.getLength() && fc.canWrite()) { JNLPRandomAccessFile raf = fc.getRandomAccessFile("rw"); raf.seek(raf.length() - 1); raf.writeUTF("Java Web Start!"); raf.close(); } } catch (Exception e) { e.printStackTrace(); } }

Converting JNLP Files to Work With ThisRelease

The JNLP file format has not changed between the 1.0 and this release.

If your JNLP file is compatible with a version of Java Web Start that is lower than 1.0, please note thatthe JNLP file format has changed significantly. Below is a list of the most common modifications thatneeds to be applied to a 0.4 JNLP file to make it compatible with Java Web Start 1.0 or higher:

Set spec attribute to 1.0.●

Rename the unrestricted element to all-permissions.●

Rename the jre element to j2se and move this element inside the resources element (i.e.,make j2se a subelement of resources).

Converting JNLP files used with the 1.0-beta or 1.0-rc release only requires updating the spec attributeto "1.0".


Recommended