View Javadoc

1   /* 
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    *  contributor license agreements.  See the NOTICE file distributed with
4    *  this work for additional information regarding copyright ownership.
5    *  The ASF licenses this file to You under the Apache License, Version 2.0
6    *  (the "License"); you may not use this file except in compliance with
7    *  the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   *  Unless required by applicable law or agreed to in writing, software
12   *  distributed under the License is distributed on an "AS IS" BASIS,
13   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   *  See the License for the specific language governing permissions and
15   *  limitations under the License.
16   *
17   */
18  
19  package org.apache.commons.exec;
20  
21  import junit.framework.TestCase;
22  
23  import java.io.File;
24  import java.io.IOException;
25  import java.util.HashMap;
26  import java.util.Map;
27  
28  /**
29   * An example based on the tutorial where the user can can safely play with
30   * <ul>
31   *  <li>blocking or non-blocking print jobs
32   *  <li>with print job timeouts to trigger the <code>ExecuteWatchdog</code>
33   *  <li>with the <code>exitValue</code> returned from the print script
34   * </ul>
35   */
36  public class TutorialTest extends TestCase {
37  
38      /** the directory to pick up the test scripts */
39      private File testDir = new File("src/test/scripts");
40  
41      /** simulates a PDF print job */
42      private File acroRd32Script = TestUtil.resolveScriptForOS(testDir + "/acrord32");
43  
44      public void testTutorialExample() throws Exception {
45  
46          long printJobTimeout = 15000;
47          boolean printInBackground = false;
48          File pdfFile = new File("/Documents and Settings/foo.pdf");
49  
50          PrintResultHandler printResult;
51  
52          try {
53              // printing takes around 10 seconds            
54              System.out.println("[main] Preparing print job ...");
55              printResult = print(pdfFile, printJobTimeout, printInBackground);
56              System.out.println("[main] Successfully sent the print job ...");
57          }
58          catch(Exception e) {
59              e.printStackTrace();
60              fail("[main] Printing of the following document failed : " + pdfFile.getAbsolutePath());
61              throw e;
62          }
63  
64          // come back to check the print result
65          System.out.println("[main] Test is exiting but waiting for the print job to finish...");
66          printResult.waitFor();
67          System.out.println("[main] The print job has finished ...");
68      }
69  
70      /**
71       * Simulate printing a PDF document.
72       *
73       * @param file the file to print
74       * @param printJobTimeout the printJobTimeout (ms) before the watchdog terminates the print process
75       * @param printInBackground printing done in the background or blocking
76       * @return a print result handler (implementing a future)
77       * @throws IOException the test failed
78       */
79      public PrintResultHandler print(File file, long printJobTimeout, boolean printInBackground)
80              throws IOException {
81  
82          int exitValue;
83          ExecuteWatchdog watchdog = null;
84          PrintResultHandler resultHandler;
85  
86          // build up the command line to using a 'java.io.File'
87          Map map = new HashMap();
88          map.put("file", file);
89          CommandLine commandLine = new CommandLine(acroRd32Script);
90          commandLine.addArgument("/p");
91          commandLine.addArgument("/h");
92          commandLine.addArgument("${file}");
93          commandLine.setSubstitutionMap(map);
94  
95          // create the executor and consider the exitValue '1' as success
96          Executor executor = new DefaultExecutor();
97          executor.setExitValue(1);
98          
99          // create a watchdog if requested
100         if(printJobTimeout > 0) {
101             watchdog = new ExecuteWatchdog(printJobTimeout);
102             executor.setWatchdog(watchdog);
103         }
104 
105         // pass a "ExecuteResultHandler" when doing background printing
106         if(printInBackground) {
107             System.out.println("[print] Executing non-blocking print job  ...");
108             resultHandler = new PrintResultHandler(watchdog);
109             executor.execute(commandLine, resultHandler);
110         }
111         else {
112             System.out.println("[print] Executing blocking print job  ...");
113             exitValue = executor.execute(commandLine);
114             resultHandler = new PrintResultHandler(exitValue);
115         }
116 
117         return resultHandler;
118     }
119 
120     private class PrintResultHandler extends DefaultExecuteResultHandler {
121 
122         private ExecuteWatchdog watchdog;
123 
124         public PrintResultHandler(ExecuteWatchdog watchdog)
125         {
126             this.watchdog = watchdog;
127         }
128 
129         public PrintResultHandler(int exitValue) {
130             super.onProcessComplete(exitValue);
131         }
132         
133         public void onProcessComplete(int exitValue) {
134             super.onProcessComplete(exitValue);
135             System.out.println("[resultHandler] The document was successfully printed ...");
136         }
137 
138         public void onProcessFailed(ExecuteException e){
139             super.onProcessFailed(e);
140             if(watchdog != null && watchdog.killedProcess()) {
141                 System.err.println("[resultHandler] The print process timed out");
142             }
143             else {
144                 System.err.println("[resultHandler] The print process failed to do : " + e.getMessage());
145             }
146         }
147     }
148 }