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 Creating an auto-install page Application Development Considerations

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 Packaging an Application for Easy Deployment JNLP File Syntax

Introduction The jnlp Element The security Element The resources Element The application-desc Element The applet-desc Element JNLP API Examples

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 Appendices:

Converting JNLP Files to Work With This Release FAQ (Not available in PDF) JNLP API (JavaDoc) (Not available in PDF)

Overview

Java Web Start Technology

Java Web Start is a helper application that gets associated with a . When a user clicks on a link that points to a special launch file (JNLP file), it causes the browser to launch Java Web Start, which then automatically downloads, caches, and runs the given Java Technology-based application. The entire process 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 attractive platform 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 and then deployed on a wide variety of platforms, including Windows 98/NT/2000/ME/XP, Linux, and the SolarisTM Operating Environment. The Java platform has proven to be a very robust, productive, and expressive development platform, leading to a significant cost savings due to minimized development and testing costs. ● Java Web Start supports multiple revisions of the Java 2 platform, Standard Edition. Thus, an application 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 causing conflicts, and Java Web Start can automatically download and install a revision of the platform if an 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 be used for off-line operation of an application, where launching through the browser is often inconvenient 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 by default run in a protective environment (sandbox) with restricted access to local disk and network resources. 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-downloaded application 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 (JCP). Java Web Start is the reference implementation (RI) for the JNLP specification. The JNLP technology defines, among other things, a standard file format that describes how to launch an application called a JNLP file. Where to find Java Web Start

See the Java Web Start web site, http://java.sun.com/products/javawebstart/, for availability of Java Web Start downloads. The JNLP specification can be found at http://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. Java Web 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 Web server must be configured with support for a new MIME type as explained below.

Setting Up the Web Site

Introduction

Java Web Start leverages existing technology, such as the HTTP protocol and Web servers, so existing infrastructure for deploying HTML-based contents can be reused to deploy Java Technology-based applications using Java Web Start. In order to deploy your application to client machines, you must make sure that all files containing your application are accessible through a Web server. This typically amounts to copying one or more JAR files, along with a JNLP file, into the Web server's directories. The set-up required for enabling the Web site to support Java Web Start is very similar to deploying HTML-based contents. The only caveat is that a new MIME type needs to be configured for the Web server. Basic Steps

1. 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 the application/x-java-jnlp-file MIME type. Most Web browsers use the MIME type returned with the contents from the Web server to determine how to handle the particular content. The server must return application/x-java-jnlp-file MIME 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 Web server 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 the Application

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 Installedor 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 to launch application app.jnlp on a web site http://www.yyy.zzz, the page needs to include the following link: Launch the application 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 take account 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: 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 is defined but always empty. If length is non-zero, then the browser is assumed to by Netscape and the JNLP MIME type is checked to see 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:

This VBScript is executed if the variable isIE from the preceeding JavaScript is "true"; i.e., if the end-user's browser is Internet Explorer. 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, and javaws142Installed will be set to either 1 or 0, as follows: Browser javawsInstalled javaws12Installed javaws142Installed Internet 1 if any version of JAWS is 1 if JAWS 1.2 is installed; 0 1 if JAWS 1.4.2 is installed; 0 Explorer installed; 0 otherwise. otherwise. otherwise. Netscape 1 if any version of JAWS is 1 if any version of JAWS is 1 if any version of JAWS is Navigator installed; 0 otherwise. installed; 0 otherwise. installed; 0 otherwise.

Launching the application if JAWS is Installedor providing a link for auto-install or general 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 on Windows); ● 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 running IE on Windows). The following JavaScript handles these scenarios: Notes: 1. The script only uses javawsInstalled, not javaws12Installed or javaws142Installed. 2. The line breaks following '?' and '&' are for readability purposes only; in an actual script there should be no breaks in the href string.

If javawsInstalled is 1, indicating that JAWS is already available on the client, then the script provides a link to the application's jnlp file. If JAWS is not installed on the client, the script instead provides a link to the PluginBrowserCheck program on the java.sun.com web site. PluginBrowserCheck checks whether the client uses Internet Explorer on a Windows platform. If so, PluginBrowserCheck sends the user to the auto-install page http://www.yyy.zzz/download.html. (See the next section, Creating an auto-install page, for how to create an auto-install page for IE running on Windows.) If PluginBrowserCheck determines the user is not using Internet Explorer on Microsoft Windows, 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 to the client an auto-installer for J2RE 1.4.2. Along with JAWS, an ActiveX control will be downloaded to the client. The ActiveX control will launch the application using the newly installed JAWS. Here is a sample download.html file:

