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.shared.filtering;
20  
21  import java.io.ByteArrayOutputStream;
22  import java.io.IOException;
23  import java.io.OutputStream;
24  import java.io.PrintStream;
25  
26  /**
27   * Helping class to capture console input and output for tests.
28   *
29   * @author abelsromero
30   * @since 3.3.2
31   */
32  class ConsoleHolder {
33  
34      private PrintStream originalOut;
35      private PrintStream originalErr;
36  
37      private ByteArrayOutputStream newOut;
38      private ByteArrayOutputStream newErr;
39  
40      private ConsoleHolder() {}
41  
42      static ConsoleHolder start() {
43          final ConsoleHolder holder = new ConsoleHolder();
44  
45          holder.originalOut = System.out;
46          holder.originalErr = System.err;
47  
48          holder.newOut = new DoubleOutputStream(holder.originalOut);
49          holder.newErr = new DoubleOutputStream(holder.originalErr);
50  
51          System.setOut(new PrintStream(holder.newOut));
52          System.setErr(new PrintStream(holder.newErr));
53  
54          return holder;
55      }
56  
57      void release() {
58          System.setOut(originalOut);
59          System.setOut(originalErr);
60      }
61  
62      String getOutput() {
63          return new String(newOut.toByteArray());
64      }
65  
66      String getError() {
67          return new String(newErr.toByteArray());
68      }
69  
70      static class DoubleOutputStream extends ByteArrayOutputStream {
71  
72          final OutputStream other;
73  
74          DoubleOutputStream(final OutputStream os) {
75              other = os;
76          }
77  
78          @Override
79          public synchronized void write(final byte[] b, final int off, final int len) {
80              try {
81                  other.write(b, off, len);
82              } catch (IOException e) {
83                  throw new RuntimeException(e);
84              }
85              super.write(b, off, len);
86          }
87      }
88  }