Java Web Start is a newer technology that aims to improve on the user experience of Java programs that are delivered over the Internet. Here are the principal differences between Java Web Start applications and applets.
To prepare an application for delivery by Java Web Start, you package it in one or more JAR files. Then you prepare a descriptor file in Java Network Launch Protocol (JNLP) format. Place these files on a web server. Next, make sure that your web server reports a MIME type of application/x-java-jnlp-file for files with extension .jnlp. (Browsers use the MIME type to determine which helper application to launch.) Consult your web server documentation for details. TIP
Let's try out Java Web Start to deliver the calculator application from Chapter 9. Follow these steps.
The JNLP APIFor a Java Web Start application to be granted full access to the local machine, the application must be digitally signed. (See Chapter 9 of Volume 2 for more information on digital signatures.) Just as with applets, an unsigned Java Web Start application that is downloaded from the Internet is inherently risky and runs in a sandbox, with minimal access to the local computer. However, with minimal security privileges, the JNLP API provides application developers some tools for accessing local resources. For example, there are services to load and save files, but they are quite restrictive. The application can't look at the file system and it can't specify file names. Instead, a file dialog is popped up, and the program user selects the file. Before the file dialog is popped up, the program user is alerted and must agree to proceed (see Figure 10-15). Furthermore, the API doesn't actually give the program access to a File object. In particular, the application has no way of finding out the file location. Thus, programmers are given the tools to implement standard "file open" and "file save" actions, but as much system information as possible is hidden from untrusted applications. Figure 10-15. A Java Web Start security advisoryThe API provides the following services:
To access a service, you use the ServiceManager, like this: FileSaveService service = (FileSaveService) ServiceManager.lookup("javax.jnlp .FileSaveService"); This call throws an UnavailableServiceException if the service is not available. NOTE
We now discuss the most useful JNLP services. To save a file, you provide suggestions for the initial path name and file extensions for the file dialog, the data to be saved, and a suggested file name. For example, service.saveFileDialog(".", new String[] { "txt" }, data, "calc.txt"); The data must be delivered in an InputStream. That can be somewhat tricky to arrange. The program in Example 10-13 uses the following strategy:
You will learn more about streams in Chapter 12. For now, you can just gloss over the details in the sample program. To read data from a file, you use the FileOpenService instead. Its openFileDialog receives suggestions for the initial path name and file extensions for the file dialog and returns a FileContents object. You can then call the getInputStream method to read the file data. If the user didn't choose a file, then the openFileDialog method returns null. FileOpenService service = (FileOpenService) ServiceManager.lookup("javax.jnlp .FileOpenService"); FileContents contents = service.openFileDialog(".", new String[] { "txt" }); if (contents != null) { InputStream in = contents.getInputStream(); . . . } To display a document on the default browser (similar to the showDocument method of an applet), use the BasicService interface. Note that some systems (in particular, many UNIX and Linux systems) may not have a default browser. BasicService service = (BasicService) ServiceManager.lookup("javax.jnlp.BasicService"); if (service.isWebBrowserSupported()) service.showDocument(url); else . . . A rudimentary PersistenceService lets an application store small amounts of configuration information and retrieve it when the application runs again. This service is necessary because an untrusted application cannot specify a location for a configuration file. The mechanism is similar to HTTP cookies. The persistent store uses URLs as keys. The URLs don't have to point to a real web resource. The service simply uses them as a convenient hierarchical naming scheme. For any given URL key, an application can store arbitrary binary data. (The store may restrict the size of the data block.) So that applications are isolated from each other, a particular application can only use URL keys that start with its codebase (as specified in the JNLP file). For example, if an application is downloaded from http://myserver.com/apps, then it can only use keys of the form http://myserver.com/apps/subkey1/subkey2/... Attempts to access other keys will fail. An application can call the getCodeBase method of the BasicService to find its codebase. You create a new key with the create method of the PersistenceService. URL url = new URL(codeBase, "mykey"); service.create(url, maxSize); To access the information associated with a particular key, call the get method. That method returns a FileContents object through which you can read and write the key data. For example, FileContents contents = service.get(url); InputStream in = contents.getInputStream(); OutputStream out = contents.getOutputStream(true); // true = overwrite Unfortunately, there is no convenient way to find out whether a key already exists or whether you need to create it. You can hope that the key exists and call get. If the call throws a FileNotFoundException, then you need to create the key. NOTE
The program in Example 10-13 is a simple enhancement of the calculator application. This calculator has a virtual paper tape that keeps track of all calculations. You can save and load the calculation history. To demonstrate the persistent store, the application lets you set the frame title. If you run the application again, it retrieves your title choice from the persistent store (see Figure 10-16). Example 10-13. WebStartCalculator.java1. import java.awt.*; 2. import java.awt.event.*; 3. import java.io.*; 4. import java.net.*; 5. import javax.swing.*; 6. import javax.swing.text.*; 7. import javax.jnlp.*; 8. 9. /** 10. A calculator with a calculation history that can be 11. deployed as a Java Web Start application. 12. */ 13. public class WebStartCalculator 14. { 15. public static void main(String[] args) 16. { 17. CalculatorFrame frame = new CalculatorFrame(); 18. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 19. frame.setVisible(true); 20. } 21. } 22. 23. /** 24. A frame with a calculator panel and a menu to load and 25. save the calculator history. 26. */ 27. class CalculatorFrame extends JFrame 28. { 29. public CalculatorFrame() 30. { 31. setTitle(); 32. panel = new CalculatorPanel(); 33. add(panel); 34. 35. JMenu fileMenu = new JMenu("File"); 36. 37. JMenuItem openItem = fileMenu.add("Open"); 38. openItem.addActionListener(new 39. ActionListener() 40. { 41. public void actionPerformed(ActionEvent event) 42. { 43. open(); 44. } 45. }); 46. 47. JMenuItem saveItem = fileMenu.add("Save"); 48. saveItem.addActionListener(new 49. ActionListener() 50. { 51. public void actionPerformed(ActionEvent event) 52. { 53. save(); 54. } 55. }); 56. JMenuBar menuBar = new JMenuBar(); 57. menuBar.add(fileMenu); 58. setJMenuBar(menuBar); 59. 60. pack(); 61. } 62. 63. /** 64. Gets the title from the persistent store or 65. asks the user for the title if there is no prior entry. 66. */ 67. public void setTitle() 68. { 69. try 70. { 71. String title = null; 72. 73. BasicService basic = (BasicService) ServiceManager.lookup("javax.jnlp .BasicService"); 74. URL codeBase = basic.getCodeBase(); 75. 76. PersistenceService service 77. = (PersistenceService) ServiceManager.lookup("javax.jnlp .PersistenceService"); 78. URL key = new URL(codeBase, "title"); 79. 80. try 81. { 82. FileContents contents = service.get(key); 83. InputStream in = contents.getInputStream(); 84. BufferedReader reader = new BufferedReader(new InputStreamReader(in)); 85. title = reader.readLine(); 86. } 87. catch (FileNotFoundException e) 88. { 89. title = JOptionPane.showInputDialog("Please supply a frame title:"); 90. if (title == null) return; 91. 92. service.create(key, 100); 93. FileContents contents = service.get(key); 94. OutputStream out = contents.getOutputStream(true); 95. PrintStream printOut = new PrintStream(out); 96. printOut.print(title); 97. } 98. setTitle(title); 99. } 100. catch (UnavailableServiceException e) 101. { 102. JOptionPane.showMessageDialog(this, e); 103. } 104. catch (MalformedURLException e) 105. { 106. JOptionPane.showMessageDialog(this, e); 107. } 108. catch (IOException e) 109. { 110. JOptionPane.showMessageDialog(this, e); 111. } 112. } 113. 114. /** 115. Opens a history file and updates the display. 116. */ 117. public void open() 118. { 119. try 120. { 121. FileOpenService service 122. = (FileOpenService) ServiceManager.lookup("javax.jnlp.FileOpenService"); 123. FileContents contents = service.openFileDialog(".", new String[] { "txt" }); 124. 125. JOptionPane.showMessageDialog(this, contents.getName()); 126. if (contents != null) 127. { 128. InputStream in = contents.getInputStream(); 129. BufferedReader reader = new BufferedReader(new InputStreamReader(in)); 130. String line; 131. while ((line = reader.readLine()) != null) 132. { 133. panel.append(line); 134. panel.append("\n"); 135. } 136. } 137. } 138. catch (UnavailableServiceException e) 139. { 140. JOptionPane.showMessageDialog(this, e); 141. } 142. catch (IOException e) 143. { 144. JOptionPane.showMessageDialog(this, e); 145. } 146. } 147. 148. /** 149. Saves the calculator history to a file. 150. */ 151. public void save() 152. { 153. try 154. { 155. ByteArrayOutputStream out = new ByteArrayOutputStream(); 156. PrintStream printOut = new PrintStream(out); 157. printOut.print(panel.getText()); 158. InputStream data = new ByteArrayInputStream(out.toByteArray()); 159. FileSaveService service 160. = (FileSaveService) ServiceManager.lookup("javax.jnlp.FileSaveService"); 161. service.saveFileDialog(".", new String[] { "txt" }, data, "calc.txt"); 162. } 163. catch (UnavailableServiceException e) 164. { 165. JOptionPane.showMessageDialog(this, e); 166. } 167. catch (IOException e) 168. { 169. JOptionPane.showMessageDialog(this, e); 170. } 171. } 172. 173. private CalculatorPanel panel; 174. } 175. 176. 177. /** 178. A panel with calculator buttons and a result display. 179. */ 180. class CalculatorPanel extends JPanel 181. { 182. /** 183. Lays out the panel. 184. */ 185. public CalculatorPanel() 186. { 187. setLayout(new BorderLayout()); 188. 189. result = 0; 190. lastCommand = "="; 191. start = true; 192. 193. // add the display 194. 195. display = new JTextArea(10, 20); 196. 197. add(new JScrollPane(display), BorderLayout.NORTH); 198. 199. ActionListener insert = new InsertAction(); 200. ActionListener command = new CommandAction(); 201. 202. // add the buttons in a 4 x 4 grid 203. 204. panel = new JPanel(); 205. panel.setLayout(new GridLayout(4, 4)); 206. 207. addButton("7", insert); 208. addButton("8", insert); 209. addButton("9", insert); 210. addButton("/", command); 211. 212. addButton("4", insert); 213. addButton("5", insert); 214. addButton("6", insert); 215. addButton("*", command); 216. 217. addButton("1", insert); 218. addButton("2", insert); 219. addButton("3", insert); 220. addButton("-", command); 221. 222. addButton("0", insert); 223. addButton(".", insert); 224. addButton("=", command); 225. addButton("+", command); 226. 227. add(panel, BorderLayout.CENTER); 228. } 229. 230. /** 231. Gets the history text. 232. @return the calculator history 233. */ 234. public String getText() 235. { 236. return display.getText(); 237. } 238. 239. /** 240. Appends a string to the history text. 241. @param s the string to append 242. */ 243. public void append(String s) 244. { 245. display.append(s); 246. } 247. 248. /** 249. Adds a button to the center panel. 250. @param label the button label 251. @param listener the button listener 252. */ 253. private void addButton(String label, ActionListener listener) 254. { 255. JButton button = new JButton(label); 256. button.addActionListener(listener); 257. panel.add(button); 258. } 259. 260. /** 261. This action inserts the button action string to the 262. end of the display text. 263. */ 264. private class InsertAction implements ActionListener 265. { 266. public void actionPerformed(ActionEvent event) 267. { 268. String input = event.getActionCommand(); 269. start = false; 270. display.append(input); 271. } 272. } 273. 274. /** 275. This action executes the command that the button 276. action string denotes. 277. */ 278. private class CommandAction implements ActionListener 279. { 280. public void actionPerformed(ActionEvent event) 281. { 282. String command = event.getActionCommand(); 283. 284. if (start) 285. { 286. if (command.equals("-")) 287. { 288. display.append(command); 289. start = false; 290. } 291. else 292. lastCommand = command; 293. } 294. else 295. { 296. try 297. { 298. int lines = display.getLineCount(); 299. int lineStart = display.getLineStartOffset(lines - 1); 300. int lineEnd = display.getLineEndOffset(lines - 1); 301. String value = display.getText(lineStart, lineEnd - lineStart); 302. display.append(" "); 303. display.append(command); 304. calculate(Double.parseDouble(value)); 305. if (command.equals("=")) 306. display.append("\n" + result); 307. lastCommand = command; 308. display.append("\n"); 309. start = true; 310. } 311. catch (BadLocationException e) 312. { 313. e.printStackTrace(); 314. } 315. } 316. } 317. } 318. 319. /** 320. Carries out the pending calculation. 321. @param x the value to be accumulated with the prior result. 322. */ 323. public void calculate(double x) 324. { 325. if (lastCommand.equals("+")) result += x; 326. else if (lastCommand.equals("-")) result -= x; 327. else if (lastCommand.equals("*")) result *= x; 328. else if (lastCommand.equals("/")) result /= x; 329. else if (lastCommand.equals("=")) result = x; 330. } 331. 332. private JTextArea display; 333. private JPanel panel; 334. private double result; 335. private String lastCommand; 336. private boolean start; 337. } javax.jnlp.ServiceManager
javax.jnlp.BasicService
javax.jnlp.FileContents
javax.jnlp.FileOpenService
javax.jnlp.FileSaveService
javax.jnlp.PersistenceService
Figure 10-16. The WebStartCalculator application |