View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.maven.surefire.extensions.util;
20  
21  import javax.annotation.Nonnull;
22  
23  import java.io.Closeable;
24  import java.io.IOException;
25  import java.io.InputStream;
26  import java.nio.channels.Channel;
27  import java.nio.channels.ClosedChannelException;
28  import java.nio.channels.ReadableByteChannel;
29  import java.nio.channels.WritableByteChannel;
30  
31  import static org.apache.maven.surefire.api.util.internal.Channels.newBufferedChannel;
32  import static org.apache.maven.surefire.api.util.internal.Channels.newChannel;
33  
34  /**
35   *
36   */
37  public final class CommandlineStreams implements Closeable {
38      private final ReadableByteChannel stdOutChannel;
39      private final ReadableByteChannel stdErrChannel;
40      private final WritableByteChannel stdInChannel;
41      private volatile boolean closed;
42  
43      public CommandlineStreams(@Nonnull Process process) {
44          InputStream stdOutStream = process.getInputStream();
45          stdOutChannel = newBufferedChannel(stdOutStream);
46  
47          InputStream stdErrStream = process.getErrorStream();
48          stdErrChannel = newBufferedChannel(stdErrStream);
49  
50          stdInChannel = newChannel(process.getOutputStream());
51      }
52  
53      public ReadableByteChannel getStdOutChannel() {
54          return stdOutChannel;
55      }
56  
57      public ReadableByteChannel getStdErrChannel() {
58          return stdErrChannel;
59      }
60  
61      public WritableByteChannel getStdInChannel() {
62          return stdInChannel;
63      }
64  
65      @Override
66      public void close() throws IOException {
67          if (closed) {
68              return;
69          }
70  
71          try (Channel c1 = stdOutChannel;
72                  Channel c2 = stdErrChannel;
73                  Channel c3 = stdInChannel) {
74              closed = true;
75          } catch (ClosedChannelException e) {
76              // already closed externally
77          }
78      }
79  }