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