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 static org.junit.Assert.fail;
22  
23  import java.io.File;
24  import java.io.IOException;
25  import java.util.HashMap;
26  import java.util.Map;
27  
28  import org.junit.Test;
29  
30  /**
31   * An example based on the tutorial where the user can can safely play with
32   * <ul>
33   *  <li>blocking or non-blocking print jobs
34   *  <li>with print job timeouts to trigger the {@code ExecuteWatchdog}
35   *  <li>with the {@code exitValue} returned from the print script
36   * </ul>
37   *
38   * @version $Id: TutorialTest.java 1636056 2014-11-01 21:12:52Z ggregory $
39   */
40  public class TutorialTest {
41  
42      /** the directory to pick up the test scripts */
43      private final File testDir = new File("src/test/scripts");
44  
45      /** simulates a PDF print job */
46      private final File acroRd32Script = TestUtil.resolveScriptForOS(testDir + "/acrord32");
47  
48      @Test
49      public void testTutorialExample() throws Exception {
50  
51          final long printJobTimeout = 15000;
52          final boolean printInBackground = false;
53          final File pdfFile = new File("/Documents and Settings/foo.pdf");
54  
55          PrintResultHandler printResult;
56  
57          try {
58              // printing takes around 10 seconds            
59              System.out.println("[main] Preparing print job ...");
60              printResult = print(pdfFile, printJobTimeout, printInBackground);
61              System.out.println("[main] Successfully sent the print job ...");
62          }
63          catch (final Exception e) {
64              e.printStackTrace();
65              fail("[main] Printing of the following document failed : " + pdfFile.getAbsolutePath());
66              throw e;
67          }
68  
69          // come back to check the print result
70          System.out.println("[main] Test is exiting but waiting for the print job to finish...");
71          printResult.waitFor();
72          System.out.println("[main] The print job has finished ...");
73      }
74  
75      /**
76       * Simulate printing a PDF document.
77       *
78       * @param file the file to print
79       * @param printJobTimeout the printJobTimeout (ms) before the watchdog terminates the print process
80       * @param printInBackground printing done in the background or blocking
81       * @return a print result handler (implementing a future)
82       * @throws IOException the test failed
83       */
84      public PrintResultHandler print(final File file, final long printJobTimeout, final boolean printInBackground)
85              throws IOException {
86  
87          int exitValue;
88          ExecuteWatchdog watchdog = null;
89          PrintResultHandler resultHandler;
90  
91          // build up the command line to using a 'java.io.File'
92          final Map<String, File> map = new HashMap<String, File>();
93          map.put("file", file);
94          final CommandLine commandLine = new CommandLine(acroRd32Script);
95          commandLine.addArgument("/p");
96          commandLine.addArgument("/h");
97          commandLine.addArgument("${file}");
98          commandLine.setSubstitutionMap(map);
99  
100         // create the executor and consider the exitValue '1' as success
101         final Executor executor = new DefaultExecutor();
102         executor.setExitValue(1);
103         
104         // create a watchdog if requested
105         if (printJobTimeout > 0) {
106             watchdog = new ExecuteWatchdog(printJobTimeout);
107             executor.setWatchdog(watchdog);
108         }
109 
110         // pass a "ExecuteResultHandler" when doing background printing
111         if (printInBackground) {
112             System.out.println("[print] Executing non-blocking print job  ...");
113             resultHandler = new PrintResultHandler(watchdog);
114             executor.execute(commandLine, resultHandler);
115         }
116         else {
117             System.out.println("[print] Executing blocking print job  ...");
118             exitValue = executor.execute(commandLine);
119             resultHandler = new PrintResultHandler(exitValue);
120         }
121 
122         return resultHandler;
123     }
124 
125     private class PrintResultHandler extends DefaultExecuteResultHandler {
126 
127         private ExecuteWatchdog watchdog;
128 
129         public PrintResultHandler(final ExecuteWatchdog watchdog)
130         {
131             this.watchdog = watchdog;
132         }
133 
134         public PrintResultHandler(final int exitValue) {
135             super.onProcessComplete(exitValue);
136         }
137         
138         @Override
139         public void onProcessComplete(final int exitValue) {
140             super.onProcessComplete(exitValue);
141             System.out.println("[resultHandler] The document was successfully printed ...");
142         }
143 
144         @Override
145         public void onProcessFailed(final ExecuteException e) {
146             super.onProcessFailed(e);
147             if (watchdog != null && watchdog.killedProcess()) {
148                 System.err.println("[resultHandler] The print process timed out");
149             }
150             else {
151                 System.err.println("[resultHandler] The print process failed to do : " + e.getMessage());
152             }
153         }
154     }
155 }