xref: /titanic_44/usr/src/cmd/krb5/kadmin/gui/dataclasses/PrintUtil.java (revision 6bbe05905a1c10a2703f95fb4912eb14b87f6670)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * ident	"%Z%%M%	%I%	%E% SMI"
24  *
25  * Copyright (c) 1999-2000 by Sun Microsystems, Inc.
26  * All rights reserved.
27  */
28 import java.awt.*;
29 import java.awt.event.*;
30 import java.io.*;
31 import java.util.ResourceBundle;
32 import java.util.MissingResourceException;
33 
34 public class PrintUtil {
35 
36     // For I18N
37     private static ResourceBundle rb =
38     ResourceBundle.getBundle("GuiResource" /* NOI18N */);
39     private static ResourceBundle hrb =
40     ResourceBundle.getBundle("HelpData" /* NOI18N */);
41     /**
42      * Prints an object to either file or printer. Uses the toString()
43      * method of the object to obtain a string representation for it.
44      * @param obj the Object that is to be printed
45      */
46     public static void dump(Frame parent, Object obj) {
47 
48         boolean usePrinter;
49         String stringRep = obj.toString();
50 
51         Frame printFrame = new PrintFrame(parent, stringRep);
52         printFrame.setVisible(true);
53     }
54 
55     /**
56      * Call rb.getString(), but catch exception and return English
57      * key so that small spelling errors don't cripple the GUI
58      *
59      */
60     private static final String getString(String key) {
61         return (getString(rb, key));
62     }
63 
64     private static final String getString(ResourceBundle rb, String key) {
65         try {
66     	    String res = rb.getString(key);
67 	    return res;
68         } catch (MissingResourceException e) {
69 	    System.out.println("Missing resource "+key+", using English.");
70 	    return key;
71         }
72     }
73 
74     /**
75      * Forgets the command and filename that was last entered.
76      */
77     public static final void reinitialize() {
78         PrintFrame.command = PrintFrame.fileName = null;
79     }
80 
81     /*
82      ************************************************************
83      *   I N N E R    C L A S S E S   F O L L O W
84      ************************************************************
85      */
86 
87     /**
88      * This class will show a Frame to determine whether the user wants
89      * to print to  a file and which file, if so, or to the printer
90      * directly. Finally it will print to the appropriate destinaition.
91      */
92     private static class PrintFrame extends Frame {
93 
94         private String text;
95 
96         static TextField command = null;
97         static TextField fileName = null;
98 
99         private CheckboxGroup options;
100         private Checkbox printer;
101         private Checkbox file;
102 
103         private Frame parent;
104 
105         private static String defaultFileName =
106             "/tmp/.SEAM_temp.txt" /* NO18N */;
107 
108         /**
109          * Constructor for PrintFrame.
110          */
111         public PrintFrame(Frame parent, String text) {
112             super(rb.getString("SEAM Print Helper"));
113             this.text = text;
114             this.parent = parent;
115             setLayout(new GridBagLayout());
116 
117             addLabelsAndFields();
118             addCheckboxGroup();
119             addButtons();
120 
121             setBackground(parent.getBackground());
122             setForeground(parent.getForeground());
123             setSize(340, 160);
124             setResizable(false);
125 
126             printer.setState(true);
127             command.setEditable(true);
128             fileName.setEditable(false);
129         }
130 
131         private void addLabelsAndFields() {
132             GridBagConstraints gbc = new GridBagConstraints();
133             gbc.weightx = gbc.weighty = 1;
134             gbc.gridwidth = 2;
135             gbc.fill = GridBagConstraints.HORIZONTAL;
136 
137             gbc.gridx = 1;
138             gbc.gridy = 0;
139             add(new Label(getString("Print Command")), gbc);
140             if (command == null)
141 	        command = new TextField("lp" /* NO18N */, 10);
142             gbc.gridx = 3;
143             add(command, gbc);
144 
145             gbc.gridx = 1;
146             gbc.gridy = 1;
147             add(new Label(getString("File Name")), gbc);
148             if (fileName == null)
149 	        fileName = new TextField("" /* NO18N */, 10);
150             gbc.gridx = 3;
151             add(fileName, gbc);
152 
153             ActionListener al = new StartPrintingListener();
154             command.addActionListener(al);
155             fileName.addActionListener(al);
156         }
157 
158         private void addCheckboxGroup() {
159 
160             GridBagConstraints gbc = new GridBagConstraints();
161             gbc.weightx = gbc.weighty = 1;
162 
163             options = new CheckboxGroup();
164               printer = new Checkbox();
165             file = new Checkbox();
166             printer.setCheckboxGroup(options);
167             file.setCheckboxGroup(options);
168             options.setSelectedCheckbox(printer);
169 
170             printer.addItemListener(new PrintSelectedListener());
171             file.addItemListener(new FileSelectedListener());
172 
173             gbc.gridx = 0;
174 
175             gbc.gridy = 0;
176             add(printer, gbc);
177             gbc.gridy = 1;
178             add(file, gbc);
179         }
180 
181         private void addButtons() {
182 
183             Button fileMore = new Button("..." /* NO18N */);
184             Button print = new Button(getString("Print"));
185             Button cancel = new Button(getString("Cancel"));
186             Button help = new Button(getString("Help"));
187 
188             GridBagConstraints gbc = new GridBagConstraints();
189             gbc.weightx = gbc.weighty = 1;
190 
191             gbc.gridx = 5;
192             gbc.gridy = 1;
193             add(fileMore, gbc);
194 
195 
196             gbc.gridx = 0;
197       //      gbc.gridy = 2;
198             gbc.gridwidth = GridBagConstraints.REMAINDER;
199             gbc.fill = GridBagConstraints.BOTH;
200       //      gbc.insets = new Insets(0, 10, 0, 10);
201       //      gbc.weighty = .1;
202       //   add(new LineSeparator(), gbc);
203       //      gbc.weighty = 1;
204 
205             Panel p = new Panel();
206             gbc.insets = new Insets(0, 10, 0, 10);
207             gbc.gridy = 2;
208             add(p, gbc);
209 
210             p.setLayout(new GridBagLayout());
211             gbc = new GridBagConstraints();
212             gbc.fill = GridBagConstraints.HORIZONTAL;
213             gbc.weightx = gbc.weighty = 1;
214 
215             p.add(print, gbc);
216             p.add(cancel, gbc);
217             p.add(help, gbc);
218 
219             print.addActionListener(new StartPrintingListener());
220             cancel.addActionListener(new CancelButtonListener());
221             help.addActionListener(new HelpButtonListener());
222             fileMore.addActionListener(new FileMoreButtonListener());
223             addWindowListener(new WindowCloseListener());
224 
225         }
226 
227         /**
228          * Called when the print frame has to be closed. IT may be closed
229          * as a result of the user choosing any one of "print", "cancel" or
230          * just the window close (which also cancels the printing).
231          * @param doIt true if the printing should be carried out, false
232          * if it is to be cancelled.
233          */
234         private void close(boolean doIt) {
235             if (doIt) {
236 
237 	        Checkbox cb = options.getSelectedCheckbox();
238 	        String dest = null;
239 
240 	        try {
241 	            if (cb == printer) {
242 	                dest = command.getText().trim();
243 	                if (dest.length() == 0)
244 	                    return;
245 	                else
246 	                    print(dest);
247 	            } else {
248 	                dest = fileName.getText().trim();
249 	                if (dest.length() == 0)
250 	                    return;
251 	                else
252 	                    saveToFile(dest);
253 	            }
254 	        } catch (IOException e) {
255 	            // System.out.println(e); XXX
256 	        }
257             } // end of doIt
258 
259             dispose();
260         }// end of close
261 
262         /**
263          * Prints the string to a file and then send the file's contents
264          * to the printer. It then deletes the file.
265          * @param command the print comman to be used
266          */
267         private void print(String command) throws IOException {
268             Thread printThread = new PrintThread(command);
269             printThread.start();
270             saveToFile(defaultFileName);
271         }
272 
273         /**
274          * Saves the string onto the file.
275          * @param fileName the file to which the string must be written
276          */
277         private void saveToFile(String fileName) throws IOException {
278             PrintWriter outFile = null;
279             outFile = new PrintWriter(new BufferedWriter(new
280                       FileWriter(fileName)));
281             outFile.print(text);
282             outFile.flush();
283             outFile.close();
284         }
285 
286         // Listeners for the gui components:
287         // javac in current makefile will not compile if these are anonymous.
288 
289         private class PrintSelectedListener implements ItemListener {
290             public void itemStateChanged(ItemEvent e) {
291 	        command.setEditable(true);
292 	        fileName.setEditable(false);
293             }
294         }
295 
296         private class FileSelectedListener implements ItemListener {
297             public void itemStateChanged(ItemEvent e) {
298 	        command.setEditable(false);
299 	        fileName.setEditable(true);
300             }
301         }
302 
303         private class StartPrintingListener implements ActionListener {
304             public void actionPerformed(ActionEvent e) {
305 	        close(true);
306             }
307         }
308 
309         private  class CancelButtonListener implements ActionListener {
310             public void actionPerformed(ActionEvent e) {
311 	        close(false);
312             }
313         }
314 
315         private  class HelpButtonListener implements ActionListener {
316             public void actionPerformed(ActionEvent e) {
317 	        HelpDialog hd = new HelpDialog(PrintFrame.this,
318 		getString("Help for Date/Time Helper"), false);
319 	        hd.setVisible(true);
320 	        hd.setText(getString(hrb, "PrintUtilHelp"));
321             }
322         }
323 
324         private  class FileMoreButtonListener implements
325         ActionListener {
326 
327             public void actionPerformed(ActionEvent e) {
328 
329 	        // Turn off print "command" and enable output "file name"
330 	        options.setSelectedCheckbox(file);
331 	        command.setEditable(false);
332 	        fileName.setEditable(true);
333 
334 	        FileDialog fd = new FileDialog(PrintFrame.this,
335 				       getString("SEAM File Helper"),
336 				       FileDialog.SAVE);
337 	        fd.setDirectory(System.getProperty("user.dir" /* NO18N */));
338 
339 	        // Use what's in the fileName field already to initialize the
340 	        // FileDialog
341 	        String fileNameText = fileName.getText();
342 	        if (fileNameText != null) {
343 	            File file = new File(fileNameText);
344 	            if (file.isDirectory())
345 	                fd.setDirectory(fileNameText);
346 	            else {
347 	                fd.setFile(fileNameText);
348 	                String parent = file.getParent();
349 	                if (parent != null)
350 	                    fd.setDirectory(parent);
351 	            }
352 	        }
353 
354 	        fd.setVisible(true);
355 	        if (fd.getFile() != null && fd.getFile().length() > 0)
356 	            fileName.setText(fd.getDirectory() + fd.getFile());
357             }
358         }
359 
360         /**
361          * This class prints out to a temporary file defaultFileName, send
362          * that to the printer, and then deletes the file after TIME_OUT
363          * milliseconds.
364          */
365         private class PrintThread extends Thread {
366             private String command;
367             private long TIME_OUT = 30000; // milliseconds
368 
369             public PrintThread(String command) {
370 	        this.command = command;
371             }
372 
373             public void run() {
374 	        try {
375 	            Process printProcess = Runtime.getRuntime()
376 	            .exec(command + " " /* NO18N */ + defaultFileName);
377 	            try {
378 	                sleep(TIME_OUT);
379 	            } catch (InterruptedException e) {}
380 	            printProcess.destroy();
381 	            File tempFile = new File(PrintFrame.this.defaultFileName);
382 	            tempFile.delete();
383 	        } catch (IOException e) {
384 	            // System.err.println(e); XXX
385 	        }
386             }
387         }
388 
389         private  class WindowCloseListener extends  WindowAdapter {
390             public void windowClosing(WindowEvent e) {
391 	        close(false);
392             }
393         }
394     }  // class PrintFrame
395 }
396