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.invoker;
20  
21  import java.io.PrintStream;
22  
23  /**
24   * Offers an output handler that writes to a print stream like {@link java.lang.System#out}.
25   *
26   * @since 2.0.9
27   */
28  public class PrintStreamHandler implements InvocationOutputHandler {
29  
30      /**
31       * The print stream to write to, never <code>null</code>.
32       */
33      private PrintStream out;
34  
35      /**
36       * A flag whether the print stream should be flushed after each line.
37       */
38      private boolean alwaysFlush;
39  
40      /**
41       * Creates a new output handler that writes to {@link java.lang.System#out}.
42       */
43      public PrintStreamHandler() {
44          this(System.out, false);
45      }
46  
47      /**
48       * Creates a new output handler that writes to the specified print stream.
49       *
50       * @param out The print stream to write to, must not be <code>null</code>.
51       * @param alwaysFlush A flag whether the print stream should be flushed after each line.
52       */
53      public PrintStreamHandler(PrintStream out, boolean alwaysFlush) {
54          if (out == null) {
55              throw new NullPointerException("missing output stream");
56          }
57          this.out = out;
58          this.alwaysFlush = alwaysFlush;
59      }
60  
61      /** {@inheritDoc} */
62      public void consumeLine(String line) {
63          if (line == null) {
64              out.println();
65          } else {
66              out.println(line);
67          }
68  
69          if (alwaysFlush) {
70              out.flush();
71          }
72      }
73  }