MavenOutputStream.java

  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. import java.io.IOException;
  18. import java.io.OutputStream;

  19. import org.apache.maven.plugin.logging.Log;

  20. /**
  21.  * A custom {@link OutputStream}.
  22.  * <p>
  23.  * Writes all complete line (ended with \n character) to a maven logger.
  24.  */
  25. public class MavenOutputStream extends OutputStream {

  26.   /**
  27.    * The new line '\n' char constant.
  28.    */
  29.   private static final char NEW_LINE = '\n';

  30.   /**
  31.    * The buffer used to maintain the line.
  32.    */
  33.   private final StringBuilder buff = new StringBuilder();

  34.   /**
  35.    * The maven {@link Log}.
  36.    */
  37.   private final Log log;

  38.   /**
  39.    * Creates a new instance of {@link MavenOutputStream}.
  40.    *
  41.    * @param log
  42.    *          the maven logger L
  43.    */
  44.   public MavenOutputStream(final Log log) {
  45.     this.log = log;
  46.   }

  47.   @Override
  48.   public void write(byte[] b, int off, int len) throws IOException {
  49.     for (int i = off; i < len; i++) {
  50.       write(b[i]);
  51.     }
  52.   }

  53.   @Override
  54.   public void write(byte[] b) throws IOException {
  55.     write(b, 0, b.length);
  56.   }

  57.   @Override
  58.   public void write(int data) throws IOException {
  59.     if (NEW_LINE == data) {
  60.       if (this.log.isInfoEnabled()) {
  61.         this.log.info(buff.toString());
  62.       }
  63.       flush();
  64.     } else {
  65.       this.buff.append((char) data);
  66.     }
  67.   }

  68.   @Override
  69.   public void flush() throws IOException {
  70.     super.flush();
  71.     this.buff.delete(0, this.buff.capacity());
  72.   }

  73. }