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  public final class CommandlineStreams implements Closeable {
35      private final ReadableByteChannel stdOutChannel;
36      private final ReadableByteChannel stdErrChannel;
37      private final WritableByteChannel stdInChannel;
38      private volatile boolean closed;
39  
40      public CommandlineStreams(@Nonnull Process process) {
41          InputStream stdOutStream = process.getInputStream();
42          stdOutChannel = newBufferedChannel(stdOutStream);
43  
44          InputStream stdErrStream = process.getErrorStream();
45          stdErrChannel = newBufferedChannel(stdErrStream);
46  
47          stdInChannel = newChannel(process.getOutputStream());
48      }
49  
50      public ReadableByteChannel getStdOutChannel() {
51          return stdOutChannel;
52      }
53  
54      public ReadableByteChannel getStdErrChannel() {
55          return stdErrChannel;
56      }
57  
58      public WritableByteChannel getStdInChannel() {
59          return stdInChannel;
60      }
61  
62      @Override
63      public void close() throws IOException {
64          if (closed) {
65              return;
66          }
67  
68          try (Channel c1 = stdOutChannel;
69                  Channel c2 = stdErrChannel;
70                  Channel c3 = stdInChannel) {
71              closed = true;
72          } catch (ClosedChannelException e) {
73              // already closed externally
74          }
75      }
76  }