View Javadoc
1   /*
2    * Licensed under the Apache License, Version 2.0 (the "License");
3    * you may not use this file except in compliance with the License.
4    * You may obtain a copy of the License at
5    *
6    * http://www.apache.org/licenses/LICENSE-2.0
7    *
8    * Unless required by applicable law or agreed to in writing, software
9    * distributed under the License is distributed on an "AS IS" BASIS,
10   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11   * See the License for the specific language governing permissions and
12   * limitations under the License.
13   */
14  package de.softwareforge.testing.postgres.embedded;
15  
16  import java.io.BufferedReader;
17  import java.io.IOException;
18  import java.io.InputStreamReader;
19  import java.io.UncheckedIOException;
20  import java.nio.charset.StandardCharsets;
21  
22  import org.slf4j.Logger;
23  
24  /**
25   * Read standard output of process and write lines to given {@link Logger} as INFO; depends on {@link ProcessBuilder#redirectErrorStream(boolean)} being set to
26   * {@code true} (since only stdout is read).
27   *
28   * <p>
29   * The use of the input stream is thread safe since it's used only in a single thread&mdash;the one launched by this code.
30   */
31  final class ProcessOutputLogger implements Runnable {
32  
33      private final Logger logger;
34      private final BufferedReader reader;
35  
36      private ProcessOutputLogger(final Logger logger, final Process process) {
37          this.logger = logger;
38          this.reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));
39      }
40  
41      @Override
42      public void run() {
43          try {
44              try {
45                  reader.lines().forEach(logger::debug);
46              } catch (final UncheckedIOException e) {
47                  logger.error("while reading output:", e);
48              }
49          } finally {
50              try {
51                  reader.close();
52              } catch (final IOException e) {
53                  logger.trace("while closing reader:", e);
54              }
55          }
56      }
57  
58      static void logOutput(final Logger logger, final String name, final Process process) {
59          final Thread t = new Thread(new ProcessOutputLogger(logger, process));
60          t.setName(name);
61          t.setDaemon(true);
62          t.start();
63      }
64  }