Download Java Web Start 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 available until 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 be automatically 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 developing stand-alone applications for the Java 2 platform. For instance, the entry point for the application is the standard public static void main(String[] argv). However, in order to support Web deploymentautomatic download and launching of an applicationand to 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 be referenced 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 system properties defined in the JNLP File, as well as read-only access to the same set of properties that 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 of signed 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 where to store the JAR files on the local machine. Thus, an application cannot use disk-relative references to resources such as images and configuration files. All application resources must be retrieved from the JAR files specified in the resources section of the JNLP file, or retrieved explicitly using an HTTP request to the Web server. Storing resources in JAR files 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.gif images/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 they have limited access to local computing resources, such as storage devices and the local network. In this sandbox environment, Java Web Start can guarantee that a downloaded and potentially untrusted application 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 being invoked is delivered in one or more signed JAR files, Java Web Start will verify that the contents of the JAR file have not been modified since they were signed. If verification of a digital signature fails, Java Web 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. This service makes it possible for users to verify that an application comes from a trusted source. Because the application service provider signs the code, both can be ensured that no other party can impersonate the application on the Web. A signed application that is trusted by the user can also request additional system privileges, 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 client system if all its JAR files are signed : The implementation of code signing in Java Web Start is based on the security API in the core Java 2 Platform. The Java 2 SE JRE 1.4.2 supports code signing with the SHA1withDSA and MD5withRSA algorithms. Developers sign code for use with Java Web Start in the same way as for Java Appletsby using the standard jarsigner tool from the Java 2 SE SDK. The documentation for the jarsigner tool provides examples of how to sign code and create test certificates, and it discusses other issues related to signing. Java Web Start also supports use of the Netscape signtool used with SDK/JRE 1.4.2. See the Netscape 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 are located 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: jks Keystore 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 guarantee the identity of the user and therefore cannot be trusted. A trust-worthy certificate can be obtained from a certificate authority, such as VeriSign or Thawte, and should be used when the application is put into production. How to Encode JNLP Files

Beginning with Java Web Start version 1.2, JNLP files may be encoded in any character encoding supported 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 following line indicates that the JNLP file will be encoded in 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 browsers do. In order to make this work, Java Web Start now sets its own https handler, using the java.protocol.handler.pkgs system properties, to initialize defaults for SSLSocketFactory and HostnameVerifier. It sets the defaults with HttpsURLConnection.setDefaultSSLSocketFactory and HttpsURLConnection.setDefaultHostnameVerifier. If your application uses those two method, make sure they are called after the Java Web Start https handler is initialized, otherwise your custom handler will be replaced by the Java Web Start default handler. You can ensure that your own customized SSLSocketFactory and HostnameVerifiter are used by doing either of the following: 1. 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); 2. Calling HttpsURLConnection.setDefaultSSLSocketFactory or HttpsURLConnection.setDefaultHostnameVerifier only after the first https url object is created, which will execute the Java Web Start https handler initialization code first.

Packaging an Application for Easy Deployment

The Developer's Pack contains a servlet that can be used to bundle a JNLP-deployed application in a Web 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 Introduction

The 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 a complete 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

SwingSet2 Demo Application Sun Microsystems, Inc. SwingSet2 Demo Application A demo of the capabilities of the Swing Graphical User Interface. The example shows the basic outline of the document. The root element is jnlp, which has four subelements: information, security, resources, and application-desc. In addition, Java Web Start also supports launching Applets by using the applet-desc element. The elements are described in more detail below. JNLP Elements jnlp Element

spec attribute: This attribute must be 1.0 or higher to work with this release. The default value is "1.0+". Thus, it can typically be omited. codebase attribute: All relative URLs specified in href attributes in the JNLP file are using this URL as a base. href attribute: This is a URL pointing to the location of the JNLP file itself. Java Web Start requires this attribute to be set in order for the application to be included in the Application 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 home page for the Application. It is used by the Application Manager to point the user to a Web page where more information about the application can be found. description element: A short statement about the application. Description elements are optional. The kind attribute defines how the description should be used. It can have one of the following values: ● one-line: If a reference to the application is going to appear on one row in a list or a table, this description will be used. ● short: If a reference to the application is going to be displayed in a situation where there is room for a paragraph, this description is used. ● tooltip: If a reference to the application is going to appear in a tooltip, this description is used. Only one description element of each kind can be specified. A description element without a kind 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 attribute is 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. The icons 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 desktop shortcuts a 32x32 icon is used. Java Web Start automatically resizes an icon to the appropriate 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 that the image is to be used as a "splash" screen during the launch of an application. If the JNLP file does not contain an icon element with a kind="splash" attribute, but does contain another icon tag, Java Web Start will display a splash screen consisting of the image specified 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 the application'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 icon element in the JNLP file, the old splash image will still be displayed. The new splash image will appear on the second and subsequent launches of the application. offline-allowed element: The optional offline-allowed element indicates if the application can be launched offline. Applications not marked offline in the JNLP file will not be launched by the Application Manager. By default Application Manager only launches an application if the client system is online. The offline-allowed element also controls how Java Web Start checks for an update to an application. If the element is not specifiedi.e., the application is required to be online to runJava Web Start will always check for an updated version before launching the application. And if an update is found, the new application will be downloaded and launched. Thus, it is guaranteed that the user always runs the latest version of the application. The application, however, must be run online. If offline-allowed is specified, Java Web Start will also check to see if an update is available. However, if the application is already downloaded the check will timeout after a few seconds, in which case the cached application will be launched instead. Given a reasonable 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 the Applet 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 the client machine and local network. If an application requests full access, then all JAR files must be signed. The user will be prompted to accept the certificate the first time the application is launched. resources Element

