KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > webtools > print > applet > FopPrintApplet


1 /*
2  * $Id: FopPrintApplet.java 6590 2006-01-26 07:21:36Z jaz $
3  *
4  * Copyright (c) 2001-2006 The Open For Business Project - www.ofbiz.org
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included
14  * in all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
21  * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
22  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23  *
24  */

25 //package print;
26
package org.ofbiz.webtools.print.applet;
27
28 import java.awt.*;
29 import java.io.*;
30 import java.net.URL JavaDoc;
31 import java.net.URLConnection JavaDoc;
32 import java.net.URLEncoder JavaDoc;
33 import java.rmi.Naming JavaDoc;
34 import java.util.ArrayList JavaDoc;
35 import java.util.HashMap JavaDoc;
36 import java.util.Iterator JavaDoc;
37 import java.util.List JavaDoc;
38 import java.util.Locale JavaDoc;
39 import java.util.Map JavaDoc;
40 import java.util.StringTokenizer JavaDoc;
41 import java.util.Vector JavaDoc;
42 import javax.print.Doc JavaDoc;
43 import javax.print.DocFlavor JavaDoc;
44 import javax.print.DocPrintJob JavaDoc;
45 import javax.print.PrintException JavaDoc;
46 import javax.print.PrintService JavaDoc;
47 import javax.print.PrintServiceLookup JavaDoc;
48 import javax.print.ServiceUI JavaDoc;
49 import javax.print.SimpleDoc JavaDoc;
50 import javax.print.event.PrintJobListener JavaDoc;
51 import javax.print.event.PrintJobEvent JavaDoc;
52 import javax.print.attribute.DocAttributeSet JavaDoc;
53 import javax.print.attribute.HashDocAttributeSet JavaDoc;
54 import javax.print.attribute.HashPrintRequestAttributeSet JavaDoc;
55 import javax.print.attribute.PrintRequestAttributeSet JavaDoc;
56 import javax.print.attribute.standard.Copies JavaDoc;
57 import javax.print.attribute.standard.JobName JavaDoc;
58 import javax.swing.*;
59
60 import org.apache.commons.codec.binary.Base64;
61 import org.apache.fop.apps.Driver;
62 import org.apache.fop.layout.Page;
63 import org.apache.fop.render.awt.AWTRenderer;
64 import org.xml.sax.InputSource JavaDoc;
65
66 import org.ofbiz.webtools.print.rmi.FopPrintRemote;
67
68 /**
69  * FopPrinter
70  *
71  * @author <a HREF="mailto:jaz@ofbiz.org">Andy Zeneski</a>
72  * @version $Rev: 6590 $
73  * @since Jan 23, 2006
74  */

