KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > WebPad


1 /*
2  * @(#)WebPad.java 1.6 05/11/17
3  *
4  * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are met:
8  *
9  * -Redistribution of source code must retain the above copyright notice, this
10  * list of conditions and the following disclaimer.
11  *
12  * -Redistribution in binary form must reproduce the above copyright notice,
13  * this list of conditions and the following disclaimer in the documentation
14  * and/or other materials provided with the distribution.
15  *
16  * Neither the name of Sun Microsystems, Inc. or the names of contributors may
17  * be used to endorse or promote products derived from this software without
18  * specific prior written permission.
19  *
20  * This software is provided "AS IS," without a warranty of any kind. ALL
21  * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
22  * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
23  * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
24  * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
25  * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
26  * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
27  * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
28  * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
29  * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
30  * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
31  *
32  * You acknowledge that this software is not designed, licensed or intended
33  * for use in the design, construction, operation or maintenance of any
34  * nuclear facility.
35  */

36
37 import java.awt.*;
38 import java.awt.event.*;
39
40 import java.util.Enumeration JavaDoc;
41 import java.util.Vector JavaDoc;
42
43 import javax.swing.*;
44
45 import javax.jnlp.BasicService;
46 import javax.jnlp.ServiceManager;
47 import javax.jnlp.PersistenceService;
48 import javax.jnlp.UnavailableServiceException;
49 import javax.jnlp.FileContents;
50 import java.io.*;
51 import java.net.*;
52
53
54 /**
55  * Demonstrates the JLF Actions classes.
56  *
57  * - The actions use the JLF icons, text and mnemonics.
58  * - Actions are shared between the JToolBar and JMenuBar.
59  * - if an Action is enabled/disabled then it will be disabled in both places.
60  * - When a mouse is over a toolbar button or a menu item, then the long
61  * description of that action will be displayed in the status bar.
62  * - Abstracts the actionPerformed method from the Action class to a handler.
63  *
64  *
65  */

