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    *      https://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  package org.apache.commons.exec;
19  
20  import static org.junit.jupiter.api.Assertions.fail;
21  
22  import java.io.File;
23  import java.io.IOException;
24  import java.nio.file.Path;
25  import java.time.Duration;
26  import java.util.HashMap;
27  import java.util.Map;
28  
29  import org.junit.jupiter.api.Test;
30  
31  /**
32   * An example based on the tutorial where the user can safely play with
33   * <ul>
34   * <li>blocking or non-blocking print jobs
35   * <li>with print job timeouts to trigger the {@code ExecuteWatchdog}
36   * <li>with the {@code exitValue} returned from the print script
37   * </ul>
38   */
39  public class TutorialTest {
40  
41      private final class PrintResultHandler extends DefaultExecuteResultHandler {
42  
43          private ExecuteWatchdog watchdog;
44  
45          public PrintResultHandler(final ExecuteWatchdog watchdog) {
46              this.watchdog = watchdog;
47          }
48  
49          public PrintResultHandler(final int exitValue) {
50              super.onProcessComplete(exitValue);
51          }
52  
53          @Override
54          public void onProcessComplete(final int exitValue) {
55              super.onProcessComplete(exitValue);
56              System.out.println("[resultHandler] The document was successfully printed ...");
57          }
58  
59          @Override
60          public void onProcessFailed(final ExecuteException e) {
61              super.onProcessFailed(e);
62              if (watchdog != null && watchdog.killedProcess()) {
63                  System.err.println("[resultHandler] The print process timed out");
64              } else {
65                  System.err.println("[resultHandler] The print process failed to do : " + e.getMessage());
66              }
67          }
68      }
69  
70      /** The directory to pick up the test scripts */
71      private final File testDir = new File("src/test/scripts");
72  
73      /** Simulates a PDF print job */
74      private final Path acroRd32Script = TestUtil.resolveScriptPathForOS(testDir + "/acrord32");
75  
76      /**
77       * Simulate printing a PDF document.
78       *
79       * @param file              the file to print
80       * @param printJobTimeout   the printJobTimeout (ms) before the watchdog terminates the print process
81       * @param printInBackground printing done in the background or blocking
82       * @return a print result handler (implementing a future)
83       * @throws IOException the test failed
84       */
85      public PrintResultHandler print(final File file, final Duration printJobTimeout, final boolean printInBackground) 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<>();
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 = DefaultExecutor.builder().get();
102         executor.setExitValue(1);
103 
104         // create a watchdog if requested
105         if (printJobTimeout.toMillis() > 0) {
106             watchdog = ExecuteWatchdog.builder().setTimeout(printJobTimeout).get();
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         } else {
116             System.out.println("[print] Executing blocking print job  ...");
117             exitValue = executor.execute(commandLine);
118             resultHandler = new PrintResultHandler(exitValue);
119         }
120 
121         return resultHandler;
122     }
123 
124     @Test
125     public void testTutorialExample() throws Exception {
126 
127         final Duration printJobTimeout = Duration.ofSeconds(15);
128         final boolean printInBackground = false;
129         final File pdfFile = new File("/Documents and Settings/foo.pdf");
130 
131         PrintResultHandler printResult;
132 
133         try {
134             // printing takes around 10 seconds
135             System.out.println("[main] Preparing print job ...");
136             printResult = print(pdfFile, printJobTimeout, printInBackground);
137             System.out.println("[main] Successfully sent the print job ...");
138         } catch (final Exception e) {
139             e.printStackTrace();
140             fail("[main] Printing of the following document failed : " + pdfFile.getAbsolutePath());
141             throw e;
142         }
143 
144         // come back to check the print result
145         System.out.println("[main] Test is exiting but waiting for the print job to finish...");
146         printResult.waitFor();
147         System.out.println("[main] The print job has finished ...");
148     }
149 }