75 public class FopPrintApplet extends JApplet implements PrintJobListener JavaDoc {
76
77     public static final String JavaDoc module = FopPrintApplet.class.getName();
78
79     protected DocFlavor JavaDoc flavor = DocFlavor.SERVICE_FORMATTED.PAGEABLE;
80     protected String JavaDoc requestPath = "/webtools/control/getXslFo";
81     protected String JavaDoc sessionId = null;
82     protected String JavaDoc serverUrl = null;
83     protected String JavaDoc rmiHost = null;
84     protected String JavaDoc rmiName = null;
85     protected int rmiPort = 1099;
86     protected boolean resetCookies = false;
87     protected boolean started = false;
88
89     protected List JavaDoc printing = new ArrayList JavaDoc();
90     protected List JavaDoc noPrint = new ArrayList JavaDoc();
91     protected Map JavaDoc jobQueue = new HashMap JavaDoc();
92     protected Map JavaDoc jobList = new HashMap JavaDoc();
93     protected Map JavaDoc toPrint = new HashMap JavaDoc();
94     protected FopPrintApplet applet = null;
95
96     public void init(Map JavaDoc toPrint, String JavaDoc sessionId, String JavaDoc serverUrl, String JavaDoc rmiName, String JavaDoc rmiHost, int rmiPort, boolean reset) {
97         this.sessionId = sessionId;
98         this.serverUrl = serverUrl;
99         this.rmiName = rmiName;
100         this.rmiHost = rmiHost;
101         this.rmiPort = rmiPort;
102         this.toPrint = toPrint;
103         this.resetCookies = reset;
104         this.applet = this;
105         if (this.sessionId == null) {
106             this.sessionId = "";
107         }
108     }
109
110     public void init() {
111         int port = 1099;
112         if (this.getParameter("rmi-port") != null) {
113             try {
114                 port = Integer.parseInt(this.getParameter("rmi-port"));
115             } catch (NumberFormatException JavaDoc e) {
116                 System.out.println("INFO: not able to parse rmi-port parameter. Using default 1099");
117             }
118         }
119
120         String JavaDoc sessionId = this.getParameter("session-id");
121         String JavaDoc serverUrl = this.getParameter("server-url");
122         String JavaDoc rmiName = this.getParameter("rmi-name");
123         String JavaDoc rmiHost = this.getParameter("rmi-host");
124         String JavaDoc reset = this.getParameter("reset-cookies");
125         boolean resetCookies = reset != null && "true".equalsIgnoreCase(reset);
126
127         Map JavaDoc toPrint = new HashMap JavaDoc();
128         boolean look = true;
129         int count = 1;
130         while (look) {
131             String JavaDoc printer = this.getParameter("printer." + count);
132             String JavaDoc screen = this.getParameter("screen." + count);
133             if (screen != null && screen.length() > 0) {
134                 toPrint.put(screen, printer);
135                 count++;
136             } else {
137                 look = false;
138             }
139         }
140         this.init(toPrint, sessionId, serverUrl, rmiName, rmiHost, port, resetCookies);
141     }
142
143     public void paint(Graphics g) {
144         super.paint(g);
145         g.setFont(new Font("Arial", Font.BOLD, 16));
146         g.drawString("Print spooler started with [" + jobQueue.size() + "] jobs queued...", 10, 30);
147
148         if (!started) {
149             started = true;
150             //Thread worker = new Thread() {
151
//public void run() {
152
processJobs();
153                 //}
154
//};
155
//worker.start();
156
}
157     }
158
159     public void printDataTransferCompleted(PrintJobEvent JavaDoc e) {
160         JobName JavaDoc jobNameAtt = (JobName JavaDoc) e.getPrintJob().getAttributes().get(JobName JavaDoc.class);
161         String JavaDoc jobName = jobNameAtt.getValue();
162
163         System.out.println("Calling notificaton that job data transfer is complete: " + jobName);
164     }
165
166     public void printJobCompleted(PrintJobEvent JavaDoc e) {
167         JobName JavaDoc jobNameAtt = (JobName JavaDoc) e.getPrintJob().getAttributes().get(JobName JavaDoc.class);
168         String JavaDoc jobName = jobNameAtt.getValue();
169
170         JOptionPane.showMessageDialog(null, "Print job completed: " + jobName, "Job Done", JOptionPane.INFORMATION_MESSAGE);
171         System.out.println("Calling notificaton that job is now complete: " + jobName);
172         try {
173             setJobComplete(jobName, false);
174         } catch (Exception JavaDoc e1) {
175             e1.printStackTrace();
176         }
177     }
178
179     public void printJobFailed(PrintJobEvent JavaDoc e) {
180         JobName JavaDoc jobNameAtt = (JobName JavaDoc) e.getPrintJob().getAttributes().get(JobName JavaDoc.class);
181         String JavaDoc jobName = jobNameAtt.getValue();
182
183         JOptionPane.showMessageDialog(null, "Print job faild: " + jobName, "Print Error", JOptionPane.ERROR_MESSAGE);
184         System.out.println("Calling notificaton that job has failed: " + jobName);
185
186         try {
187             setJobComplete(jobName, true);
188         } catch (Exception JavaDoc e1) {
189             e1.printStackTrace();
190         }
191     }
192
193     public void printJobCanceled(PrintJobEvent JavaDoc e) {
194         JobName JavaDoc jobNameAtt = (JobName JavaDoc) e.getPrintJob().getAttributes().get(JobName JavaDoc.class);
195         String JavaDoc jobName = jobNameAtt.getValue();
196
197         JOptionPane.showMessageDialog(null, "Print job was cancelled: " + jobName, "Print Error", JOptionPane.ERROR_MESSAGE);
198         System.out.println("Calling notificaton that job has been cancelled: " + jobName);
199         try {
200             setJobComplete(jobName, true);
201         } catch (Exception JavaDoc e1) {
202             e1.printStackTrace();
203         }
204     }
205
206     public void printJobNoMoreEvents(PrintJobEvent JavaDoc e) {
207         JobName JavaDoc jobNameAtt = (JobName JavaDoc) e.getPrintJob().getAttributes().get(JobName JavaDoc.class);
208         String JavaDoc jobName = jobNameAtt.getValue();
209
210         System.out.println("Calling notificaton that job has no more events: " + jobName);
211         try {
212             setJobComplete(jobName, true);
213         } catch (Exception JavaDoc e1) {
214             e1.printStackTrace();
215         }
216     }
217
218     public void printJobRequiresAttention(PrintJobEvent JavaDoc e) {
219         JobName JavaDoc jobNameAtt = (JobName JavaDoc) e.getPrintJob().getAttributes().get(JobName JavaDoc.class);
220         String JavaDoc jobName = jobNameAtt.getValue();
221
222         System.out.println("Calling notificaton that job requires attention: " + jobName);
223         try {
224             setJobComplete(jobName, true);
225         } catch (Exception JavaDoc e1) {
226             e1.printStackTrace();
227         }
228         JOptionPane.showMessageDialog(null, "Print Warning", "Print job requires attention: " + jobName, JOptionPane.WARNING_MESSAGE);
229     }
230
231     protected void processJobs() {
232         Iterator JavaDoc i = toPrint.keySet().iterator();
233         while (i.hasNext()) {
234             String JavaDoc screen = (String JavaDoc) i.next();
235             String JavaDoc printer = (String JavaDoc) toPrint.get(screen);
236
237             String JavaDoc screenUri = this.getScreenUri(screen);
238             PrintSettings settings = this.getPrintSettings(screenUri, printer);
239             if (settings != null) {
240                 jobQueue.put(screenUri, settings);
241                 jobList.put(screen, settings);
242                 this.repaint();
243             } else {
244                 System.out.println("No printer for job: " + screenUri);
245                 this.getAppletContext().showStatus("No printer(s) available.");
246             }
247         }
248
249         // if nothing to do, call complete
250
if (jobQueue.size() == 0) {
251             try {
252                 this.sendComplete();
253             } catch (Exception JavaDoc e) {
254                 e.printStackTrace();
255             }
256         } else {
257             // begin processing
258
Iterator JavaDoc x = jobList.keySet().iterator();
259             while (x.hasNext()) {
260                 final String JavaDoc screen = (String JavaDoc) x.next();
261                 Thread JavaDoc worker = new Thread JavaDoc() {
262                     public void run() {
263                         try {
264                             printFo((rmiHost == null ? serverUrl : rmiHost), screen);
265                         } catch (Exception JavaDoc e) {
266                             e.printStackTrace();
267                             getAppletContext().showStatus("Unable to render print job.");
268                         }
269                     }
270                 };
271                 worker.start();
272             }
273         }
274
275         this.repaint();
276     }
277
278     protected void printFo(String JavaDoc url, String JavaDoc screenUrl) throws Exception JavaDoc {
279         if (url.startsWith("http")) {
280             this.printFoFromHttp(url, screenUrl);
281         } else if (url.startsWith("rmi")) {
282             this.printFoFromRmi(url, screenUrl);
283         } else {
284             this.getAppletContext().showStatus("Unsupported protocol used.");
285         }
286     }
287
288     protected void printFoFromRmi(String JavaDoc lookup, String JavaDoc screenUrl) throws Exception JavaDoc {
289         InputSource JavaDoc source = this.getScreenFromRmi(lookup, screenUrl);
290         this.renderFO(this.getScreenUri(screenUrl), source);
291     }
292
293     protected void printFoFromHttp(String JavaDoc server, String JavaDoc screenUrl) throws Exception JavaDoc {
294         InputSource JavaDoc source = this.getScreenFromHttp(server, screenUrl);
295         this.renderFO(this.getScreenUri(screenUrl), source);
296     }
297
298     protected InputSource JavaDoc getScreenFromHttp(String JavaDoc server, String JavaDoc screenUrl) throws Exception JavaDoc {
299         String JavaDoc screen = this.getScreenUri(screenUrl);
300         Map JavaDoc params = this.getParameters(screenUrl);
301         Iterator JavaDoc i = params.keySet().iterator();
302         String JavaDoc paramString = "?screenUri=" + URLEncoder.encode(screen, "UTF-8");
303         while (i.hasNext()) {
304             String JavaDoc key = (String JavaDoc) i.next();
305             Object JavaDoc val = params.get(key);
306             paramString = paramString + "&" + key + "=" + URLEncoder.encode(val.toString(), "UTF-8");
307         }
308
309         URL JavaDoc url = new URL JavaDoc(server + requestPath + paramString);
310         URLConnection JavaDoc con = url.openConnection();
311         con.setDoInput(true);
312         con.setDoOutput(true);
313         con.setUseCaches(false);
314         con.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
315
316         PrintWriter toServlet = new PrintWriter(con.getOutputStream());
317         toServlet.flush();
318         toServlet.close();
319
320         InputStream in = con.getInputStream();
321         BufferedReader reader = new BufferedReader(new InputStreamReader(in));
322
323         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
324         String JavaDoc line;
325         while ((line = reader.readLine()) != null) {
326             buf.append(line);
327             buf.append(System.getProperty("line.separator"));
328         }
329         reader.close();
330
331         // convert the base64 string to bytes
332
byte[] bytes = Base64.decodeBase64(buf.toString().getBytes());
333         System.out.println(new String JavaDoc(bytes));
334         return new InputSource JavaDoc(new ByteArrayInputStream(bytes));
335     }
336
337     protected InputSource JavaDoc getScreenFromRmi(String JavaDoc lookup, String JavaDoc screenUrl) throws Exception JavaDoc {
338         FopPrintRemote remote = (FopPrintRemote) Naming.lookup(lookup);
339         if (remote != null) {
340             String JavaDoc screen = this.getScreenUri(screenUrl);
341             Map JavaDoc params = this.getParameters(screenUrl);
342             byte[] fo = remote.getXslFo(screen, params);
343             return new InputSource JavaDoc(new ByteArrayInputStream(fo));
344         }
345         return null;
346     }
347
348     protected String JavaDoc getScreenUri(String JavaDoc screen) {
349         return screen.indexOf("?") != -1 ? screen.substring(0, screen.indexOf("?")) : screen;
350     }
351
352     protected Map JavaDoc getParameters(String JavaDoc screen) {
353         Map JavaDoc params = parseQueryString(screen.substring(screen.indexOf("?") + 1));
354         params.put("locale", Locale.getDefault());
355         System.out.println("Parsed parameters: " + params);
356         return params;
357     }
358
359     protected synchronized void setJobComplete(String JavaDoc jobName, boolean fail) {
360         String JavaDoc screen = null;
361         Iterator JavaDoc i = jobQueue.keySet().iterator();
362         while (i.hasNext()) {
363             String JavaDoc s = (String JavaDoc) i.next();
364             String JavaDoc internalName = s.substring(s.indexOf("#") + 1);
365             if (jobName.equals(internalName)) {
366                 screen = s;
367             }
368         }
369
370         jobQueue.remove(screen);
371         if (fail) {
372             noPrint.add(screen);
373         }
374         if (jobQueue.size() == 0) {
375             try {
376                 this.sendComplete();
377             } catch (Exception JavaDoc e) {
378                 e.printStackTrace();
379             }
380         }
381     }
382
383     protected void sendComplete() throws Exception JavaDoc {
384         // send the applet settings (via post) back to the server
385
this.postAppletSettings();
386
387         // now redirect to the done page to set cookies on browser
388
this.getAppletContext().showStatus("Sending final update to server...");
389         String JavaDoc path = "/webtools/control/printComplete?sessionId=" + URLEncoder.encode(sessionId, "UTF-8");
390         URL JavaDoc url = new URL JavaDoc(serverUrl + path);
391         System.out.println("Returning complete: " + url.toExternalForm());
392         this.getAppletContext().showStatus("Finished.");
393         this.getAppletContext().showDocument(url);
394     }
395
396     protected void postAppletSettings() throws Exception JavaDoc {
397         this.getAppletContext().showStatus("Updating settings on server...");
398
399         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
400         buf.append("sessionId=").append(sessionId);
401
402         Iterator JavaDoc i = jobList.keySet().iterator();
403         while (i.hasNext()) {
404             String JavaDoc screen = (String JavaDoc) i.next();
405             PrintSettings s = (PrintSettings) jobList.get(screen);
406
407             if (!noPrint.contains(screen)) {
408                 // serialize the print settings
409
String JavaDoc hex = null;
410                 byte[] bytes;
411                 if ((bytes = getBytes(s)) != null) {
412                     hex = toHex(bytes);
413                     System.out.println("Hex string created; receive: " + hex.length() + " characters");
414                 }
415
416                 // add settings to call back
417
if (hex != null) {
418                     // if settings exist
419
if (buf.length() > 0) {
420                        buf.append("&");
421                     }
422
423                     buf.append(URLEncoder.encode(this.getScreenUri(screen), "UTF-8"));
424                     buf.append("=");
425                     buf.append(URLEncoder.encode(hex, "UTF-8"));
426                 }
427             }
428         }
429
430         String JavaDoc path = "/webtools/control/updatePrintSettings";
431         URL JavaDoc url = new URL JavaDoc(serverUrl + path);
432         System.out.println("Posting settings back to: " + url.toExternalForm());
433
434         URLConnection JavaDoc con = url.openConnection();
435         con.setDoInput(true);
436         con.setDoOutput(true);
437         con.setUseCaches(false);
438         con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
439
440         // send the post data
441
DataOutputStream out = new DataOutputStream(con.getOutputStream());
442         out.writeBytes(buf.toString());
443         out.flush();
444         out.close();
445
446         // receive the response
447
InputStream in = con.getInputStream();
448         BufferedReader reader = new BufferedReader(new InputStreamReader(in));
449         String JavaDoc resp = reader.readLine();
450         reader.close();
451         System.out.println("Response was: " + resp);
452     }
453
454     protected PrintService JavaDoc getPrintService(String JavaDoc jobName, String JavaDoc printerName) {
455         PrintRequestAttributeSet JavaDoc aset = new HashPrintRequestAttributeSet JavaDoc();
456         PrintService JavaDoc printService[] = PrintServiceLookup.lookupPrintServices(flavor, aset);
457         PrintService JavaDoc defaultService = PrintServiceLookup.lookupDefaultPrintService();
458
459         PrintService JavaDoc service = null;
460         if (printService.length > 0) {
461             if (!resetCookies && printerName != null && printerName.length() > 0) {
462                 System.out.println("Looking for available printer: " + printerName);
463                 for (int i = 0; i < printService.length; i++) {
464                     PrintService JavaDoc svc = printService[i];
465                     if (svc.getName().equals(printerName)) {
466                         service = svc;
467                     }
468                 }
469             }
470
471             if (service == null) {
472                 aset.add(new JobName JavaDoc(jobName.substring(jobName.indexOf("#") + 1), Locale.getDefault()));
473                 this.getAppletContext().showStatus("Requesting printer settings... [" + jobName.substring(jobName.indexOf("#") + 1) + "]");
474                 try {
475                     service = ServiceUI.printDialog(null, 200, 200, printService, defaultService, flavor, aset);
476                 } catch (Throwable JavaDoc t) {
477                     t.printStackTrace();
478                 }
479
480                 if (service == null) {
481                     System.out.println("Null print service returned.");
482                 } else {
483                     System.out.println("Print service received: " + service.getName());
484                 }
485             }
486         }
487
488         return service;
489     }
490
491     protected PrintSettings getPrintSettings(String JavaDoc jobName, String JavaDoc printerInfo) {
492         PrintRequestAttributeSet JavaDoc aset = new HashPrintRequestAttributeSet JavaDoc();
493         PrintService JavaDoc printService[] = PrintServiceLookup.lookupPrintServices(flavor, aset);
494         PrintService JavaDoc defaultService = PrintServiceLookup.lookupDefaultPrintService();
495
496         PrintSettings settings = null;
497         if (printService.length > 0) {
498             PrintService JavaDoc service = null;
499             if (!resetCookies && printerInfo != null && printerInfo.length() > 0) {
500                 System.out.println("Attemping to deserialize printer info hex string.");
501                 settings = (PrintSettings) getObject(toByteArray(printerInfo));
502                 if (settings != null) {
503                     System.out.println("Looking for available printer: " + settings.getPrinterName());
504                     service = settings.getPrintService();
505                 }
506             }
507
508             if (service == null) {
509                 aset.add(new JobName JavaDoc(jobName.substring(jobName.indexOf("#") + 1), Locale.getDefault()));
510                 this.getAppletContext().showStatus("Requesting printer settings... [" + jobName.substring(jobName.indexOf("#") + 1) + "]");
511                 try {
512                     service = ServiceUI.printDialog(null, 200, 200, printService, defaultService, flavor, aset);
513                 } catch (Throwable JavaDoc t) {
514                     t.printStackTrace();
515                 }
516
517                 if (service == null) {
518                     System.out.println("Null print service returned.");
519                 } else {
520                     System.out.println("Print service received: " + service.getName());
521                     settings = new PrintSettings(service, aset);
522                 }
523             }
524         }
525
526         return settings;
527     }
528
529     /**
530      * Renders an FO inputsource to the selected printer.
531      */

532     protected void renderFO(final String JavaDoc name, final InputSource JavaDoc foFile) throws Exception JavaDoc {
533         //PrintService service = (PrintService) jobQueue.get(name);
534
PrintSettings settings = (PrintSettings) jobQueue.get(name);
535         if (settings != null) {
536             this.getAppletContext().showStatus("Rendering PDF...");
537
538             try {
539                 PrintRenderer renderer = new PrintRenderer(name, settings);
540                 Driver driver = new Driver(foFile, null);
541                 driver.setRenderer(renderer);
542                 driver.run();
543             } catch (Exception JavaDoc ex) {
544                 ex.printStackTrace();
545             }
546         }
547     }
548
549     private static String JavaDoc parseName(String JavaDoc s, StringBuffer JavaDoc sb) {
550         sb.setLength(0);
551         for (int i = 0; i < s.length(); i++) {
552             char c = s.charAt(i);
553             switch (c) {
554                 case '+':
555                     sb.append(' ');
556                     break;
557                 case '%':
558                     try {
559                         sb.append((char) Integer.parseInt(s.substring(i + 1, i + 3), 16));
560                         i += 2;
561                     } catch (NumberFormatException JavaDoc e) {
562                         throw new IllegalArgumentException JavaDoc();
563                     } catch (StringIndexOutOfBoundsException JavaDoc e) {
564                         String JavaDoc rest = s.substring(i);
565                         sb.append(rest);
566                         if (rest.length() == 2)
567                             i++;
568                     }
569                     break;
570                 default:
571                     sb.append(c);
572                     break;
573             }
574         }
575         return sb.toString();
576     }
577
578     private static Map JavaDoc parseQueryString(String JavaDoc s) {
579         System.out.println("Parsing string: " + s);
580
581         if (s == null) {
582             throw new IllegalArgumentException JavaDoc();
583         }
584         HashMap JavaDoc ht = new HashMap JavaDoc();
585         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
586         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(s, "&");
587         while (st.hasMoreTokens()) {
588             String JavaDoc pair = st.nextToken();
589             System.out.println("Next token: " + pair);
590             int pos = pair.indexOf('=');
591             if (pos == -1) {
592                 throw new IllegalArgumentException JavaDoc();
593             }
594             String JavaDoc key = parseName(pair.substring(0, pos), sb);
595             String JavaDoc val = parseName(pair.substring(pos + 1, pair.length()), sb);
596             System.out.println("Key: " + key + " / Val: " + val);
597
598             ht.put(key, val);
599         }
600         return ht;
601     }
602
603     private static String JavaDoc toHex(byte[] buf) {
604         char[] cbf = new char[buf.length * 2];
605         for (int jj = 0, kk = 0; jj < buf.length; jj++) {
606             cbf[kk++] = "0123456789ABCDEF".charAt((buf[jj] >> 4) & 0x0F);
607             cbf[kk++] = "0123456789ABCDEF".charAt(buf[jj] & 0x0F);
608         }
609         return new String JavaDoc(cbf);
610     }
611
612     private static byte[] toByteArray(String JavaDoc hex) {
613         byte[] result = new byte[hex.length() / 2];
614         for (int jj = 0, kk = 0; jj < result.length; jj++) {
615             result[jj] = (byte) (
616                     ("0123456789ABCDEF".indexOf(hex.charAt(kk++)) << 4) +
617                             "0123456789ABCDEF".indexOf(hex.charAt(kk++)));
618         }
619         return result;
620     }
621
622     private static byte[] getBytes(Object JavaDoc obj) {
623         ByteArrayOutputStream bos = null;
624         ObjectOutputStream oos = null;
625         byte[] data = null;
626         try {
627             bos = new ByteArrayOutputStream();
628             oos = new ObjectOutputStream(bos);
629             oos.writeObject(obj);
630             data = bos.toByteArray();
631         } catch (IOException e) {
632             e.printStackTrace();
633         } finally {
634             try {
635                 if (oos != null) {
636                     oos.flush();
637                     oos.close();
638                 }
639                 if (bos != null) {
640                     bos.close();
641                 }
642             } catch (IOException e) {
643                 e.printStackTrace();
644             }
645         }
646
647         return data;
648     }
649
650     private static Object JavaDoc getObject(byte[] bytes) {
651         ByteArrayInputStream bis = null;
652         ObjectInputStream ois = null;
653         Object JavaDoc obj = null;
654
655         try {
656             bis = new ByteArrayInputStream(bytes);
657             ois = new ObjectInputStream(bis);
658             obj = ois.readObject();
659         } catch (ClassNotFoundException JavaDoc e) {
660             e.printStackTrace();
661         } catch (IOException e) {
662             e.printStackTrace();
663         } finally {
664             try {
665                 if (ois != null) {
666                     ois.close();
667                 }
668                 if (bis != null) {
669                     bis.close();
670                 }
671             } catch (IOException e) {
672                 e.printStackTrace();
673             }
674         }
675
676         return obj;
677     }
678
679     // This is stolen from FOP PrintStarter
680
class PrintRenderer extends AWTRenderer {
681
682         public static final int EVEN_AND_ALL = 0;
683         public static final int EVEN = 1;
684         public static final int ODD = 2;
685
686         private int startNumber;
687         private int endNumber;
688         private int mode = EVEN_AND_ALL;
689         private int copies = 0;
690         private PrintSettings settings;
691         private PrintService JavaDoc service;
692         private String JavaDoc jobName;
693
694         PrintRenderer(String JavaDoc jobName, PrintSettings settings) {
695             super(null);
696             this.settings = settings;
697             this.jobName = jobName;
698
699             this.service = settings.getPrintService();
700             this.copies = settings.getCopies();
701             this.mode = settings.getMode();
702             this.startNumber = settings.getStartNumber();
703             this.endNumber = settings.getEndNumber();
704             this.setScaleFactor(1);
705         }
706
707         /*
708         PrintRenderer(PrintService service, String jobName) {
709             this(service, jobName, EVEN_AND_ALL, 0);
710         }
711
712         PrintRenderer(PrintService service, String jobName, int mode, int copies) {
713             super(null);
714             this.service = service;
715             this.jobName = jobName;
716             this.copies = copies;
717             this.mode = mode;
718             this.startNumber = 0 ;
719             this.endNumber = -1;
720             this.setScaleFactor(1);
721         }
722         */

723
724         public void stopRenderer(OutputStream outputStream) throws IOException {
725             super.stopRenderer(outputStream);
726
727             if (endNumber == -1) {
728                 endNumber = getPageCount();
729             }
730
731             Vector JavaDoc numbers = getInvalidPageNumbers();
732             for (int i = numbers.size() - 1; i > -1; i--) {
733                 removePage(Integer.parseInt((String JavaDoc) numbers.elementAt(i)));
734             }
735
736             // print job attribute
737
JobName JavaDoc printJobName = new JobName JavaDoc(jobName.substring(jobName.indexOf("#") + 1), Locale.getDefault());
738
739             PrintRequestAttributeSet JavaDoc aset = settings.getAttributeSet();
740             aset.add(printJobName);
741             if (copies > 0) {
742                 aset.add(new Copies JavaDoc(copies));
743             }
744
745             if (service != null) {
746                 log.info("Printing job [" + jobName + "] to printer - " + service.getName());
747                 DocPrintJob JavaDoc job = service.createPrintJob();
748                 job.addPrintJobListener(applet);
749
750                 DocAttributeSet JavaDoc das = new HashDocAttributeSet JavaDoc();
751                 Doc JavaDoc doc = new SimpleDoc JavaDoc(this, flavor, das);
752                 try {
753                     int copiesToPrint = 1;
754                     if (!service.isAttributeCategorySupported(Copies JavaDoc.class)) {
755                         copiesToPrint = ((Copies JavaDoc) aset.get(Copies JavaDoc.class)).getValue();
756                         aset.add(new Copies JavaDoc(1));
757                     }
758
759                     getAppletContext().showStatus("Printing...");
760                     for (int i = 0; i < copiesToPrint; i++) {
761                         System.out.println("Printing copy [" + i+1 + " of " + copiesToPrint + "]");
762                         job.print(doc, aset);
763                     }
764
765                     /*
766                     try {
767                         setJobComplete(jobName, false);
768                     } catch (Exception e) {
769                         e.printStackTrace();
770                         throw new IOException(e.getMessage());
771                     }
772                     */

773                 } catch (PrintException JavaDoc e) {
774                     log.error("Unable to print", e);
775                     throw new IOException("Unable to print: " + e.getClass().getName() + ": " + e.getMessage());
776                 }
777             }
778         }
779
780         public void renderPage(Page page) {
781             pageWidth = (int)((float) page.getWidth() / 1000f);
782             pageHeight = (int)((float) page.getHeight() / 1000f);
783             super.renderPage(page);
784         }
785
786         private Vector JavaDoc getInvalidPageNumbers() {
787             Vector JavaDoc vec = new Vector JavaDoc();
788             int max = getPageCount();
789             boolean isValid;
790             for (int i = 0; i < max; i++) {
791                 isValid = true;
792                 if (i < startNumber || i > endNumber) {
793                     isValid = false;
794                 } else if (mode != EVEN_AND_ALL) {
795                     if (mode == EVEN && ((i + 1) % 2 != 0)) {
796                         isValid = false;
797                     } else if (mode == ODD && ((i + 1) % 2 != 1)) {
798                         isValid = false;
799                     }
800                 }
801
802                 if (!isValid) {
803                     vec.add(i + "");
804                 }
805             }
806             return vec;
807         }
808     }
809
810     class PrintSettings implements Serializable {
811
812         protected transient PrintService JavaDoc service;
813         protected PrintRequestAttributeSet JavaDoc aset;
814         protected String JavaDoc printerName;
815         protected int startNumber;
816         protected int endNumber;
817         protected int copies;
818         protected int mode;
819
820         public PrintSettings(PrintService JavaDoc service, PrintRequestAttributeSet JavaDoc aset, int start, int end, int copies, int mode) {
821             this.printerName = service.getName();
822             this.service = service;
823             this.aset = aset;
824             this.startNumber = start;
825             this.endNumber = end;
826             this.copies = copies;
827             this.mode = mode;
828         }
829
830         public PrintSettings(PrintService JavaDoc service, PrintRequestAttributeSet JavaDoc aset) {
831             this(service, aset, 0, -1, 0, 0);
832         }
833
834         public synchronized PrintService JavaDoc getPrintService() {
835             if (service == null) {
836                 PrintService JavaDoc printService[] = PrintServiceLookup.lookupPrintServices(flavor, new HashPrintRequestAttributeSet JavaDoc());
837                 if (printService.length > 0) {
838                     for (int i = 0; i < printService.length; i++) {
839                         PrintService JavaDoc svc = printService[i];
840                         if (svc.getName().equals(printerName)) {
841                             service = svc;
842                         }
843                     }
844                 }
845             }
846             return service;
847         }
848
849         public String JavaDoc getPrinterName() {
850             return printerName;
851         }
852
853         public PrintRequestAttributeSet JavaDoc getAttributeSet() {
854             return aset;
855         }
856
857         public int getStartNumber() {
858             return startNumber;
859         }
860
861         public int getEndNumber() {
862             return endNumber;
863         }
864
865         public int getCopies() {
866             return copies;
867         }
868
869         public int getMode() {
870             return mode;
871         }
872     }
873
874 }
875
876
Popular Tags