View Javadoc
1   /*
2    *    Copyright 2010-2024 the original author or authors.
3    *
4    *    Licensed under the Apache License, Version 2.0 (the "License");
5    *    you may not use this file except in compliance with the License.
6    *    You may obtain a copy of the License at
7    *
8    *       https://www.apache.org/licenses/LICENSE-2.0
9    *
10   *    Unless required by applicable law or agreed to in writing, software
11   *    distributed under the License is distributed on an "AS IS" BASIS,
12   *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *    See the License for the specific language governing permissions and
14   *    limitations under the License.
15   */
16  package org.mybatis.maven.mvnmigrate.util;
17  
18  import java.io.IOException;
19  import java.io.OutputStream;
20  
21  import org.apache.maven.plugin.logging.Log;
22  
23  /**
24   * A custom {@link OutputStream}.
25   * <p>
26   * Writes all complete line (ended with \n character) to a maven logger.
27   */
28  public class MavenOutputStream extends OutputStream {
29  
30    /**
31     * The new line '\n' char constant.
32     */
33    private static final char NEW_LINE = '\n';
34  
35    /**
36     * The buffer used to maintain the line.
37     */
38    private final StringBuilder buff = new StringBuilder();
39  
40    /**
41     * The maven {@link Log}.
42     */
43    private final Log log;
44  
45    /**
46     * Creates a new instance of {@link MavenOutputStream}.
47     *
48     * @param log
49     *          the maven logger L
50     */
51    public MavenOutputStream(final Log log) {
52      this.log = log;
53    }
54  
55    @Override
56    public void write(byte[] b, int off, int len) throws IOException {
57      for (int i = off; i < len; i++) {
58        write(b[i]);
59      }
60    }
61  
62    @Override
63    public void write(byte[] b) throws IOException {
64      write(b, 0, b.length);
65    }
66  
67    @Override
68    public void write(int data) throws IOException {
69      if (NEW_LINE == data) {
70        if (this.log.isInfoEnabled()) {
71          this.log.info(buff.toString());
72        }
73        flush();
74      } else {
75        this.buff.append((char) data);
76      }
77    }
78  
79    @Override
80    public void flush() throws IOException {
81      super.flush();
82      this.buff.delete(0, this.buff.capacity());
83    }
84  
85  }