KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > edu > rice > cs > drjava > ui > JarOptionsDialog


1 /*BEGIN_COPYRIGHT_BLOCK
2  *
3  * This file is part of DrJava. Download the current version of this project from http://www.drjava.org/
4  * or http://sourceforge.net/projects/drjava/
5  *
6  * DrJava Open Source License
7  *
8  * Copyright (C) 2001-2005 JavaPLT group at Rice University (javaplt@rice.edu). All rights reserved.
9  *
10  * Developed by: Java Programming Languages Team, Rice University, http://www.cs.rice.edu/~javaplt/
11  *
12  * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
13  * documentation files (the "Software"), to deal with the Software without restriction, including without limitation
14  * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
15  * to permit persons to whom the Software is furnished to do so, subject to the following conditions:
16  *
17  * - Redistributions of source code must retain the above copyright notice, this list of conditions and the
18  * following disclaimers.
19  * - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
20  * following disclaimers in the documentation and/or other materials provided with the distribution.
21  * - Neither the names of DrJava, the JavaPLT, Rice University, nor the names of its contributors may be used to
22  * endorse or promote products derived from this Software without specific prior written permission.
23  * - Products derived from this software may not be called "DrJava" nor use the term "DrJava" as part of their
24  * names without prior written permission from the JavaPLT group. For permission, write to javaplt@rice.edu.
25  *
26  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
27  * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
28  * CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
29  * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
30  * WITH THE SOFTWARE.
31  *
32  *END_COPYRIGHT_BLOCK*/

