1 /*
   2  * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 import java.io.File;
  26 import java.io.FileReader;
  27 import java.io.FileWriter;
  28 import java.io.IOException;
  29 import java.io.InputStream;
  30 import java.io.OutputStream;
  31 import java.io.Reader;
  32 import java.io.Writer;
  33 import java.util.Arrays;
  34 import java.util.List;
  35 
  36 /*
  37  * @test PipelineTest
  38  */
  39 
  40 public class PipelineTest {
  41 
  42     private static void realMain(String[] args) throws Throwable {
  43         t1_simplePipeline();
  44         t2_translatePipeline();
  45         t3_redirectErrorStream();
  46         t4_failStartPipeline();
  47     }
  48 
  49     /**
  50      * Return a list of the varargs arguments.
  51      * @param args elements to include in the list
  52      * @param <T> the type of the elements
  53      * @return a {@code List<T>} of the arguments
  54      */
  55     @SafeVarargs
  56     @SuppressWarnings("varargs")
  57     static <T> List<T> asList(T... args) {
  58         return Arrays.asList(args);
  59     }
  60 
  61     /**
  62      * T1 - simple copy between two processes
  63      */
  64     static void t1_simplePipeline() {
  65         try {
  66             String s1 = "Now is the time to check!";
  67             verify(s1, s1,
  68                     asList(new ProcessBuilder("cat")));
  69             verify(s1, s1,
  70                     asList(new ProcessBuilder("cat"),
  71                             new ProcessBuilder("cat")));
  72             verify(s1, s1,
  73                     asList(new ProcessBuilder("cat"),
  74                             new ProcessBuilder("cat"),
  75                             new ProcessBuilder("cat")));
  76         } catch (Throwable t) {
  77             unexpected(t);
  78         }
  79     }
  80 
  81     /**
  82      * Pipeline that modifies the content.
  83      */
  84     static void t2_translatePipeline() {
  85         try {
  86             String s2 = "Now is the time to check!";
  87             String r2 = s2.replace('e', 'E').replace('o', 'O');
  88             verify(s2, r2,
  89                     asList(new ProcessBuilder("tr", "e", "E"),
  90                             new ProcessBuilder("tr", "o", "O")));
  91         } catch (Throwable t) {
  92             unexpected(t);
  93         }
  94     }
  95 
  96     /**
  97      * Test that redirectErrorStream sends standard error of the first process
  98      * to the standard output. The standard error of the first process should be empty.
  99      * The standard output of the 2nd should contain the error message including the bad file name.
 100      */
 101     static void t3_redirectErrorStream() {
 102         try {
 103             File p1err = new File("p1-test.err");
 104             File p2out = new File("p2-test.out");
 105 
 106             List<Process> processes = ProcessBuilder.startPipeline(
 107                     asList(new ProcessBuilder("cat", "NON-EXISTENT-FILE")
 108                                     .redirectErrorStream(true)
 109                                     .redirectError(p1err),
 110                             new ProcessBuilder("cat").redirectOutput(p2out)));
 111             waitForAll(processes);
 112 
 113             check("".equals(fileContents(p1err)), "The first process standard error should be empty");
 114             String p2contents = fileContents(p2out);
 115             check(p2contents.contains("NON-EXISTENT-FILE"),
 116                     "The error from the first process should be in the output of the second: " + p2contents);
 117         } catch (Throwable t) {
 118             unexpected(t);
 119         }
 120     }
 121 
 122     /**
 123      * Test that no processes are left after a failed startPipeline.
 124      * Test illegal combinations of redirects.
 125      */
 126     static void t4_failStartPipeline() {
 127         File p1err = new File("p1-test.err");
 128         File p2out = new File("p2-test.out");
 129 
 130         THROWS(IllegalArgumentException.class,
 131                 () -> {
 132                     // Test that output redirect != PIPE throws IAE
 133                     List<Process> processes = ProcessBuilder.startPipeline(
 134                             asList(new ProcessBuilder("cat", "NON-EXISTENT-FILE1")
 135                                             .redirectOutput(p1err),
 136                                     new ProcessBuilder("cat")));
 137                 },
 138                 () -> {
 139                     // Test that input redirect != PIPE throws IAE
 140                     List<Process> processes = ProcessBuilder.startPipeline(
 141                             asList(new ProcessBuilder("cat", "NON-EXISTENT-FILE2"),
 142                                     new ProcessBuilder("cat").redirectInput(p2out)));
 143                 }
 144         );
 145 
 146         THROWS(NullPointerException.class,
 147                 () -> {
 148                     List<Process> processes = ProcessBuilder.startPipeline(
 149                             asList(new ProcessBuilder("cat", "a"), null));
 150                 },
 151                 () -> {
 152                     List<Process> processes = ProcessBuilder.startPipeline(
 153                             asList(null, new ProcessBuilder("cat", "b")));
 154                 }
 155         );
 156 
 157         THROWS(IOException.class,
 158                 () -> {
 159                     List<Process> processes = ProcessBuilder.startPipeline(
 160                             asList(new ProcessBuilder("cat", "c"),
 161                                     new ProcessBuilder("NON-EXISTENT-COMMAND")));
 162                 });
 163 
 164         // Check no subprocess are left behind
 165         ProcessHandle.current().children().forEach(PipelineTest::print);
 166         ProcessHandle.current().children()
 167                 .filter(p -> p.info().command().orElse("").contains("cat"))
 168                 .forEach(p -> fail("process should have been destroyed: " + p));
 169     }
 170 
 171     static void verify(String input, String expected, List<ProcessBuilder> builders) throws IOException {
 172         File infile = new File("test.in");
 173         File outfile = new File("test.out");
 174         setFileContents(infile, expected);
 175         for (int i = 0; i < builders.size(); i++) {
 176             ProcessBuilder b = builders.get(i);
 177             if (i == 0) {
 178                 b.redirectInput(infile);
 179             }
 180             if (i == builders.size() - 1) {
 181                 b.redirectOutput(outfile);
 182             }
 183         }
 184         List<Process> processes = ProcessBuilder.startPipeline(builders);
 185         verifyProcesses(processes);
 186         waitForAll(processes);
 187         String result = fileContents(outfile);
 188         System.out.printf(" in: %s%nout: %s%n", input, expected);
 189         check(result.equals(expected), "result not as expected");
 190     }
 191 
 192     /**
 193      * Wait for each of the processes to be done.
 194      *
 195      * @param processes the list  of processes to check
 196      */
 197     static void waitForAll(List<Process> processes) {
 198         processes.forEach(p -> {
 199             try {
 200                 int status = p.waitFor();
 201             } catch (InterruptedException ie) {
 202                 unexpected(ie);
 203             }
 204         });
 205     }
 206 
 207     static void print(ProcessBuilder pb) {
 208         if (pb != null) {
 209             System.out.printf(" pb: %s%n", pb);
 210             System.out.printf("    cmd: %s%n", pb.command());
 211         }
 212     }
 213 
 214     static void print(ProcessHandle p) {
 215         System.out.printf("process: pid: %d, info: %s%n",
 216                 p.getPid(), p.info());
 217     }
 218 
 219     // Check various aspects of the processes
 220     static void verifyProcesses(List<Process> processes) {
 221         for (int i = 0; i < processes.size(); i++) {
 222             Process p = processes.get(i);
 223             if (i != 0) {
 224                 verifyNullStream(p.getOutputStream(), "getOutputStream");
 225             }
 226             if (i == processes.size() - 1) {
 227                 verifyNullStream(p.getInputStream(), "getInputStream");
 228                 verifyNullStream(p.getErrorStream(), "getErrorStream");
 229             }
 230         }
 231     }
 232 
 233     static void verifyNullStream(OutputStream s, String msg) {
 234         try {
 235             s.write(0xff);
 236             fail("Stream should have been a NullStream" + msg);
 237         } catch (IOException ie) {
 238             // expected
 239         }
 240     }
 241 
 242     static void verifyNullStream(InputStream s, String msg) {
 243         try {
 244             int len = s.read();
 245             check(len == -1, "Stream should have been a NullStream" + msg);
 246         } catch (IOException ie) {
 247             // expected
 248         }
 249     }
 250 
 251     static void setFileContents(File file, String contents) {
 252         try {
 253             Writer w = new FileWriter(file);
 254             w.write(contents);
 255             w.close();
 256         } catch (Throwable t) { unexpected(t); }
 257     }
 258 
 259     static String fileContents(File file) {
 260         try {
 261             Reader r = new FileReader(file);
 262             StringBuilder sb = new StringBuilder();
 263             char[] buffer = new char[1024];
 264             int n;
 265             while ((n = r.read(buffer)) != -1)
 266                 sb.append(buffer,0,n);
 267             r.close();
 268             return new String(sb);
 269         } catch (Throwable t) { unexpected(t); return ""; }
 270     }
 271 
 272     //--------------------- Infrastructure ---------------------------
 273     static volatile int passed = 0, failed = 0;
 274     static void pass() {passed++;}
 275     static void fail() {failed++; Thread.dumpStack();}
 276     static void fail(String msg) {System.err.println(msg); fail();}
 277     static void unexpected(Throwable t) {failed++; t.printStackTrace();}
 278     static void check(boolean cond) {if (cond) pass(); else fail();}
 279     static void check(boolean cond, String m) {if (cond) pass(); else fail(m);}
 280     static void equal(Object x, Object y) {
 281         if (x == null ? y == null : x.equals(y)) pass();
 282         else fail(">'" + x + "'<" + " not equal to " + "'" + y + "'");
 283     }
 284 
 285     public static void main(String[] args) throws Throwable {
 286         try {realMain(args);} catch (Throwable t) {unexpected(t);}
 287         System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
 288         if (failed > 0) throw new AssertionError("Some tests failed");
 289     }
 290     interface Fun {void f() throws Throwable;}
 291     static void THROWS(Class<? extends Throwable> k, Fun... fs) {
 292         for (Fun f : fs)
 293             try { f.f(); fail("Expected " + k.getName() + " not thrown"); }
 294             catch (Throwable t) {
 295                 if (k.isAssignableFrom(t.getClass())) pass();
 296                 else unexpected(t);}
 297     }
 298 
 299 }