KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > FileHandler


1 /*
2  * @(#)FileHandler.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.print.*;
39 import java.util.*;
40 import java.awt.geom.*;
41 import java.awt.font.*;
42 import javax.swing.text.*;
43
44 import javax.jnlp.FileOpenService;
45 import javax.jnlp.FileSaveService;
46 import javax.jnlp.PrintService;
47 import javax.jnlp.FileContents;
48 import javax.jnlp.ServiceManager;
49 import javax.jnlp.UnavailableServiceException;
50 import java.io.*;
51
52 public class FileHandler {
53    
54     static private FileOpenService _fos = null;
55     static private FileSaveService _fss = null;
56     static private PrintService _ps = null;
57         
58     static private FileContents _fc = null;
59     
60     static private JTextComponent editor = null;
61     
62     static public boolean isEnabled() {
63     return true;
64     }
65     
66     static public String JavaDoc open() {
67     initialize();
68     try {
69         _fc = _fos.openFileDialog(null, null);
70         return readFromFile(_fc);
71     } catch(IOException ioe) {
72         ioe.printStackTrace(System.out);
73         return null;
74     }
75     };
76     
77     static public void save(String JavaDoc txt) {
78     initialize();
79     try {
80         // Show save dialog if no name is already given
81
if (_fc == null) {
82         _fc = _fss.saveFileDialog(null, null, new StringBufferInputStream(txt), null);
83         // file saved, done
84
return;
85         }
86         // use this only when filename is known
87
if (_fc != null) {
88         writeToFile(txt, _fc);
89         }
90     } catch(IOException ioe) {
91         ioe.printStackTrace(System.out);
92         return;
93     }
94     };
95     
96     static public void saveAs(String JavaDoc txt) {
97     initialize();
98     try {
99         if (_fc == null) {
100         // If not already saved. Save-as is like save
101
save(txt);
102         return;
103         } else {
104         _fc = _fss.saveAsFileDialog(null, null, _fc);
105         }
106     } catch(IOException ioe) {
107         ioe.printStackTrace(System.out);
108         return;
109     }
110     };
111     
112     static public void print(JTextComponent textArea) {
113         editor = textArea;
114
115         // Creating printjob on a separate user thread
116
// to workaround a known awt bug 4394889/4218471.
117
// window does n't get repainted when print dialog displayed.
118

119     new Thread JavaDoc() {
120         public void run() {
121             initialize();
122             try {
123                     if (_ps != null) {
124                     _ps.print(new WebpadPrinter());
125                      return;
126                     }
127                 } catch(Exception JavaDoc e) {
128                  e.printStackTrace(System.out);
129                  return;
130                 }
131               }
132             }.start();
133     };
134  
135     static private void writeToFile(String JavaDoc txt, FileContents fc) throws IOException {
136     int sizeNeeded = txt.length() * 2;
137     if (sizeNeeded > fc.getMaxLength()) fc.setMaxLength(sizeNeeded);
138     BufferedWriter os = new BufferedWriter(new OutputStreamWriter(_fc.getOutputStream(true)));
139     os.write(txt);
140     os.close();
141     }
142     
143     static private String JavaDoc readFromFile(FileContents fc) throws IOException {
144     if (fc == null) return null;
145     BufferedReader br = new BufferedReader(new InputStreamReader(_fc.getInputStream()));
146     StringBuffer JavaDoc sb = new StringBuffer JavaDoc((int)_fc.getLength());
147     String JavaDoc line = br.readLine();
148     while(line != null) {
149         sb.append(line);
150         sb.append("\n");
151         line = br.readLine();
152     }
153     br.close();
154     return sb.toString();
155     }
156     
157     static private synchronized void initialize() {
158     if (_fss != null) return;
159     try {
160         _fos = (FileOpenService)ServiceManager.lookup("javax.jnlp.FileOpenService");
161         _fss = (FileSaveService)ServiceManager.lookup("javax.jnlp.FileSaveService");
162         _ps = (PrintService)ServiceManager.lookup("javax.jnlp.PrintService");
163     } catch(UnavailableServiceException e) {
164            _fos = null;
165            _fss = null;
166            _ps = null;
167     }
168     }
169
170
171 static class WebpadPrinter implements Printable {
172
173     public int print(Graphics g, PageFormat pageFormat,
174         int pageIndex) {
175         Graphics2D g2d = (Graphics2D)g;
176
177         try {
178         return paintText(g2d, pageFormat, pageIndex);
179         } catch (Exception JavaDoc e) {
180             e.printStackTrace();
181             return Printable.NO_SUCH_PAGE;
182          }
183             }
184
185     int paintText(Graphics2D g2d, PageFormat pageFormat,
186             int pageIndex) throws Exception JavaDoc {
187         String JavaDoc holdString;
188
189         int pageImgHeight = (int)pageFormat.getImageableHeight();
190         int pageHeight = (int)pageFormat.getHeight();
191             
192         g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
193         g2d.setFont(editor.getGraphics().getFont());
194         g2d.setColor(Color.black);
195
196         String JavaDoc dispText = null;
197         try {
198         dispText = editor.getText(0, editor.getDocument().getLength());
199         } catch (BadLocationException e) {
200             throw new Exception JavaDoc(e.getMessage());
201         }
202         FontRenderContext frc = g2d.getFontRenderContext();
203         Rectangle2D rect = g2d.getFont().getMaxCharBounds(frc);
204         double charWidth = rect.getWidth();
205         double charHeight = rect.getHeight() + 2.0d;
206         double maxLineWidth = pageFormat.getImageableWidth();
207         int maxCharsPerLine = (int)(maxLineWidth / (double)charWidth);
208
209         String JavaDoc [] lines = getLines(dispText);
210
211         int numLines = lines.length;
212         double canvasHeight = charHeight * (double)numLines;
213         int linesPerPage = (int)(pageImgHeight / charHeight);
214         int numPages = numLines / linesPerPage + 1;
215
216         int startLineNum = linesPerPage * pageIndex;
217
218         int linesForThisPage = getNumLinesForPage(lines, pageIndex, linesPerPage);
219         int endLineNum = startLineNum + linesForThisPage - 1;
220
221
222         if (startLineNum >= lines.length) {
223             return Printable.NO_SUCH_PAGE;
224         }
225             
226         String JavaDoc [] linesToPrint = new String JavaDoc[linesForThisPage];
227
228         System.arraycopy(lines, startLineNum, linesToPrint, 0, linesForThisPage);
229             
230         float y = 10.0f;
231         LineMetrics lm = g2d.getFont().getLineMetrics("A", frc);
232         double yinc = lm.getHeight() + 2.0;
233         for (int i = 0; i<linesToPrint.length; i++) {
234             g2d.drawString(linesToPrint[i], 10.0f, y);
235             y = (float)((double)y + yinc);
236         }
237         return Printable.PAGE_EXISTS;
238
239           }
240
241     String JavaDoc [] getLines(String JavaDoc text) {
242         // breaks string at '\n' into string array
243
StringTokenizer st = new StringTokenizer(text,"\n",true);
244         Vector v = new Vector();
245         while(st.hasMoreTokens()) {
246
247                 /*
248                 ** This implementation is to workaround a know
249                 ** StringTokenizer bug 4140850 due to which
250                 ** empty lines if any inside the document were not
251                 ** getting printed.
252                 */

253                 
254                        String JavaDoc s = st.nextToken();
255                    if (s.equals("\n")) {
256               v.add("");
257                    } else {
258               v.add(s);
259                       if (st.hasMoreTokens())
260                     st.nextToken(); // Skip '\n' separator
261
}
262         }
263         return (String JavaDoc [])v.toArray(new String JavaDoc[0]);
264     }
265
266      int getNumLinesForPage(String JavaDoc [] lines, int pageIndex, int linesPerPage)
267         {
268     if (lines.length < (pageIndex + 1) * linesPerPage) {
269         int val = lines.length - pageIndex * linesPerPage;
270         return val;
271        } else {
272         return linesPerPage;
273        }
274      }
275
276                 
277    }
278 }
279
Popular Tags