Skip to content

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</a> &gt; <a href="index.source.html" class="el_package">it.tidalwave.util.impl</a> &gt; <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 &quot;License&quot;); 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 &quot;AS IS&quot; 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.Map.Entry;
import java.util.Scanner;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
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.ProcessExecutorException;
import it.tidalwave.util.ProcessExecutor;
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="nc" id="L60">@NotThreadSafe @Slf4j</span>
public final class DefaultProcessExecutor implements ProcessExecutor
  {
    private static final String PROCESS_EXITED_WITH = &quot;Process exited with &quot;;

    /*******************************************************************************************************************
     *
     ******************************************************************************************************************/
<span class="nc" id="L68">    @RequiredArgsConstructor(access = AccessLevel.PACKAGE)</span>
    public class DefaultConsoleOutput implements ConsoleOutput
      {
        @Nonnull
        private final String name;

        @Nonnull
        private final InputStream input;

<span class="nc" id="L77">        @Getter</span>
<span class="nc" id="L78">        private final List&lt;String&gt; content = Collections.synchronizedList(new ArrayList&lt;&gt;());</span>

        private volatile boolean completed;

        /** The consumer for output. */
<span class="nc" id="L83">        private final Runnable consoleConsumer = () -&gt;</span>
          {
            try
              {
<span class="nc" id="L87">                read();</span>
              }
<span class="nc" id="L89">            catch (IOException e)</span>
              {
<span class="nc" id="L91">                log.warn(&quot;while reading from process console&quot;, e);</span>
<span class="nc" id="L92">              }</span>

<span class="nc" id="L94">            synchronized (DefaultConsoleOutput.this)</span>
              {
<span class="nc" id="L96">                completed = true;</span>
<span class="nc" id="L97">                DefaultConsoleOutput.this.notifyAll();</span>
<span class="nc" id="L98">              }</span>
<span class="nc" id="L99">          };</span>

        /***************************************************************************************************************
         *
         * {@inheritDoc}
         *
         **************************************************************************************************************/
        @Override @Nonnull
        public ConsoleOutput start()
          {
<span class="nc" id="L109">            Executors.newSingleThreadExecutor().submit(consoleConsumer);</span>
<span class="nc" id="L110">            return this;</span>
          }

        /***************************************************************************************************************
         *
         * {@inheritDoc}
         *
         **************************************************************************************************************/
        @Override @Nonnull
        public synchronized ConsoleOutput waitForCompleted ()
                throws InterruptedException
          {
<span class="nc bnc" id="L122" title="All 2 branches missed.">            while (!completed)</span>
              {
<span class="nc" id="L124">                wait();</span>
              }

<span class="nc" id="L127">            return this;</span>
          }

        /***************************************************************************************************************
         *
         * {@inheritDoc}
         *
         **************************************************************************************************************/
        @Override @Nonnull @SuppressWarnings({&quot;squid:S2095&quot;, &quot;IOResourceOpenedButNotSafelyClosed&quot;})
        public Scanner filteredAndSplitBy (@Nonnull final String filterRegexp, @Nonnull final String delimiterRegexp)
          {
<span class="nc" id="L138">            return new Scanner(filteredBy(filterRegexp).get(0)).useDelimiter(Pattern.compile(delimiterRegexp));</span>
          }

        /***************************************************************************************************************
         *
         * {@inheritDoc}
         *
         **************************************************************************************************************/
        @Override @Nonnull
        public List&lt;String&gt; filteredBy (@Nonnull final String filterRegexp)
          {
<span class="nc" id="L149">            final Pattern p = Pattern.compile(filterRegexp);</span>
<span class="nc" id="L150">            final List&lt;String&gt; result = new ArrayList&lt;&gt;();</span>

<span class="nc bnc" id="L152" title="All 2 branches missed.">            for (final String s : new ArrayList&lt;&gt;(content))</span>
              {
<span class="nc" id="L154">                final Matcher m = p.matcher(s);</span>

<span class="nc bnc" id="L156" title="All 2 branches missed.">                if (m.matches())</span>
                  {
<span class="nc" id="L158">                    result.add(m.group(1));</span>
                  }
<span class="nc" id="L160">              }</span>

<span class="nc" id="L162">            return result;</span>
          }

        /***************************************************************************************************************
         *
         * {@inheritDoc}
         *
         **************************************************************************************************************/
        @Override @Nonnull
        public ConsoleOutput waitFor (@Nonnull final String regexp)
                throws InterruptedException, IOException
          {
<span class="nc" id="L174">            log.debug(&quot;waitFor({})&quot;, regexp);</span>

<span class="nc bnc" id="L176" title="All 2 branches missed.">            while (filteredBy(regexp).isEmpty())</span>
              {
                try
                  {
<span class="nc" id="L180">                    final int exitValue = process.exitValue();</span>
<span class="nc" id="L181">                    throw new IOException(PROCESS_EXITED_WITH + exitValue);</span>
                  }
<span class="nc" id="L183">                catch (IllegalThreadStateException e) // ok, process not terminated yet</span>
                  {
<span class="nc" id="L185">                    synchronized (this)</span>
                      {
<span class="nc" id="L187">                        wait(50); // FIXME: polls because it doesn't get notified</span>
polls because it doesn't get notified
<span class="nc" id="L188"> }</span> <span class="nc" id="L189"> }</span> } <span class="nc" id="L192"> return this;</span> } /*************************************************************************************************************** * * {@inheritDoc} * **************************************************************************************************************/ @Override public void clear() { <span class="nc" id="L203"> content.clear();</span> <span class="nc" id="L204"> }</span> /*************************************************************************************************************** * * {@inheritDoc} * **************************************************************************************************************/ @Override public void read() throws IOException { <span class="nc" id="L215"> try (final BufferedReader br = new BufferedReader(new InputStreamReader(input)))</span> { for (; ; ) { <span class="nc" id="L219"> final String s = br.readLine();</span> <span class="nc bnc" id="L221" title="All 2 branches missed."> if (s == null)</span> { <span class="nc" id="L223"> break;</span> } <span class="nc" id="L226"> log.trace(&quot;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; {}: {}&quot;, name, s);</span> <span class="nc" id="L227"> content.add(s);</span> <span class="nc" id="L229"> synchronized (this)</span> { <span class="nc" id="L231"> notifyAll();</span> <span class="nc" id="L232"> }</span> <span class="nc" id="L233"> }</span> } <span class="nc" id="L235"> }</span> } /** The arguments to pass to the external process. */ <span class="nc" id="L239"> private final List&lt;String&gt; arguments = new ArrayList&lt;&gt;();</span> /** The working directory for the external process. */ <span class="nc" id="L242"> private Path workingDirectory = new File(&quot;.&quot;).toPath();</span> /** The external process. */ private Process process; /** The processor of stdout. */ <span class="nc" id="L248"> @Getter</span> private ConsoleOutput stdout; /** The processor of stderr. */ <span class="nc" id="L252"> @Getter</span> private ConsoleOutput stderr; /** The writer to feed the process' stdin. */ private PrintWriter stdin; /******************************************************************************************************************* * ******************************************************************************************************************/ public DefaultProcessExecutor (@Nonnull String executable) throws IOException <span class="nc" id="L263"> {</span> <span class="nc" id="L264"> arguments.add(DefaultProcessExecutor.findPathFor(executable));</span> <span class="nc" id="L265"> }</span> /******************************************************************************************************************* * * {@inheritDoc} * ******************************************************************************************************************/ @Override @Nonnull public ProcessExecutor withArgument (@Nonnull final String argument) { <span class="nc" id="L275"> arguments.add(argument);</span> <span class="nc" id="L276"> return this;</span> } /******************************************************************************************************************* * * {@inheritDoc} * ******************************************************************************************************************/ @Override @Nonnull public ProcessExecutor withArguments (@Nonnull final String... arguments) { <span class="nc" id="L287"> this.arguments.addAll(List.of(arguments));</span> <span class="nc" id="L288"> return this;</span> } /******************************************************************************************************************* * * {@inheritDoc} * ******************************************************************************************************************/ @Override @Nonnull public ProcessExecutor withWorkingDirectory (@Nonnull final Path workingDirectory) { <span class="nc" id="L299"> this.workingDirectory = workingDirectory;</span> <span class="nc" id="L300"> return this;</span> } /******************************************************************************************************************* * * {@inheritDoc} * ******************************************************************************************************************/ @Override @Nonnull public ProcessExecutor start() throws IOException { <span class="nc" id="L312"> log.debug(&quot;&gt;&gt;&gt;&gt; executing: {}&quot;, String.join(&quot; &quot;, arguments));</span> <span class="nc" id="L314"> final List&lt;String&gt; environment = new ArrayList&lt;&gt;();</span> // for (final Entry&lt;String, String&gt; e : System.getenv().entrySet()) // { // environment.add(String.format(&quot;%s=%s&quot;, e.getKey(), e.getValue())); // } <span class="nc" id="L321"> log.debug(&quot;&gt;&gt;&gt;&gt; working directory: {}&quot;, workingDirectory.toFile().getCanonicalPath());</span> <span class="nc" id="L322"> log.debug(&quot;&gt;&gt;&gt;&gt; environment: {}&quot;, environment);</span> <span class="nc" id="L323"> process = Runtime.getRuntime().exec(arguments.toArray(new String[0]),</span> <span class="nc" id="L324"> environment.toArray(new String[0]),</span> <span class="nc" id="L325"> workingDirectory.toFile());</span> <span class="nc" id="L327"> stdout = new DefaultConsoleOutput(&quot;STDOUT&quot;, process.getInputStream()).start();</span> <span class="nc" id="L328"> stderr = new DefaultConsoleOutput(&quot;STDERR&quot;, process.getErrorStream()).start();</span> <span class="nc" id="L329"> stdin = new PrintWriter(process.getOutputStream(), true);</span> <span class="nc" id="L331"> return this;</span> } /******************************************************************************************************************* * * {@inheritDoc} * ******************************************************************************************************************/ @Override @Nonnull public ProcessExecutor waitForCompletion() throws IOException, InterruptedException { <span class="nc bnc" id="L343" title="All 2 branches missed."> if (process.waitFor() != 0)</span> { <span class="nc" id="L345"> final List&lt;String&gt; environment = new ArrayList&lt;&gt;();</span> <span class="nc bnc" id="L347" title="All 2 branches missed."> for (final Entry&lt;String, String&gt; e : System.getenv().entrySet())</span> { <span class="nc" id="L349"> environment.add(String.format(&quot;%s=%s, &quot;, e.getKey(), e.getValue()));</span> <span class="nc" id="L350"> }</span> <span class="nc" id="L352"> log.warn(PROCESS_EXITED_WITH + process.exitValue());</span> <span class="nc" id="L353"> log.debug(&quot;&gt;&gt;&gt;&gt; executed: {}&quot;, arguments);</span> <span class="nc" id="L354"> log.debug(&quot;&gt;&gt;&gt;&gt; working directory: {}&quot;, workingDirectory.toFile().getCanonicalPath());</span> <span class="nc" id="L355"> log.debug(&quot;&gt;&gt;&gt;&gt; environment: {}&quot;, environment);</span> // log(&quot;STDOUT&quot;, stdout); // log(&quot;STDERR&quot;, stderr); <span class="nc" id="L358"> throw new ProcessExecutorException(PROCESS_EXITED_WITH + process.exitValue(),</span> <span class="nc" id="L359"> process.exitValue(),</span> <span class="nc" id="L360"> stdout.waitForCompleted().getContent(),</span> <span class="nc" id="L361"> stderr.waitForCompleted().getContent());</span> } <span class="nc" id="L364"> return this;</span> } /******************************************************************************************************************* * * {@inheritDoc} * ******************************************************************************************************************/ @Override @Nonnull public ProcessExecutor send (@Nonnull final String string) { <span class="nc" id="L375"> log.info(&quot;&gt;&gt;&gt;&gt; sending '{}'...&quot;, string);</span> <span class="nc" id="L376"> stdin.println(string);</span> <span class="nc" id="L377"> 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="nc" id="L393"> final String pathEnv = System.getenv(&quot;PATH&quot;) + File.pathSeparator + &quot;/usr/local/bin&quot;;</span> <span class="nc bnc" id="L395" title="All 2 branches missed."> for (final String path : pathEnv.split(File.pathSeparator))</span> { <span class="nc" id="L397"> final File file = new File(new File(path), executable);</span> <span class="nc bnc" id="L399" title="All 2 branches missed."> if (file.canExecute())</span> { <span class="nc" id="L401"> return file.getAbsolutePath();</span> } } <span class="nc" id="L405"> throw new IOException(&quot;Can't find &quot; + executable + &quot; in PATH&quot;);</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="L418" title="All 2 branches missed."> for (final String line : consoleOutput.getContent())</span> { <span class="nc" id="L420"> log.error(&quot;{}: {}&quot;, prefix, line);</span> <span class="nc" id="L421"> }</span> <span class="nc" id="L422"> }</span> } </pre><div class="footer"><span class="right">Created with <a href="http://www.jacoco.org/jacoco">JaCoCo</a> 0.8.7.202105040129</span></div></body></html>