33
34 package edu.rice.cs.drjava.ui;
35
36 import edu.rice.cs.drjava.model.OpenDefinitionsDocument;
37 import edu.rice.cs.drjava.model.GlobalModel;
38 import edu.rice.cs.drjava.model.definitions.InvalidPackageException;
39 import edu.rice.cs.util.UnexpectedException;
40 import edu.rice.cs.util.jar.JarBuilder;
41 import edu.rice.cs.util.jar.ManifestWriter;
42 import edu.rice.cs.util.swing.FileChooser;
43 import edu.rice.cs.util.swing.FileSelectorStringComponent;
44 import edu.rice.cs.util.swing.FileSelectorComponent;
45 import edu.rice.cs.util.swing.SwingWorker;
46 import edu.rice.cs.util.swing.Utilities;
47 import edu.rice.cs.util.newjvm.ExecJVM;
48 import edu.rice.cs.util.StreamRedirectThread;
49
50 import javax.swing.*;
51 import javax.swing.border.EmptyBorder JavaDoc;
52 import javax.swing.event.DocumentEvent JavaDoc;
53 import javax.swing.event.DocumentListener JavaDoc;
54 import javax.swing.filechooser.FileFilter JavaDoc;
55 import java.awt.*;
56 import java.awt.event.ActionEvent JavaDoc;
57 import java.io.File JavaDoc;
58 import java.io.IOException JavaDoc;
59 import java.util.Iterator JavaDoc;
60 import java.util.List JavaDoc;
61 import java.util.StringTokenizer JavaDoc;
62 import java.util.NoSuchElementException JavaDoc;
63
64 public class JarOptionsDialog extends JFrame {
65   /** Class to save the frame state, i.e. location. */
66   public static class FrameState {
67     private Point _loc;
68     public FrameState(Point l) {
69       _loc = l;
70     }
71     public FrameState(String JavaDoc s) {
72       StringTokenizer JavaDoc tok = new StringTokenizer JavaDoc(s);
73       try {
74         int x = Integer.valueOf(tok.nextToken());
75         int y = Integer.valueOf(tok.nextToken());
76         _loc = new Point(x, y);
77       }
78       catch(NoSuchElementException JavaDoc nsee) {
79         throw new IllegalArgumentException JavaDoc("Wrong FrameState string: " + nsee);
80       }
81       catch(NumberFormatException JavaDoc nfe) {
82         throw new IllegalArgumentException JavaDoc("Wrong FrameState string: " + nfe);
83       }
84     }
85     public FrameState(JarOptionsDialog comp) {
86       _loc = comp.getLocation();
87     }
88     public String JavaDoc toString() {
89       final StringBuilder JavaDoc sb = new StringBuilder JavaDoc();
90       sb.append(_loc.x);
91       sb.append(' ');
92       sb.append(_loc.y);
93       return sb.toString();
94     }
95     public Point getLocation() { return _loc; }
96   }
97   
98   /** Bitflags for default selection. */
99   public static final int JAR_CLASSES = 1;
100   public static final int JAR_SOURCES = 2;
101   public static final int MAKE_EXECUTABLE = 4;
102   
103   /** Determines whether class files should be jar-ed. */
104   private JCheckBox _jarClasses;
105   /** Determines whether source files should be jar-ed. */
106   private JCheckBox _jarSources;
107   /** Determines whether the jar file should be made executable. */
108   private JCheckBox _makeExecutable;
109   /** File selector for the jar output file. */
110   private FileSelectorComponent _jarFileSelector;
111   /** Text field for the main class. */
112   private FileSelectorStringComponent _mainClassField;
113   /** Label for main class. */
114   private JLabel _mainClassLabel;
115   /** OK button. */
116   private JButton _okButton;
117   /** Cancel button. */
118   private JButton _cancelButton;
119   /** Main frame. */
120   private MainFrame _mainFrame;
121   /** Model. */
122   private GlobalModel _model;
123   /** Label explaining why classes can't be jar-ed. */
124   private JLabel _cantJarClassesLabel;
125   /** Root of the chooser. */
126   private File JavaDoc _rootFile;
127   /** Processing dialog. */
128   private ProcessingFrame _processingFrame;
129   /** Last frame state. It can be stored and restored. */
130   private FrameState _lastState = null;
131
132   
133   /** Returns the last state of the frame, i.e. the location and dimension.
134    * @return frame state
135    */

136   public FrameState getFrameState() { return _lastState; }
137   
138   /** Sets state of the frame, i.e. the location and dimension of the frame for the next use.
139    * @param ds State to update to, or {@code null} to reset
140    */

141   public void setFrameState(FrameState ds) {
142     _lastState = ds;
143     if (_lastState!=null) {
144       setLocation(_lastState.getLocation());
145       validate();
146     }
147   }
148   
149   /** Sets state of the frame, i.e. the location and dimension of the frame for the next use.
150    * @param s State to update to, or {@code null} to reset
151    */

152   public void setFrameState(String JavaDoc s) {
153     try { _lastState = new FrameState(s); }
154     catch(IllegalArgumentException JavaDoc e) { _lastState = null; }
155     if (_lastState!=null) setLocation(_lastState.getLocation());
156     else MainFrame.setPopupLoc(this, _mainFrame);
157     validate();
158   }
159   
160   /** Frame that gets displayed when the program is processing data. */
161   private static class ProcessingFrame extends JFrame {
162     private Component _parent;
163     public ProcessingFrame(Component parent, String JavaDoc title, String JavaDoc label) {
164       super(title);
165       _parent = parent;
166       setSize(350, 150);
167       MainFrame.setPopupLoc(this, parent);
168       JLabel waitLabel = new JLabel(label, SwingConstants.CENTER);
169       getRootPane().setLayout(new BorderLayout());
170       getRootPane().add(waitLabel, BorderLayout.CENTER);
171     }
172     public void setVisible(boolean vis) {
173       MainFrame.setPopupLoc(this, _parent);
174       super.setVisible(vis);
175     }
176   }
177
178   /** Create a configuration diaglog
179    * @param mf the instance of mainframe to query into the project
180    */

181   public JarOptionsDialog(MainFrame mf) {
182     super("Create Jar File from Project");
183     _mainFrame = mf;
184     _model = mf.getModel();
185     initComponents();
186   }
187
188   /** Load the initial state from the previous files or with defaults. */
189   private void _loadSettings() {
190     int f = _model.getCreateJarFlags();
191     _jarClasses.setSelected(((f & JAR_CLASSES) != 0));
192     _jarSources.setSelected(((f & JAR_SOURCES) != 0));
193     _makeExecutable.setSelected(((f & MAKE_EXECUTABLE) != 0));
194     
195     boolean outOfSync = true;
196     if (_model.getBuildDirectory() != null) {
197       outOfSync = _model.hasOutOfSyncDocuments();
198     }
199     if ((_model.getBuildDirectory() == null) || (outOfSync)) {
200       _jarClasses.setSelected(false);
201       _jarClasses.setEnabled(false);
202       String JavaDoc s;
203       if ((_model.getBuildDirectory() == null) && (outOfSync)) {
204         s = "<html><center>A build directory must be specified in order to jar class files,<br>and the project needs to be compiled.</center></html>";
205       }
206       else
207       if (_model.getBuildDirectory() == null) {
208         s = "<html>A build directory must be specified in order to jar class files.</html>";
209       }
210       else {
211         s = "<html>The project needs to be compiled.</html>";
212       }
213       _cantJarClassesLabel.setText(s);
214     }
215     else {
216       _jarClasses.setEnabled(true);
217       _cantJarClassesLabel.setText(" ");
218
219       // Main class
220
_rootFile = _model.getBuildDirectory();
221       try {
222         _rootFile = _rootFile.getCanonicalFile();
223       } catch(IOException JavaDoc e) { }
224       
225       final File JavaDoc mc = _model.getMainClass();
226       if (mc == null) _mainClassField.setText("");
227       else {
228         try {
229           OpenDefinitionsDocument mcDoc = _model.getDocumentForFile(mc);
230           _mainClassField.setText(mcDoc.getQualifiedClassName());
231         }
232         catch(IOException JavaDoc ioe) { _mainClassField.setText(""); }
233         catch(edu.rice.cs.drjava.model.definitions.ClassNameNotFoundException e) { _mainClassField.setText(""); }
234       }
235     }
236     
237     _jarFileSelector.setFileField(_model.getCreateJarFile());
238     
239     _okButton.setEnabled(_jarSources.isSelected() || _jarClasses.isSelected());
240     _setEnableExecutable(_jarClasses.isSelected());
241   }
242
243   /** Build the dialog. */
244   private void initComponents() {
245     JPanel main = _makePanel();
246     super.getContentPane().setLayout(new BorderLayout());
247     super.getContentPane().add(main, BorderLayout.NORTH);
248
249     Action okAction = new AbstractAction("OK") {
250       public void actionPerformed(ActionEvent JavaDoc e) {
251         _ok();
252       }
253     };
254     _okButton = new JButton(okAction);
255
256     Action cancelAction = new AbstractAction("Cancel") {
257       public void actionPerformed(ActionEvent JavaDoc e) {
258         _cancel();
259       }
260     };
261     _cancelButton = new JButton(cancelAction);
262
263     // Add buttons
264
JPanel bottom = new JPanel();
265     bottom.setBorder(new EmptyBorder JavaDoc(5, 5, 5, 5));
266     bottom.setLayout(new BoxLayout(bottom, BoxLayout.X_AXIS));
267     bottom.add(Box.createHorizontalGlue());
268     bottom.add(_okButton);
269     bottom.add(_cancelButton);
270     bottom.add(Box.createHorizontalGlue());
271
272     super.getContentPane().add(bottom, BorderLayout.SOUTH);
273     super.setResizable(false);
274     pack();
275     
276     MainFrame.setPopupLoc(this, _mainFrame);
277   }
278
279   /** Make the options panel.
280    * @return The panel with the options for jarring a project
281    */

282   private JPanel _makePanel() {
283     JPanel panel = new JPanel();
284     GridBagLayout gridbag = new GridBagLayout();
285     GridBagConstraints c = new GridBagConstraints();
286     panel.setLayout(gridbag);
287     c.fill = GridBagConstraints.HORIZONTAL;
288     Insets labelInsets = new Insets(5, 10, 0, 10);
289     c.weightx = 0.0;
290     c.gridwidth = 1;
291     c.insets = labelInsets;
292
293     // Jar class files
294
c.weightx = 1.0;
295     c.gridwidth = GridBagConstraints.REMAINDER;
296     c.insets = labelInsets;
297     c.fill = GridBagConstraints.HORIZONTAL;
298
299     JPanel jarClassesPanel = _makeClassesPanel();
300     gridbag.setConstraints(jarClassesPanel, c);
301     panel.add(jarClassesPanel);
302
303     _cantJarClassesLabel = new JLabel("<html><center>A build directory must be specified in order to jar class files,<br>and the project needs to be compiled.</center></html>", SwingConstants.CENTER);
304     c.gridx = 0;
305     c.anchor = GridBagConstraints.WEST;
306     c.fill = GridBagConstraints.HORIZONTAL;
307     gridbag.setConstraints(jarClassesPanel, c);
308     panel.add(_cantJarClassesLabel);
309     
310     // Jar Sources
311
_jarSources = new JCheckBox(new AbstractAction("Jar source files") {
312       public void actionPerformed(ActionEvent JavaDoc e) {
313         _okButton.setEnabled(_jarSources.isSelected() || _jarClasses.isSelected());
314       }
315     });
316
317     c.weightx = 0.0;
318     c.gridwidth = 1;
319     c.insets = labelInsets;
320
321     gridbag.setConstraints(_jarSources, c);
322     panel.add(_jarSources);
323
324     // Output file
325
c.gridx = 0;
326     c.gridwidth = 1;
327     c.insets = labelInsets;
328     JLabel label = new JLabel("Jar File");
329     label.setToolTipText("The file that the jar should be written to.");
330     gridbag.setConstraints(label, c);
331     panel.add(label);
332
333     c.weightx = 1.0;
334     c.gridx = 0;
335     c.gridwidth = GridBagConstraints.REMAINDER;
336     c.insets = labelInsets;
337
338     JPanel jarFilePanel = _makeJarFileSelector();
339     gridbag.setConstraints(jarFilePanel, c);
340     panel.add(jarFilePanel);
341
342     return panel;
343   }
344
345   /** Make the panel that is enabled when you are going to jar class files
346    * @return the panel containing the sub-options to the jarring classes option
347    */

348   private JPanel _makeClassesPanel() {
349     JPanel panel = new JPanel();
350     GridBagConstraints gridBagConstraints;
351     panel.setLayout(new GridBagLayout());
352     
353     _jarClasses = new JCheckBox(new AbstractAction("Jar classes") {
354       public void actionPerformed(ActionEvent JavaDoc e) {
355         _toggleClassOptions();
356         _okButton.setEnabled(_jarSources.isSelected() || _jarClasses.isSelected());
357       }
358     });
359     gridBagConstraints = new GridBagConstraints();
360     gridBagConstraints.gridx = 0;
361     gridBagConstraints.weightx = 1.0;
362     gridBagConstraints.anchor = GridBagConstraints.WEST;
363     panel.add(_jarClasses, gridBagConstraints);
364
365     JPanel addclasses = new JPanel();
366     addclasses.setLayout(new GridBagLayout());
367     _makeExecutable = new JCheckBox(new AbstractAction("Make executable") {
368       public void actionPerformed(ActionEvent JavaDoc e) {
369         _toggleMainClass();
370       }
371     });
372     gridBagConstraints = new GridBagConstraints();
373     gridBagConstraints.anchor = GridBagConstraints.WEST;
374     addclasses.add(_makeExecutable, gridBagConstraints);
375     
376     gridBagConstraints = new GridBagConstraints();
377     gridBagConstraints.gridx = 0;
378     gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
379     gridBagConstraints.insets = new Insets(0, 20, 0, 0);
380     addclasses.add(_makeMainClassSelectorPanel(), gridBagConstraints);
381
382     gridBagConstraints = new GridBagConstraints();
383     gridBagConstraints.gridx = 0;
384     gridBagConstraints.anchor = GridBagConstraints.WEST;
385     gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
386     gridBagConstraints.insets = new Insets(0, 25, 0, 0);
387     panel.add(addclasses, gridBagConstraints);
388
389     return panel;
390   }
391  
392   /** Make the panel that lets you select the jar's main class.
393    * @return the panel containing the label and the selector for the main class.
394    */

395   private JPanel _makeMainClassSelectorPanel() {
396     
397     FileChooser chooser = new FileChooser(_rootFile);
398     chooser.setDialogTitle("Select Main Class");
399 // chooser.setTopMessage("Select the main class for the executable jar file:");
400
chooser.setApproveButtonText("Select");
401     FileFilter JavaDoc filter = new FileFilter JavaDoc() {
402       public boolean accept(File JavaDoc f) {
403         String JavaDoc name = f.getName();
404         return !f.isDirectory() && name.endsWith(".class");
405       }
406       public String JavaDoc getDescription() { return "Class Files (*.class)"; }
407     };
408     chooser.addChoosableFileFilter(filter);
409     
410     _mainClassField = new FileSelectorStringComponent(this, chooser, 20, 12f) {
411       public File JavaDoc convertStringToFile(String JavaDoc s) {
412         s = s.trim().replace('.', java.io.File.separatorChar) + ".class";
413         if (s.equals("")) return null;
414         else return new File JavaDoc(_rootFile, s);
415       }
416       
417       public String JavaDoc convertFileToString(File JavaDoc f) {
418         if (f == null) return "";
419         else {
420           try {
421             String JavaDoc s = edu.rice.cs.util.FileOps.makeRelativeTo(f, _rootFile).toString();
422             s = s.substring(0, s.lastIndexOf(".class"));
423             s = s.replace(java.io.File.separatorChar, '.').replace('$', '.');
424             int pos = 0;
425             boolean ok = true;
426             while((pos = s.indexOf('.', pos)) >= 0) {
427               if ((s.length() <= pos + 1) || (Character.isDigit(s.charAt(pos + 1)))) {
428                 ok = false;
429                 break;
430               }
431               ++pos;
432             }
433             if (ok) return s;
434             return "";
435           }
436           catch(Exception JavaDoc e) { return ""; }
437         }
438       }
439     };
440     _mainClassField.getTextField().getDocument().addDocumentListener(new DocumentListener JavaDoc() {
441       public void insertUpdate(DocumentEvent JavaDoc e) { setEnabled(); }
442       public void removeUpdate(DocumentEvent JavaDoc e) { setEnabled(); }
443       public void changedUpdate(DocumentEvent JavaDoc e) { setEnabled(); }
444       private void setEnabled() { Utilities.invokeLater(new Runnable JavaDoc() { public void run() { _okButton.setEnabled(true); } }); }
445     });
446     JPanel p = new JPanel();
447     p.setLayout(new BorderLayout());
448     _mainClassLabel = new JLabel("Main class: ");
449     _mainClassLabel.setLabelFor(_mainClassField);
450     p.add(_mainClassLabel, BorderLayout.WEST);
451     p.add(_mainClassField, BorderLayout.CENTER);
452     return p;
453   }
454
455
456   /** Create a file selector to select the output jar file
457    * @return The JPanel that contains the selector
458    */

459   private JPanel _makeJarFileSelector() {
460     JFileChooser fileChooser = new JFileChooser(_model.getBuildDirectory());
461     fileChooser.setDialogTitle("Select Jar Output File");
462     fileChooser.setApproveButtonText("Select");
463     fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
464     fileChooser.setMultiSelectionEnabled(false);
465     fileChooser.setDialogType(JFileChooser.SAVE_DIALOG);
466
467     _jarFileSelector = new FileSelectorComponent(this, fileChooser, 20, 12f, false);
468     _jarFileSelector.setFileFilter(new FileFilter JavaDoc() {
469       public boolean accept(File JavaDoc f) { return f.getName().endsWith(".jar") || f.isDirectory(); }
470       public String JavaDoc getDescription() { return "Java Archive Files (*.jar)"; }
471     });
472
473     return _jarFileSelector;
474   }
475
476   /** Modifies state for when the executable check box is selected */
477   private void _setEnableExecutable(boolean b) {
478     _makeExecutable.setEnabled(b);
479     _toggleMainClass();
480   }
481  
482   /** Method to run when the jar class file is selected */
483   private void _toggleClassOptions() {
484     _setEnableExecutable(_jarClasses.isSelected());
485   }
486
487   /** Method to call when the 'Make Executable' check box is clicked. */
488   private void _toggleMainClass() {
489     _mainClassField.setEnabled(_makeExecutable.isSelected() && _jarClasses.isSelected());
490     _mainClassLabel.setEnabled(_makeExecutable.isSelected() && _jarClasses.isSelected());
491   }
492
493   /** Method that handels the Cancel button */
494   private void _cancel() {
495     _lastState = new FrameState(this);
496     this.setVisible(false);
497   }
498
499   /** Do the Jar. */
500   private void _ok() {
501     // Always apply and save settings
502
_saveSettings();
503
504     File JavaDoc jarOut = _jarFileSelector.getFileFromField();
505     if (jarOut == null) {
506       JOptionPane.showMessageDialog(JarOptionsDialog.this,
507                                     "You must specify an output file",
508                                     "Error: No File Specified",
509                                     JOptionPane.ERROR_MESSAGE);
510       return;
511     }
512     else if (jarOut.exists()) {
513       if (JOptionPane.showConfirmDialog(JarOptionsDialog.this,
514                                         "Are you sure you want to overwrite the file '" + jarOut.getPath() + "'?",
515                                         "Overwrite file?",
516                                         JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) {
517         // I want to focus back to the dialog
518
return;
519       }
520     }
521
522     setEnabled(false);
523     _processingFrame = new ProcessingFrame(this, "Creating Jar File", "Processing, please wait.");
524     _processingFrame.setVisible(true);
525     SwingWorker worker = new SwingWorker() {
526       boolean _success = false;
527
528       /**
529        * Takes input of a file which is a directory and compresses all the class files in it
530        * into a jar file
531        *
532        * @param dir the File object representing the directory
533        * @param jarFile the JarBuilder that the data should be written to
534        * @return true on success, false on failure
535        */

536       private boolean jarBuildDirectory(File JavaDoc dir, JarBuilder jarFile) throws IOException JavaDoc {
537         java.io.FileFilter JavaDoc classFilter = new java.io.FileFilter JavaDoc() {
538           public boolean accept(File JavaDoc f) {
539             return f.isDirectory() || f.getName().endsWith(".class");
540           }
541         };
542
543         File JavaDoc[] files = dir.listFiles(classFilter);
544         if (files!=null) { // listFiles may return null if there's an IO error
545
for (int i = 0; i < files.length; i++) {
546             if (files[i].isDirectory()) {
547               jarFile.addDirectoryRecursive(files[i], files[i].getName(), classFilter);
548             }
549             else {
550               jarFile.addFile(files[i], "", files[i].getName());
551             }
552           }
553         }
554
555         return true;
556       }
557
558       /**
559        * Takes the model and the jar and writes all the sources to the jar
560        *
561        * @param model the GlobalModel that the files are to come out of
562        * @param jar the JarBuilder that the data should be written to
563        * @return true on success, false on failure
564        */

565       private boolean jarSources(GlobalModel model, JarBuilder jar) {
566         List JavaDoc<OpenDefinitionsDocument> srcs = model.getProjectDocuments();
567
568         Iterator JavaDoc<OpenDefinitionsDocument> iter = srcs.iterator();
569         while (iter.hasNext()) {
570           OpenDefinitionsDocument doc = iter.next();
571           if (doc.inProject() && ! doc.isAuxiliaryFile()) {
572             try {
573               // Since the file compiled without any errors, this shouldn't have any problems
574
jar.addFile(doc.getFile(), packageNameToPath(doc.getPackageName()), doc.getFileName());
575             }
576             catch (IOException JavaDoc e) {
577               e.printStackTrace();
578               throw new UnexpectedException(e);
579             }
580           }
581         }
582         return true;
583       }
584
585       /** Helper function to convert a package name to its path form
586        * @param packageName the name of the package
587        * @return the String which is should be the directory that it should be contained within
588        */

589       private String JavaDoc packageNameToPath(String JavaDoc packageName) {
590         return packageName.replaceAll("\\.", System.getProperty("file.separator").replaceAll("\\\\", "\\\\\\\\"));
591       }
592       /** The method to perform the work
593        * @return null
594        */

595       public Object JavaDoc construct() {
596         try {
597           File JavaDoc jarOut = _jarFileSelector.getFileFromField();
598           if (!jarOut.exists()) {
599             jarOut.createNewFile();
600           }
601           
602           if (_jarClasses.isSelected() && _jarSources.isSelected()) {
603             JarBuilder mainJar = null;
604             if (_makeExecutable.isSelected()) {
605               ManifestWriter mw = new ManifestWriter();
606               mw.setMainClass(_mainClassField.getText());
607               mainJar = new JarBuilder(jarOut, mw.getManifest());
608             }
609             else {
610               mainJar = new JarBuilder(jarOut);
611             }
612             
613             jarBuildDirectory(_model.getBuildDirectory(), mainJar);
614             
615             File JavaDoc sourceJarFile = File.createTempFile(_model.getBuildDirectory().getName(), ".jar");
616             JarBuilder sourceJar = new JarBuilder(sourceJarFile);
617             jarSources(_model, sourceJar);
618             sourceJar.close();
619             mainJar.addFile(sourceJarFile, "", "source.jar");
620             
621             mainJar.close();
622             sourceJarFile.delete();
623           }
624           else if (_jarClasses.isSelected()) {
625             JarBuilder jb;
626             if (_makeExecutable.isSelected()) {
627               ManifestWriter mw = new ManifestWriter();
628               mw.setMainClass(_mainClassField.getText());
629               jb = new JarBuilder(jarOut, mw.getManifest());
630             }
631             else {
632               jb = new JarBuilder(jarOut);
633             }
634             jarBuildDirectory(_model.getBuildDirectory(), jb);
635             jb.close();
636           }
637           else {
638             JarBuilder jb = new JarBuilder(jarOut);
639             jarSources(_model, jb);
640             jb.close();
641           }
642           _success = true;
643         }
644         catch (Exception JavaDoc e) {
645           e.printStackTrace();
646         }
647         return null;
648       }
649       public void finished() {
650         _processingFrame.setVisible(false);
651         _processingFrame.dispose();
652         JarOptionsDialog.this.setEnabled(true);
653         if (_success) {
654           if (_makeExecutable.isSelected()) {
655              Object JavaDoc[] options = { "OK", "Run" };
656              int res = JOptionPane.showOptionDialog(JarOptionsDialog.this, "Jar file successfully written to '"+_jarFileSelector.getFileFromField().getName()+"'",
657                                                     "Jar Creation Successful", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE,
658                                                     null, options, options[0]);
659              JarOptionsDialog.this.setVisible(false);
660              if (1==res) {
661                SwingWorker jarRunner = new SwingWorker() {
662                  public Object JavaDoc construct() {
663                    try {
664                      Process JavaDoc jarFileProcess = ExecJVM.runJVM(_mainClassField.getText(), // mainClass
665
new String JavaDoc[] {}, // classParams,
666
new String JavaDoc[] { _jarFileSelector.getFileFromField().getAbsolutePath() }, // classPath,
667
new String JavaDoc[] {}, // jvmParams,
668
_jarFileSelector.getFileFromField().getParentFile());
669                                                              
670                      StreamRedirectThread errThread = new StreamRedirectThread("error reader", jarFileProcess.getErrorStream(), System.err);
671                      StreamRedirectThread outThread = new StreamRedirectThread("output reader", jarFileProcess.getInputStream(), System.out);
672                      errThread.start();
673                      outThread.start();
674                      boolean notDead = true;
675                      while(notDead) {
676                        try {
677                          errThread.join();
678                          outThread.join();
679                          notDead = false;
680                        }
681                        catch (InterruptedException JavaDoc exc) {
682                          // ignore, we don't interrupt
683
}
684                      }
685                      jarFileProcess.waitFor();
686                      JOptionPane.showMessageDialog(JarOptionsDialog.this,"Execution of jar file terminated (exit value = "+
687                                                    jarFileProcess.exitValue()+")", "Execution terminated.",
688                                                    JOptionPane.INFORMATION_MESSAGE);
689                    }
690                    catch(Exception JavaDoc e) {
691                      JOptionPane.showMessageDialog(JarOptionsDialog.this, "An error occured while running the jar file: \n"+e, "Error", JOptionPane.ERROR_MESSAGE);
692                    }
693                    finally {
694                      JarOptionsDialog.this.setVisible(false);
695                    }
696                    return null;
697                  }
698                };
699                jarRunner.start();
700              }
701           }
702           else {
703             JOptionPane.showMessageDialog(JarOptionsDialog.this, "Jar file successfully written to '" + _jarFileSelector.getFileFromField().getName() + "'", "Jar Creation Successful", JOptionPane.INFORMATION_MESSAGE);
704             JarOptionsDialog.this.setVisible(false);
705           }
706         }
707         else {
708           JOptionPane.showMessageDialog(JarOptionsDialog.this, "An error occured while creating the jar file. This could be because the file that you are writing to or the file you are reading from could not be opened.", "Error: File Access", JOptionPane.ERROR_MESSAGE);
709           JarOptionsDialog.this.setVisible(false);
710         }
711       }
712     };
713     worker.start();
714   }
715
716   /** Save the settings for this dialog. */
717   private boolean _saveSettings() {
718     _lastState = new FrameState(this);
719     if ((_model.getCreateJarFile() == null) ||
720         (!_model.getCreateJarFile().getName().equals(_jarFileSelector.getFileFromField().getName()))) {
721       _model.setCreateJarFile(_jarFileSelector.getFileFromField());
722     }
723     int f = 0;
724     if (_jarClasses.isSelected()) f |= JAR_CLASSES;
725     if (_jarSources.isSelected()) f |= JAR_SOURCES;
726     if (_makeExecutable.isSelected()) f |= MAKE_EXECUTABLE;
727     if (f!=_model.getCreateJarFlags()) {
728       _model.setCreateJarFlags(f);
729     }
730     return true;
731   }
732
733   /** Toggle visibility of this frame. Warning, it behaves like a modal dialog. */
734   public void setVisible(boolean vis) {
735     assert EventQueue.isDispatchThread();
736     validate();
737     if (vis) {
738       _mainFrame.hourglassOn();
739       ProcessingFrame pf = new ProcessingFrame(this, "Checking class files", "Processing, please wait.");
740       pf.setVisible(true);
741       _loadSettings();
742       pf.setVisible(false);
743       pf.dispose();
744     }
745     else {
746       _mainFrame.hourglassOff();
747       _mainFrame.toFront();
748     }
749     super.setVisible(vis);
750   }
751 }
752
Popular Tags