66
67 public class WebPad extends JFrame implements ActionListener {
68     
69     // These are the actions defined for the application
70
private AboutAction aboutAction;
71     private CutAction cutAction;
72     private CopyAction copyAction;
73     private PasteAction pasteAction;
74     private OpenAction openAction;
75     private SaveAction saveAction;
76     private SaveAsAction saveAsAction;
77     private PrintAction printAction;
78     private HelpAction helpAction;
79     private ExitAction exitAction;
80     private PublishAction publishAction;
81     private ShowAction showAction;
82
83     private ClassLoader JavaDoc cl;
84     // Vector for holding all the actions.
85
private Vector JavaDoc actions;
86     
87     // Status bar
88
private JLabel status;
89     
90     // Text area which acts as a clipboard.
91
private JTextArea textArea;
92     
93     // This adapter handles Mouse over messages on toolbar buttons and
94
// menu items.
95
private MouseHandler mouseHandler;
96     
97     // Popup Menu with the actions.
98
private JPopupMenu popup;
99    
100     private PersistenceService ps;
101     private BasicService bs;
102     private FileContents fc;
103  
104     public WebPad() {
105         super("WebPad");
106
107         cl = this.getClass().getClassLoader();
108         initActions();
109         
110         status = createStatusBar();
111         mouseHandler = new MouseHandler(status);
112         
113         setJMenuBar(createMenu());
114         getContentPane().add(createToolBar(), BorderLayout.NORTH);
115         getContentPane().add(createPanel(), BorderLayout.CENTER);
116         getContentPane().add(status, BorderLayout.SOUTH);
117         
118         popup = createPopupMenu();
119         
120         initPersistence();
121
122         addWindowListener(new WindowAdapter() {
123             public void windowClosing(WindowEvent evt) {
124             System.exit(0);
125             }
126         });
127         
128     }
129     
130     // This method should be called before creating the UI
131
// to create all the Actions
132
private void initActions() {
133         actions = new Vector JavaDoc();
134         
135         aboutAction = new AboutAction();
136         registerAction(aboutAction);
137         
138         cutAction = new CutAction();
139         registerAction(cutAction);
140         
141         copyAction = new CopyAction();
142         registerAction(copyAction);
143         
144         pasteAction = new PasteAction();
145         registerAction(pasteAction);
146     
147     
148         openAction = new OpenAction();
149     registerAction(openAction);
150     
151     saveAction = new SaveAction();
152     registerAction(saveAction);
153     
154     saveAsAction = new SaveAsAction();
155     registerAction(saveAsAction);
156         
157         printAction = new PrintAction();
158         registerAction(printAction);
159     
160     exitAction = new ExitAction();
161     registerAction(exitAction);
162     
163     helpAction = new HelpAction();
164     registerAction(helpAction);
165     
166     publishAction = new PublishAction();
167     registerAction(publishAction);
168     
169     showAction = new ShowAction();
170     registerAction(showAction);
171     }
172     
173     private void registerAction(JLFAbstractAction action) {
174         action.addActionListener(this);
175         actions.addElement(action);
176     }
177     
178     // Creates the application menu bar.
179
private JMenuBar createMenu() {
180         JMenuBar menuBar = new JMenuBar();
181     
182         JMenuItem menuItem;
183     
184         // Build the File menu
185
JMenu fileMenu = new JMenu("File");
186         fileMenu.setMnemonic('F');
187     if (FileHandler.isEnabled()) {
188         menuItem = fileMenu.add(openAction);
189         menuItem.addMouseListener(mouseHandler);
190         menuItem = fileMenu.add(saveAction);
191         menuItem.addMouseListener(mouseHandler);
192         menuItem = fileMenu.add(saveAsAction);
193         menuItem.addMouseListener(mouseHandler);
194         menuItem = fileMenu.add(printAction);
195         menuItem.addMouseListener(mouseHandler);
196         fileMenu.add(new JSeparator());
197     }
198     menuItem = fileMenu.add(exitAction);
199     menuItem.addMouseListener(mouseHandler);
200     
201         // Build the edit menu
202
JMenu editMenu = new JMenu("Edit");
203         editMenu.setMnemonic('E');
204         menuItem = editMenu.add(cutAction);
205         menuItem.addMouseListener(mouseHandler);
206         menuItem = editMenu.add(copyAction);
207         menuItem.addMouseListener(mouseHandler);
208         menuItem = editMenu.add(pasteAction);
209         menuItem.addMouseListener(mouseHandler);
210     
211     // Build the help menu
212
JMenu helpMenu = new JMenu("Help");
213     helpMenu.setMnemonic('H');
214     menuItem = helpMenu.add(helpAction);
215         menuItem.addMouseListener(mouseHandler);
216         menuItem = helpMenu.add(aboutAction);
217         menuItem.addMouseListener(mouseHandler);
218     
219         menuBar.add(fileMenu);
220         menuBar.add(editMenu);
221     if (WebHandler.isEnabled()) {
222         JMenu webMenu = new JMenu("Web");
223         webMenu.setMnemonic('W');
224         menuItem = webMenu.add(publishAction);
225         menuItem.addMouseListener(mouseHandler);
226         menuItem = webMenu.add(showAction);
227         menuItem.addMouseListener(mouseHandler);
228         menuBar.add(webMenu);
229     }
230     menuBar.add(helpMenu);
231         
232         return menuBar;
233     }
234     
235     private JToolBar createToolBar() {
236         JToolBar toolbar = new JToolBar();
237         
238         JButton button;
239         
240         button = toolbar.add(cutAction);
241         button.addMouseListener(mouseHandler);
242         button = toolbar.add(copyAction);
243         button.addMouseListener(mouseHandler);
244         button = toolbar.add(pasteAction);
245         button.addMouseListener(mouseHandler);
246         toolbar.addSeparator();
247         button = toolbar.add(aboutAction);
248         button.addMouseListener(mouseHandler);
249     
250         return toolbar;
251     }
252     
253     private JPopupMenu createPopupMenu() {
254         JPopupMenu menu = new JPopupMenu();
255         
256         JMenuItem menuItem;
257         
258         menuItem = menu.add(cutAction);
259         menuItem.addMouseListener(mouseHandler);
260         menuItem = menu.add(copyAction);
261         menuItem.addMouseListener(mouseHandler);
262         menuItem = menu.add(pasteAction);
263         menuItem.addMouseListener(mouseHandler);
264         menu.addSeparator();
265         menuItem = menu.add(aboutAction);
266         menuItem.addMouseListener(mouseHandler);
267         
268         return menu;
269     }
270     
271     // Panel which allows for the enabling and disabling of all the actions.
272
private JPanel createPanel() {
273     textArea = new JTextArea();
274     JScrollPane scrollPane = new JScrollPane(textArea);
275         textArea.addMouseListener(new MouseAdapter() {
276             public void mousePressed(MouseEvent e) {
277             if(e.isPopupTrigger()) {
278                 popup.show(textArea, e.getX(), e.getY());
279             }
280             }
281             public void mouseReleased(MouseEvent e) {
282             if(e.isPopupTrigger()) {
283                 popup.show(textArea, e.getX(), e.getY());
284             }
285             }
286         });
287     
288         JPanel panel = new JPanel(new BorderLayout());
289         panel.setPreferredSize(new Dimension(450, 200));
290         panel.add(scrollPane, BorderLayout.CENTER);
291         
292         return panel;
293     }
294     
295     // Creates the status bar.
296
private JLabel createStatusBar() {
297         status = new JLabel("Ready...");
298         status.setBorder(BorderFactory.createEtchedBorder());
299     
300         return status;
301     }
302     
303     /*
304      * This method acts as the Action handler delegate for all the actions.
305      * The Cut, Copy and Paste Actions operate on the JTextArea.
306      */

307     public void actionPerformed(ActionEvent evt) {
308         String JavaDoc command = evt.getActionCommand();
309         
310         // Compare the action command to the known actions.
311
if (command.equals(aboutAction.getActionCommand())) {
312         // The about action was invoked
313
JOptionPane.showMessageDialog(this, aboutAction.getLongDescription(), aboutAction.getShortDescription(), JOptionPane.INFORMATION_MESSAGE);
314         } else if (command.equals(cutAction.getActionCommand())) {
315         ClipboardHandler.toClipboard(textArea.getSelectedText());
316         textArea.replaceSelection("");
317         } else if (command.equals(copyAction.getActionCommand())) {
318         ClipboardHandler.toClipboard(textArea.getSelectedText());
319         } else if (command.equals(pasteAction.getActionCommand())) {
320         String JavaDoc txt = ClipboardHandler.fromClipboard();
321         textArea.replaceSelection(txt);
322         } else if (command.equals(helpAction.getActionCommand())) {
323         HelpHandler.showHelp(evt);
324     } else if (command.equals(exitAction.getActionCommand())) {
325             saveScratch(textArea.getText());
326         System.exit(0);
327     } else if (command.equals(openAction.getActionCommand())) {
328         String JavaDoc t = FileHandler.open();
329         if (t != null) textArea.setText(t);
330     } else if (command.equals(saveAction.getActionCommand())) {
331         FileHandler.save(textArea.getText());
332     } else if (command.equals(saveAsAction.getActionCommand())) {
333         FileHandler.saveAs(textArea.getText());
334     } else if (command.equals(printAction.getActionCommand())) {
335         FileHandler.print(textArea);
336     } else if (command.equals(publishAction.getActionCommand())) {
337         WebHandler.publish(textArea.getText());
338     } else if (command.equals(showAction.getActionCommand())) {
339         WebHandler.show();
340     }
341     }
342
343
344 /*
345  * This method will check to see if there is anything stored in
346  * PersistenceStorage. If so, it will read it. If not, we will
347  * just create a new Persistence Storage. This is implemented
348  * mainly for the Webpad app to remember/recall what was
349  * displayed in the TextArea before the App was exited
350 */

351
352  private void initPersistence()
353  {
354
355      long maxSize = 8192;
356      long fileSize = 0;
357      boolean persExists = true;
358      URL url = null;
359      BufferedReader br = null;
360      String JavaDoc fName = "README";
361
362      try {
363       ps = (PersistenceService)ServiceManager.lookup("javax.jnlp.PersistenceService");
364       bs = (BasicService)ServiceManager.lookup("javax.jnlp.BasicService");
365        } catch (UnavailableServiceException e) {
366            ps = null;
367            bs = null;
368        }
369
370     if (ps != null && bs != null)
371     {
372     
373
374     /*
375     ** When the app is executed for the first time, there will be no
376     ** Persistence Storage existing, so an Exception will be thrown.
377     **/

378
379
380        try
381        {
382
383        URL codebase = bs.getCodeBase();
384
385        url = new URL(codebase.toString() + "perstest");
386        
387        fc = ps.get(url);
388        maxSize = fc.getMaxLength();
389        fileSize = fc.getLength();
390        } catch (IOException ioe) {
391
392      /*
393      ** There will no persistence storage when the app is executed for
394      ** for the first time on the client machine.
395      */

396            persExists = false;
397        }
398      
399      /* If there is no persistence storage, open the default README file.
400      ** If persistence exists, but there was nothing in the scratch pad
401      ** still open the default README file. Deliberately checking for
402      ** length > 1, because in some cases it is writing one byte to the
403      ** file even though it is a null character. Maybe due to some bug.
404      ** If we had some valid contents in scratch pad, then retrieve
405      ** it from Persistence storage and display it.
406      */

407        try {
408          if (persExists = true && fileSize > 1)
409          {
410           br = new BufferedReader(new InputStreamReader(fc.getInputStream()));
411          }
412          else
413          {
414        URL fNameURL = cl.getResource(fName);
415        if (fNameURL != null) {
416                br = new BufferedReader(new InputStreamReader(fNameURL.openStream()));
417                fileSize = 4096;
418        }
419          }
420          
421           StringBuffer JavaDoc sb = new StringBuffer JavaDoc((int)fileSize);
422       if (br != null) {
423           String JavaDoc line = br.readLine();
424           while(line != null) {
425           sb.append(line);
426           sb.append("\n");
427           line = br.readLine();
428           }
429           
430           textArea.setText(sb.toString());
431           br.close();
432       }
433          } catch (IOException ioe) {
434          ioe.printStackTrace();
435      }
436
437      try {
438      
439           ps.delete(url);
440
441      } catch (IOException ioe) {
442        
443         /*
444         ** This exception will be raised when the app is executed
445         ** for the first time in ps.delete.
446         */

447         }
448        
449         try
450         {
451         ps.create(url, maxSize);
452         fc = ps.get(url);
453         } catch (IOException ioe) {
454                 ioe.printStackTrace();
455         }
456     }
457  }
458
459
460   /*
461   ** This method will be called upon exit to store whatever is in the
462  ** scratch pad into the Persistence Storage. Whenever the app is started
463  ** next time, the same content will be displayed again.
464  **/

465
466   private void saveScratch(String JavaDoc txt)
467   {
468
469       try
470       {
471         int sizeNeeded = txt.length() * 2;
472     if (sizeNeeded > fc.getMaxLength()) fc.setMaxLength(sizeNeeded);
473     BufferedWriter os = new BufferedWriter(new OutputStreamWriter(fc.getOutputStream(false)));
474     os.write(txt);
475     os.close();
476       } catch(Exception JavaDoc e) {
477          e.printStackTrace();
478       }
479
480   }
481     
482     /**
483      * This adapter is constructed to handle mouse over component events.
484      */

485     private class MouseHandler extends MouseAdapter {
486     
487     private JLabel label;
488     private String JavaDoc oldMsg;
489     
490     /**
491      * ctor for the adapter.
492      * @param label the JLabel which will recieve value of the
493      * Action.LONG_DESCRIPTION key.
494      */

495     public MouseHandler(JLabel label) {
496         setLabel(label);
497         oldMsg = label.getText();
498     }
499     
500     public void setLabel(JLabel label) {
501         this.label = label;
502     }
503     
504     public void mouseEntered(MouseEvent evt) {
505         if (evt.getSource() instanceof AbstractButton) {
506         AbstractButton button = (AbstractButton)evt.getSource();
507         Action action = button.getAction(); // getAction is new in JDK 1.3
508
if (action != null) {
509             oldMsg = label.getText();
510             String JavaDoc message = (String JavaDoc)action.getValue(Action.LONG_DESCRIPTION);
511             label.setText(message);
512         }
513         }
514     }
515     
516     public void mouseExited(MouseEvent evt) {
517         label.setText(oldMsg);
518     }
519     }
520     
521     /**
522      * Main method
523      */

524     public static void main(String JavaDoc[] args) {
525     WebPad demo = new WebPad();
526     demo.pack();
527     demo.setVisible(true);
528     }
529 }
530
531
532
Popular Tags