Content of file DefaultProcessExecutor.java.html
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" lang="en"><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/><link rel="stylesheet" href="../../jacoco-resources/report.css" type="text/css"/><link rel="shortcut icon" href="../../jacoco-resources/report.gif" type="image/gif"/><title>DefaultProcessExecutor.java</title><link rel="stylesheet" href="../../jacoco-resources/prettify.css" type="text/css"/><script type="text/javascript" src="../../jacoco-resources/prettify.js"></script></head><body onload="window['PR_TAB_WIDTH']=4;prettyPrint()"><div class="breadcrumb" id="breadcrumb"><span class="info"><a href="../../jacoco-sessions.html" class="el_session">Sessions</a></span><a href="../../index.html" class="el_report">NorthernWind :: Filesystems :: SCM :: Git</a> > <a href="../index.html" class="el_bundle">it-tidalwave-northernwind-core-filesystem-scm</a> > <a href="index.source.html" class="el_package">it.tidalwave.util.impl</a> > <span class="el_source">DefaultProcessExecutor.java</span></div><h1>DefaultProcessExecutor.java</h1><pre class="source lang-java linenums">/*
* #%L
* *********************************************************************************************************************
*
* NorthernWind - lightweight CMS
* http://northernwind.tidalwave.it - git clone https://bitbucket.org/tidalwave/northernwind-src.git
* %%
* Copyright (C) 2011 - 2023 Tidalwave s.a.s. (http://tidalwave.it)
* %%
* *********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* *********************************************************************************************************************
*
*
* *********************************************************************************************************************
* #L%
*/
package it.tidalwave.util.impl;
import javax.annotation.Nonnull;
import javax.annotation.concurrent.NotThreadSafe;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.Executors;
import java.util.regex.Pattern;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.file.Path;
import it.tidalwave.util.ProcessExecutor;
import it.tidalwave.util.ProcessExecutorException;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/***********************************************************************************************************************
*
* A helper class for launching an external process and handling its output.
*
* @author Fabrizio Giudici
*
**********************************************************************************************************************/
<span class="fc" id="L58">@NotThreadSafe @Slf4j</span>
public final class DefaultProcessExecutor implements ProcessExecutor
{
private static final String PROCESS_EXITED_WITH = "Process exited with ";
/*******************************************************************************************************************
*
******************************************************************************************************************/
<span class="fc" id="L66"> @RequiredArgsConstructor(access = AccessLevel.PACKAGE)</span>
public class DefaultConsoleOutput implements ConsoleOutput
{
@Nonnull
private final String name;
@Nonnull
private final InputStream input;
<span class="fc" id="L75"> @Getter</span>
<span class="fc" id="L76"> private final List<String> content = Collections.synchronizedList(new ArrayList<>());</span>
private volatile boolean completed;
/** The consumer for output. */
<span class="fc" id="L81"> private final Runnable consoleConsumer = () -></span>
{
try
{
<span class="fc" id="L85"> read();</span>
}
<span class="nc" id="L87"> catch (IOException e)</span>
{
<span class="nc" id="L89"> log.warn("while reading from process console", e);</span>
<span class="fc" id="L90"> }</span>
<span class="fc" id="L92"> synchronized (DefaultConsoleOutput.this)</span>
{
<span class="fc" id="L94"> completed = true;</span>
<span class="fc" id="L95"> DefaultConsoleOutput.this.notifyAll();</span>
<span class="fc" id="L96"> }</span>
<span class="fc" id="L97"> };</span>
/***************************************************************************************************************
*
* {@inheritDoc}
*
**************************************************************************************************************/
@Override @Nonnull
public ConsoleOutput start()
{
<span class="fc" id="L107"> Executors.newSingleThreadExecutor().submit(consoleConsumer);</span>
<span class="fc" id="L108"> return this;</span>
}
/***************************************************************************************************************
*
* {@inheritDoc}
*
**************************************************************************************************************/
@Override @Nonnull
public synchronized ConsoleOutput waitForCompleted ()
throws InterruptedException
{
<span class="fc bfc" id="L120" title="All 2 branches covered."> while (!completed)</span>
{
<span class="fc" id="L122"> wait();</span>
}
<span class="fc" id="L125"> return this;</span>
}
/***************************************************************************************************************
*
* {@inheritDoc}
*
**************************************************************************************************************/
@Override @Nonnull @SuppressWarnings({"squid:S2095", "IOResourceOpenedButNotSafelyClosed"})
public Scanner filteredAndSplitBy (@Nonnull final String filterRegexp, @Nonnull final String delimiterRegexp)
{
<span class="nc" id="L136"> return new Scanner(filteredBy(filterRegexp).get(0)).useDelimiter(Pattern.compile(delimiterRegexp));</span>
}
/***************************************************************************************************************
*
* {@inheritDoc}
*
**************************************************************************************************************/
@Override @Nonnull
public List<String> filteredBy (@Nonnull final String filterRegexp)
{
<span class="fc" id="L147"> final var p = Pattern.compile(filterRegexp);</span>
<span class="fc" id="L148"> final List<String> result = new ArrayList<>();</span>
<span class="fc bfc" id="L150" title="All 2 branches covered."> for (final var s : new ArrayList<>(content))</span>
{
<span class="fc" id="L152"> final var m = p.matcher(s);</span>
<span class="pc bpc" id="L154" title="1 of 2 branches missed."> if (m.matches())</span>
{
<span class="fc" id="L156"> result.add(m.group(1));</span>
}
<span class="fc" id="L158"> }</span>
<span class="fc" id="L160"> return result;</span>
}
/***************************************************************************************************************
*
* {@inheritDoc}
*
**************************************************************************************************************/
@Override @Nonnull
public ConsoleOutput waitFor (@Nonnull final String regexp)
throws InterruptedException, IOException
{
<span class="nc" id="L172"> log.debug("waitFor({})", regexp);</span>
<span class="nc bnc" id="L174" title="All 2 branches missed."> while (filteredBy(regexp).isEmpty())</span>
{
try
{
<span class="nc" id="L178"> final var exitValue = process.exitValue();</span>
<span class="nc" id="L179"> throw new IOException(PROCESS_EXITED_WITH + exitValue);</span>
}
<span class="nc" id="L181"> catch (IllegalThreadStateException e) // ok, process not terminated yet</span>
{
<span class="nc" id="L183"> synchronized (this)</span>
{
<span class="nc" id="L185"> wait(50); // FIXME: polls because it doesn't get notified</span>
| polls because it doesn't get notified | |
<span class="nc" id="L186"> }</span>
<span class="nc" id="L187"> }</span>
}
<span class="nc" id="L190"> return this;</span>
}
/***************************************************************************************************************
*
* {@inheritDoc}
*
**************************************************************************************************************/
@Override
public void clear()
{
<span class="nc" id="L201"> content.clear();</span>
<span class="nc" id="L202"> }</span>
/***************************************************************************************************************
*
* {@inheritDoc}
*
**************************************************************************************************************/
@Override
public void read()
throws IOException
{
<span class="fc" id="L213"> try (final var br = new BufferedReader(new InputStreamReader(input)))</span>
{
for (; ; )
{
<span class="fc" id="L217"> final var s = br.readLine();</span>
<span class="fc bfc" id="L219" title="All 2 branches covered."> if (s == null)</span>
{
<span class="fc" id="L221"> break;</span>
}
<span class="fc" id="L224"> log.trace(">>>>>>>> {}: {}", name, s);</span>
<span class="fc" id="L225"> content.add(s);</span>
<span class="fc" id="L227"> synchronized (this)</span>
{
<span class="fc" id="L229"> notifyAll();</span>
<span class="fc" id="L230"> }</span>
<span class="fc" id="L231"> }</span>
}
<span class="fc" id="L233"> }</span>
}
/** The arguments to pass to the external process. */
<span class="fc" id="L237"> private final List<String> arguments = new ArrayList<>();</span>
/** The working directory for the external process. */
<span class="fc" id="L240"> private Path workingDirectory = new File(".").toPath();</span>
/** The external process. */
private Process process;
/** The processor of stdout. */
<span class="fc" id="L246"> @Getter</span>
private ConsoleOutput stdout;
/** The processor of stderr. */
<span class="nc" id="L250"> @Getter</span>
private ConsoleOutput stderr;
/** The writer to feed the process' stdin. */
private PrintWriter stdin;
/*******************************************************************************************************************
*
******************************************************************************************************************/
public DefaultProcessExecutor (@Nonnull final String executable)
throws IOException
<span class="fc" id="L261"> {</span>
<span class="fc" id="L262"> arguments.add(DefaultProcessExecutor.findPathFor(executable));</span>
<span class="fc" id="L263"> }</span>
/*******************************************************************************************************************
*
* {@inheritDoc}
*
******************************************************************************************************************/
@Override @Nonnull
public ProcessExecutor withArgument (@Nonnull final String argument)
{
<span class="nc" id="L273"> arguments.add(argument);</span>
<span class="nc" id="L274"> return this;</span>
}
/*******************************************************************************************************************
*
* {@inheritDoc}
*
******************************************************************************************************************/
@Override @Nonnull
public ProcessExecutor withArguments (@Nonnull final String... arguments)
{
<span class="fc" id="L285"> this.arguments.addAll(List.of(arguments));</span>
<span class="fc" id="L286"> return this;</span>
}
/*******************************************************************************************************************
*
* {@inheritDoc}
*
******************************************************************************************************************/
@Override @Nonnull
public ProcessExecutor withWorkingDirectory (@Nonnull final Path workingDirectory)
{
<span class="fc" id="L297"> this.workingDirectory = workingDirectory;</span>
<span class="fc" id="L298"> return this;</span>
}
/*******************************************************************************************************************
*
* {@inheritDoc}
*
******************************************************************************************************************/
@Override @Nonnull
public ProcessExecutor start()
throws IOException
{
<span class="fc" id="L310"> log.debug(">>>> executing: {}", String.join(" ", arguments));</span>
<span class="fc" id="L312"> final List<String> environment = new ArrayList<>();</span>
// for (final Entry<String, String> e : System.getenv().entrySet())
// {
// environment.add(String.format("%s=%s", e.getKey(), e.getValue()));
// }
<span class="fc" id="L319"> log.debug(">>>> working directory: {}", workingDirectory.toFile().getCanonicalPath());</span>
<span class="fc" id="L320"> log.debug(">>>> environment: {}", environment);</span>
<span class="fc" id="L321"> process = Runtime.getRuntime().exec(arguments.toArray(new String[0]),</span>
<span class="fc" id="L322"> environment.toArray(new String[0]),</span>
<span class="fc" id="L323"> workingDirectory.toFile());</span>
<span class="fc" id="L325"> stdout = new DefaultConsoleOutput("STDOUT", process.getInputStream()).start();</span>
<span class="fc" id="L326"> stderr = new DefaultConsoleOutput("STDERR", process.getErrorStream()).start();</span>
<span class="fc" id="L327"> stdin = new PrintWriter(process.getOutputStream(), true);</span>
<span class="fc" id="L329"> return this;</span>
}
/*******************************************************************************************************************
*
* {@inheritDoc}
*
******************************************************************************************************************/
@Override @Nonnull
public ProcessExecutor waitForCompletion()
throws IOException, InterruptedException
{
<span class="fc bfc" id="L341" title="All 2 branches covered."> if (process.waitFor() != 0)</span>
{
<span class="fc" id="L343"> final List<String> environment = new ArrayList<>();</span>
<span class="fc bfc" id="L345" title="All 2 branches covered."> for (final var e : System.getenv().entrySet())</span>
{
<span class="fc" id="L347"> environment.add(String.format("%s=%s, ", e.getKey(), e.getValue()));</span>
<span class="fc" id="L348"> }</span>
<span class="fc" id="L350"> log.warn(PROCESS_EXITED_WITH + process.exitValue());</span>
<span class="fc" id="L351"> log.debug(">>>> executed: {}", arguments);</span>
<span class="fc" id="L352"> log.debug(">>>> working directory: {}", workingDirectory.toFile().getCanonicalPath());</span>
<span class="fc" id="L353"> log.debug(">>>> environment: {}", environment);</span>
// log("STDOUT", stdout);
// log("STDERR", stderr);
<span class="fc" id="L356"> throw new ProcessExecutorException(PROCESS_EXITED_WITH + process.exitValue(),</span>
<span class="fc" id="L357"> process.exitValue(),</span>
<span class="fc" id="L358"> stdout.waitForCompleted().getContent(),</span>
<span class="fc" id="L359"> stderr.waitForCompleted().getContent());</span>
}
<span class="fc" id="L362"> return this;</span>
}
/*******************************************************************************************************************
*
* {@inheritDoc}
*
******************************************************************************************************************/
@Override @Nonnull
public ProcessExecutor send (@Nonnull final String string)
{
<span class="nc" id="L373"> log.info(">>>> sending '{}'...", string);</span>
<span class="nc" id="L374"> stdin.println(string);</span>
<span class="nc" id="L375"> return this;</span>
}
/*******************************************************************************************************************
*
* Scans the {@code PATH} for finding the absolute path of the given executable.
*
* @param executable the executable to search for
* @return the absolute path
* @throws IOException if the executable can't be found
*
******************************************************************************************************************/
@Nonnull
private static String findPathFor (@Nonnull final String executable)
throws IOException
{
<span class="fc" id="L391"> final var pathEnv = System.getenv("PATH") + File.pathSeparator + "/usr/local/bin";</span>
<span class="pc bpc" id="L393" title="1 of 2 branches missed."> for (final var path : pathEnv.split(File.pathSeparator))</span>
{
<span class="fc" id="L395"> final var file = new File(new File(path), executable);</span>
<span class="fc bfc" id="L397" title="All 2 branches covered."> if (file.canExecute())</span>
{
<span class="fc" id="L399"> return file.getAbsolutePath();</span>
}
}
<span class="nc" id="L403"> throw new IOException("Can't find " + executable + " in PATH");</span>
}
/*******************************************************************************************************************
*
* Logs a whole console output.
*
* @param prefix a log prefix
* @param consoleOutput the output
*
******************************************************************************************************************/
private static void log (@Nonnull final String prefix, @Nonnull final DefaultConsoleOutput consoleOutput)
{
<span class="nc bnc" id="L416" title="All 2 branches missed."> for (final var line : consoleOutput.getContent())</span>
{
<span class="nc" id="L418"> log.error("{}: {}", prefix, line);</span>
<span class="nc" id="L419"> }</span>
<span class="nc" id="L420"> }</span>
}
</pre><div class="footer"><span class="right">Created with <a href="http://www.jacoco.org/jacoco">JaCoCo</a> 0.8.9.202303310957</span></div></body></html>