The resources element is used to specify all the resources, such as Java class files, native libraries, and system properties, that are part of the application. A resource definition can be restricted to a specific operating system, architecture, or locale using the os, arch, and locale attributes. The resources element has six different possible subelements: jar, nativelib, j2se, property, package, and extension. The package and extension elements are not 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: The jar file will be loaded into the JVM using a ClassLoader object. The jar file will typically contain Java classes that contain the code for the particular application, but can also contain other resources, such as icons and configuration files, that are available through the getResource mechanism. A nativelib element specifies a JAR file that contains native libraries. For example: 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 for doing the actual call to System.loadLibrary. Native libraries would typically be included in a resources element that is geared toward a particular operating system and architecture. For example: By default, jar and nativelib resources will be downloaded eagerly, i.e., they are downloaded and available locally to the JVM running the application before the application is launched. The jar and nativelib elements also allow a resource to be specified as lazy. This means the resource does not have to be downloaded onto the client system before the application is launched. The download attribute is used to control whether a resource is downloaded eagerly or lazily. For example: The j2se element specifies what Java 2 SE Runtime Environment (JRE) versions an application is supported on, as well as standard parameters to the . If several JREs can are specified, this indicates a prioritized list of the supported JREs, with the most preferred version first. For example: The version attribute refers, by default, to a platform (specification) version of the Java 2 platform. Currently defined platform version are 1.2, 1.3, and 1.4. (A platform version may optionally contain a micro version number; e.g., 1.4.2.) Exact product versions (implementation versions) may also be specifiede.g., 1.3.1_01 or 1.4.2-beta by , Inc.by including the href attribute. E.g., If a platform version is specified (i.e., no href attribute is provided), Java Web Start will not consider an installed non-FCS (i.e., milestone) JRE as a match. E.g., a request of the form 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 the System.getProperty and System.getProperties methods. It has two required attributes: name and value. For example: application-desc Element

The application element indicates that the JNLP file is launching an application (as opposed 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 that contains the public static void main(String argv[]) method where execution must begin. The main-class attribute can be omitted if the first JAR file specified in the JNLP file contains a manifest file containing the main class. Arguments can be specified to the application by including one or more nested argument elements. For example: arg1 arg2 applet-desc Element

Java Web Start has support for launching Java applets. This support provides easy migration of existing code to Java Web Start. An applet is launched using the applet-desc element instead of the application-desc element. For example: 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 not embedded in an HTML page. The rest of the attributes correspond to the respective HTML applet tag elements. The main-class attribute is used instead of the code attribute. The main-class attribute is assigned the name of the Applet class (without the .class extension). This attribute can be omitted if the Applet class can be found from the Main-Class manifest entry 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 using the standard Java 2 SE API. The following code examples show how the following services can be used: BasicService, ClipboardService, DownloadService, FileOpenService, FileSaveService, PrintService, and PersistenceService. The public classes and interfaces in the JNLP API are included in the jnlp.jar file. This JAR file must be included in the classpath 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 environment similar to what the AppletContext provides for a . The showURL method uses the JNLP API to direct the default browser on the platform to show the given URL. The method returns 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, even for 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 potentially confidential 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 to remove resources from the . 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 = new URL("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 for applications 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 that a 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 for applications 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 a Web browser provides for contents that it is displaying. Most browsers provide a Save As... dialog as part of their user interface. 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 running in 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, if accepted, 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, even for 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 the browser 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 the FileOpenService, FileSaveService and PersistenceService. Here is an example of how an instance of a FileContents 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. A random access file behaves like a large array of bytes stored in the file system. Here is an example of how an instance of a JNLPRandomAccessFile 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 This Release

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 that the JNLP file format has changed significantly. Below is a list of the most common modifications that needs 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 attribute to "1.0".