KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > pentaho > plugin > print > PrintComponent


1 /**
2  * Copyright 2006 Pentaho Corporation. All rights reserved.
3  * This software was developed by Pentaho Corporation and is provided under the terms
4  * of the Mozilla Public License, Version 1.1, or any later version. You may not use
5  * this file except in compliance with the license. If you need a copy of the license,
6  * please go to http://www.mozilla.org/MPL/MPL-1.1.txt. The Original Code is the Pentaho
7  * BI Platform. The Initial Developer is Pentaho Corporation.
8  *
9  * Software distributed under the Mozilla Public License is distributed on an "AS IS"
10  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
11  * the license for the specific language governing your rights and limitations.
12  *
13  * @created Jul 5, 2005
14  * @author William Seyler
15  **/

16
17 package org.pentaho.plugin.print;
18
19 import java.awt.print.PrinterException JavaDoc;
20 import java.awt.print.PrinterJob JavaDoc;
21 import java.io.FileInputStream JavaDoc;
22 import java.io.FileNotFoundException JavaDoc;
23 import java.io.IOException JavaDoc;
24 import java.io.InputStream JavaDoc;
25 import java.io.OutputStream JavaDoc;
26 import java.util.ArrayList JavaDoc;
27
28 import javax.print.PrintService JavaDoc;
29
30 import org.apache.commons.logging.Log;
31 import org.apache.commons.logging.LogFactory;
32 import org.apache.fop.apps.Driver;
33 import org.apache.fop.render.awt.AWTRenderer;
34 import org.pentaho.core.repository.ISolutionRepository;
35 import org.pentaho.core.solution.IActionResource;
36 import org.pentaho.core.system.PentahoSystem;
37 import org.pentaho.messages.Messages;
38 import org.pentaho.plugin.ComponentBase;
39 import org.pentaho.plugin.core.StandardSettings;
40 import org.xml.sax.InputSource JavaDoc;
41
42 /**
43  *
44  * Implements a PrintComponent class that will send a attached print file to a
45  * specified printer.
46  */

47 public class PrintComponent extends ComponentBase {
48     /**
49      *
50      */

51     private static final long serialVersionUID = 7377566797214172734L;
52
53     private static final String JavaDoc LAST_PRINTER = "default-printer"; // Parameter name uset to store the last printer selected //$NON-NLS-1$
54

55     private static final String JavaDoc DEFAULT_PRINTER = "PENTAHO_DEFAULT_PRINTER"; // This should never be a real printer //$NON-NLS-1$
56

57     private static final String JavaDoc COPIES = "copies"; //$NON-NLS-1$
58

59     private static final String JavaDoc PRINT_FILE = "printFile"; //$NON-NLS-1$
60

61     private static final String JavaDoc REPORT_OUTPUT = "report-output"; //$NON-NLS-1$
62

63     public Log getLogger() {
64         return LogFactory.getLog(PrintComponent.class);
65     }
66
67     public boolean init() {
68         // TODO Auto-generated method stub
69
return true;
70     }
71
72     protected boolean validateSystemSettings() {
73         // This component does not have any system settings to validate
74
return true;
75     }
76
77     protected boolean validateAction() {
78
79         if (!isDefinedInput(PRINT_FILE) && !isDefinedResource(PRINT_FILE) && !isDefinedInput("report-output") && !isDefinedOutput(StandardSettings.PRINTER_NAME)) { //$NON-NLS-1$
80
error(Messages.getErrorString("PrintComponent.ERROR_0001_NO_PRINT_FILE_DEFINED") + getActionName()); //$NON-NLS-1$
81
return false;
82         }
83         return true;
84     }
85
86     protected boolean executeAction() {
87         String JavaDoc printFileName = null;
88         IActionResource printFileResource = null;
89
90         if (isDefinedInput(PRINT_FILE)) {
91             printFileName = getInputStringValue(PRINT_FILE);
92         } else if (isDefinedResource(PRINT_FILE)) {
93             printFileResource = getResource(PRINT_FILE);
94         }
95
96         InputStream JavaDoc inStream = null;
97         String JavaDoc printerName = DEFAULT_PRINTER;
98         String JavaDoc lastPrinter = null;
99
100         // Get the printer name if it's in the inputs
101
if (isDefinedInput(StandardSettings.PRINTER_NAME)) {
102             printerName = getInputStringValue(StandardSettings.PRINTER_NAME);
103         }
104
105         if (isDefinedInput(LAST_PRINTER)) {
106             lastPrinter = getInputStringValue(LAST_PRINTER);
107         } else {
108             lastPrinter = null;
109         }
110
111         if (isDefinedOutput(StandardSettings.PRINTER_NAME) && !printerName.equals("")) { //$NON-NLS-1$
112
// we are done here
113
setOutputValue(StandardSettings.PRINTER_NAME, printerName);
114             // Save for next time
115
if (isDefinedOutput(LAST_PRINTER)) {
116                 setOutputValue(LAST_PRINTER, printerName);
117             }
118             return true;
119         }
120
121         PrintService JavaDoc printer = getPrinterInternal(printerName, lastPrinter);
122         if (printer == null) {
123             if (!feedbackAllowed()) {
124                 error(Messages.getErrorString("PrintComponent.ERROR_0002_NO_SUITABLE_PRINTER")); //$NON-NLS-1$
125
return false;
126             }
127             // we created the printer feedback entry already
128
return true;
129         }
130         // Save for next time
131
if (isDefinedOutput(LAST_PRINTER)) {
132             setOutputValue(LAST_PRINTER, printerName);
133         }
134
135         // Get the number of copies
136
int copies = 1;
137         if (isDefinedInput(COPIES)) {
138             copies = Integer.valueOf(getInputStringValue(COPIES)).intValue();
139         }
140
141         // Check for a valid printFileName or printFile Resource
142
if (printFileName != null) {
143                 ISolutionRepository repository = PentahoSystem.getSolutionRepository(getSession());
144                 inStream = repository.getResourceInputStream(printFileName);
145
146             if (inStream == null) { // this should probably never execute
147
// inStream==null should be caught at the
148
// above try/catch
149
return false;
150             }
151         } else if (printFileResource != null) {
152             inStream = getResourceInputStream(printFileResource);
153         } else if (isDefinedInput(REPORT_OUTPUT)) {
154             inStream = getInputStream(REPORT_OUTPUT);
155         } else { // This should never happen if we validated ok.
156
return false;
157         }
158         try {
159           // Set the input source for sending to the driver.
160
InputSource JavaDoc source = new InputSource JavaDoc(inStream);
161           try {
162               Driver driver = new Driver(source, null);
163               PrinterJob JavaDoc pj = PrinterJob.getPrinterJob();
164               // Check to see if we're using the default printer or the user
165
// requested a different printer.
166
if (!(DEFAULT_PRINTER.equals(printerName))) {
167                   pj.setPrintService(getPrinterInternal(printerName, lastPrinter));
168               }
169               PrintRenderer renderer = new PrintRenderer(pj, copies);
170               driver.setRenderer(renderer);
171               driver.run();
172           } catch (Exception JavaDoc ex) {
173               return false;
174           }
175         } finally {
176           try {
177             inStream.close();
178           } catch (IOException JavaDoc ex) {
179             // TODO: Provide message here...
180
ex.printStackTrace();
181           }
182         }
183         return true;
184     }
185
186     public void done() {
187         // TODO Auto-generated method stub
188

189     }
190
191     /**
192      * Takes a printer name and find the associated PrintService. If no match
193      * can be made it randomly picks the first printer listed from the call to
194      * lookupPrintServices.
195      *
196      * @param printerName
197      * @return PrintService referenced by the printerName
198      */

199     public PrintService JavaDoc getPrinterInternal(String JavaDoc printerName, String JavaDoc lastPrinterName) {
200         // The parameter value was not provided, and we are allowed to create
201
// user interface forms
202

203         PrintService JavaDoc[] services = PrinterJob.lookupPrintServices();
204         // If the printerName is valid then we just return the servies
205
// associated with it.
206
for (int i = 0; i < services.length; i++) {
207             if (services[i].getName().equals(printerName)) {
208                 return services[i];
209             }
210         }
211         if (feedbackAllowed()) {
212             // If it's not valid then lets find one and end this current run.
213
ArrayList JavaDoc values = new ArrayList JavaDoc();
214             for (int i = 0; i < services.length; i++) {
215                 String JavaDoc value = services[i].getName();
216                 values.add(value);
217             }
218             createFeedbackParameter(StandardSettings.PRINTER_NAME, Messages.getString("PrintComponent.USER_PRINTER_NAME"), "", lastPrinterName, values, null, "select"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
219
promptNeeded();
220             return null;
221         }
222         return services[0];
223     }
224
225     /**
226      * Takes a printer name and find the associated PrintService. If no match
227      * can be made it randomly picks the first printer listed from the call to
228      * lookupPrintServices.
229      *
230      * @param printerName
231      * @return PrintService referenced by the printerName
232      */

233     public static PrintService JavaDoc getPrinter(String JavaDoc printerName) {
234         // The parameter value was not provided, and we are allowed to create
235
// user interface forms
236

237         PrintService JavaDoc[] services = PrinterJob.lookupPrintServices();
238         // If the printerName is valid then we just return the servies
239
// associated with it.
240
for (int i = 0; i < services.length; i++) {
241             if (services[i].getName().equals(printerName)) {
242                 return services[i];
243             }
244         }
245         return services[0];
246     }
247
248     public static PrintService JavaDoc getDefaultPrinter() {
249         // The parameter value was not provided, and we are allowed to create
250
// user interface forms
251

252         PrintService JavaDoc[] services = PrinterJob.lookupPrintServices();
253         if (services == null || services.length == 0) {
254             return null;
255         }
256         return services[0];
257     }
258
259     /**
260      *
261      * Extends AWTRenderer to create a class that will print to a specified
262      * printerJob
263      *
264      */

265     class PrintRenderer extends AWTRenderer {
266
267         private static final int EVEN_AND_ALL = 0;
268
269         private static final int EVEN = 1;
270
271         private static final int ODD = 2;
272
273         private int startNumber;
274
275         private int endNumber;
276
277         private int mode = EVEN_AND_ALL;
278
279         private int copies = 1;
280
281         private PrinterJob JavaDoc printerJob;
282
283         PrintRenderer(PrinterJob JavaDoc printerJob, int copies) {
284             super(null);
285
286             this.printerJob = printerJob;
287             this.copies = copies;
288             startNumber = 0;
289             endNumber = -1;
290
291             printerJob.setPageable(this);
292             printerJob.setCopies(this.copies);
293             mode = EVEN_AND_ALL;
294             String JavaDoc str = null;
295             if (str != null) {
296                 try {
297                     mode = Boolean.valueOf(str).booleanValue() ? EVEN : ODD;
298                 } catch (Exception JavaDoc e) {
299                 }
300
301             }
302
303         }
304
305         public void stopRenderer(OutputStream JavaDoc outputStream) throws IOException JavaDoc {
306             super.stopRenderer(outputStream);
307
308             if (endNumber == -1)
309                 endNumber = getPageCount();
310
311             ArrayList JavaDoc numbers = getInvalidPageNumbers();
312             for (int i = numbers.size() - 1; i > -1; i--)
313                 removePage(Integer.parseInt((String JavaDoc) numbers.get(i)));
314
315             try {
316                 printerJob.print();
317             } catch (PrinterException JavaDoc e) {
318                 e.printStackTrace();
319                 throw new IOException JavaDoc(Messages.getString("PrintComponent.ERROR_0003_UNABLE_TO_PRINT", e.getClass().getName(), e.getMessage())); //$NON-NLS-1$
320
}
321         }
322
323 // public void renderPage(Page page) {
324
// pageWidth = (int) (page.getWidth() / 1000f);
325
// pageHeight = (int) (page.getHeight() / 1000f);
326
// super.renderPage(page);
327
// }
328

329         private ArrayList JavaDoc getInvalidPageNumbers() {
330             ArrayList JavaDoc vec = new ArrayList JavaDoc();
331             int max = getPageCount();
332             boolean isValid;
333             for (int i = 0; i < max; i++) {
334                 isValid = true;
335                 if (i < startNumber || i > endNumber) {
336                     isValid = false;
337                 } else if (mode != EVEN_AND_ALL) {
338                     if (mode == EVEN && ((i + 1) % 2 != 0))
339                         isValid = false;
340                     else if (mode == ODD && ((i + 1) % 2 != 1))
341                         isValid = false;
342                 }
343                 if (!isValid)
344                     vec.add(i + ""); //$NON-NLS-1$
345
}
346             return vec;
347         }
348     } // class PrintRenderer
349
}
350
Popular Tags