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">TheseFoolishThings :: Actors</a> &gt; <a href="../index.html" class="el_bundle">it-tidalwave-util</a> &gt; <a href="index.source.html" class="el_package">it.tidalwave.util.spi</a> &gt; <span class="el_source">DefaultProcessExecutor.java</span></div><h1>DefaultProcessExecutor.java</h1><pre class="source lang-java linenums">/*
 * *********************************************************************************************************************
 *
 * TheseFoolishThings: Miscellaneous utilities
 * http://tidalwave.it/projects/thesefoolishthings
 *
 * Copyright (C) 2009 - 2023 by 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.
 *
 * *********************************************************************************************************************
 *
 * git clone https://bitbucket.org/tidalwave/thesefoolishthings-src
 * git clone https://github.com/tidalwave-it/thesefoolishthings-src
 *
 * *********************************************************************************************************************
 */
package it.tidalwave.util.spi;

import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.concurrent.ThreadSafe;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Pattern;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import it.tidalwave.util.ProcessExecutor;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/***********************************************************************************************************************
 *
 * @author  Fabrizio Giudici
 * @since   1.39
 *
 **********************************************************************************************************************/
<span class="nc" id="L60">@ThreadSafe @NoArgsConstructor(access=AccessLevel.PRIVATE) @Slf4j</span>
public class DefaultProcessExecutor implements ProcessExecutor
  {
<span class="nc" id="L63">    private final ExecutorService executorService = Executors.newFixedThreadPool(10);</span>

    /*******************************************************************************************************************
     *
     *
     ******************************************************************************************************************/
<span class="nc bnc" id="L69" title="All 4 branches missed.">    @RequiredArgsConstructor(access=AccessLevel.PACKAGE)</span>
    public class DefaultConsoleOutput implements ConsoleOutput
      {
        @Nonnull
        private final String name;

        @Nonnull
        private final InputStream input;

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

        private volatile String latestLine;

<span class="nc" id="L83">        private final AtomicInteger li = new AtomicInteger(0);</span>

<span class="nc" id="L85">        private final AtomicBoolean started = new AtomicBoolean();</span>
        
<span class="nc" id="L87">        @CheckForNull @Setter @Getter</span>
        private Listener listener;

        /***************************************************************************************************************
         *
         *
         ***************************************************************************************************************/
<span class="nc" id="L94">        private final Runnable reader = new Runnable()</span>
<span class="nc" id="L95">          {</span>
            @Override
            public void run()
              {
                try
                  {
<span class="nc" id="L101">                    read();</span>
                  }
<span class="nc" id="L103">                catch (IOException e)</span>
                  {
<span class="nc" id="L105">                    log.warn(&quot;while reading from &quot; + name, e);</span>
<span class="nc" id="L106">                  }</span>
<span class="nc" id="L107">              }</span>
          };

        /***************************************************************************************************************
         *
         *
         ***************************************************************************************************************/
<span class="nc" id="L114">        private final Runnable logger = new Runnable()</span>
<span class="nc" id="L115">          {</span>
            @Override
            public void run()
              {
<span class="nc" id="L119">                var l = 0;</span>

                for (;;)
                  {
                    try
                      {
<span class="nc bnc" id="L125" title="All 4 branches missed.">                        if ((l != li.get()) &amp;&amp; (latestLine != null))</span>
                          {
<span class="nc" id="L127">                            log.trace(&quot;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; {} {}&quot;, name, latestLine);</span>
                          }

<span class="nc" id="L130">                        l = li.get();</span>
<span class="nc" id="L131">                        Thread.sleep(500);</span>
                      }
<span class="nc" id="L133">                    catch (Throwable e)</span>
                      {
<span class="nc" id="L135">                        return;</span>
<span class="nc" id="L136">                      }</span>
                  }
              }
          };

        /***************************************************************************************************************
         *
         * Should not be used by the programmer.
         *
         * @return -
         *
         ***************************************************************************************************************/
        @Nonnull
        public ConsoleOutput start()
          {
<span class="nc bnc" id="L151" title="All 2 branches missed.">            if (started.getAndSet(true))</span>
              {
<span class="nc" id="L153">                throw new IllegalStateException(&quot;Already started&quot;);</span>
              }

<span class="nc" id="L156">            log.info(&quot;{} - started&quot;, name);</span>
<span class="nc" id="L157">            executorService.submit(reader);</span>
<span class="nc" id="L158">            executorService.submit(logger);</span>
<span class="nc" id="L159">            return this;</span>
          }

        /***************************************************************************************************************
         *
         * {@inheritDoc}
         *
         ***************************************************************************************************************/
        @Override
        public boolean latestLineMatches (@Nonnull final String regexp)
          {
<span class="nc" id="L170">            String s = null;</span>

<span class="nc bnc" id="L172" title="All 2 branches missed.">            if (latestLine != null)</span>
              {
<span class="nc" id="L174">                s = latestLine;</span>
              }
<span class="nc bnc" id="L176" title="All 2 branches missed.">            else if (!content.isEmpty())</span>
              {
<span class="nc" id="L178">                s = content.get(content.size() - 1);</span>
              }

<span class="nc" id="L181">            log.trace(&quot;&gt;&gt;&gt;&gt; testing '{}' for '{}'&quot;, s, regexp);</span>
<span class="nc bnc" id="L182" title="All 4 branches missed.">            return (s != null) &amp;&amp; Pattern.compile(regexp).matcher(s).matches();</span>
            // FIXME: sync
          }

        /***************************************************************************************************************
         *
         * {@inheritDoc}
         *
         ***************************************************************************************************************/
        @Override @Nonnull
        public Scanner filteredAndSplitBy (@Nonnull final String filterRegexp, @Nonnull final String delimiterRegexp)
          {
<span class="nc" id="L194">            final var string = filteredBy(filterRegexp).get(0);</span>
<span class="nc" id="L195">            return new Scanner(string).useDelimiter(Pattern.compile(delimiterRegexp));</span>
          }

        /***************************************************************************************************************
         *
         * {@inheritDoc}
         *
         ***************************************************************************************************************/
        @Override @Nonnull
        public List&lt;String&gt; filteredBy (@Nonnull final String regexp)
          {
<span class="nc" id="L206">            final var pattern = Pattern.compile(regexp);</span>
<span class="nc" id="L207">            final List&lt;String&gt; result = new ArrayList&lt;&gt;();</span>
<span class="nc" id="L208">            final var strings = new ArrayList&lt;&gt;(content);</span>

            // TODO: sync
<span class="nc bnc" id="L211" title="All 2 branches missed.">            if (latestLine != null)</span>
              {
<span class="nc" id="L213">                strings.add(latestLine);</span>
              }

<span class="nc bnc" id="L216" title="All 2 branches missed.">            for (final var s : strings)</span>
              {
//                log.trace(&quot;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; matching '{}' with '{}'...&quot;, s, filter);
<span class="nc" id="L219">                final var m = pattern.matcher(s);</span>

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

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

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

<span class="nc bnc" id="L241" title="All 2 branches missed.">            while (filteredBy(regexp).isEmpty())</span>
              {
                try
                  {
<span class="nc" id="L245">                    final var exitValue = process.exitValue();</span>
<span class="nc" id="L246">                    throw new IOException(&quot;Process exited with &quot; + exitValue);</span>
                  }
<span class="nc" id="L248">                catch (IllegalThreadStateException e) // ok, process not terminated yet</span>
                  {
<span class="nc" id="L250">                    synchronized (this)</span>
                      {
<span class="nc" id="L252">                        wait(50); // FIXME: polls because it doesn't get notified</span>
polls because it doesn't get notified
<span class="nc" id="L253"> }</span> <span class="nc" id="L254"> }</span> } <span class="nc" id="L257"> return this;</span> } /*************************************************************************************************************** * * {@inheritDoc} * ***************************************************************************************************************/ @Override public void clear() { <span class="nc" id="L268"> content.clear();</span> <span class="nc" id="L269"> latestLine = null;</span> <span class="nc" id="L270"> }</span> /*************************************************************************************************************** * * ***************************************************************************************************************/ private void read() throws IOException { <span class="nc" id="L279"> try (final var is = new InputStreamReader(input))</span> { <span class="nc" id="L281"> var l = new StringBuilder();</span> for (;;) { <span class="nc" id="L285"> final var c = is.read();</span> <span class="nc bnc" id="L287" title="All 2 branches missed."> if (c &lt; 0)</span> { <span class="nc" id="L289"> break;</span> } // if (c == 10) // { // continue; // } <span class="nc bnc" id="L297" title="All 4 branches missed."> if ((c == 13) || (c == 10))</span> { <span class="nc" id="L299"> latestLine = l.toString();</span> <span class="nc" id="L300"> li.incrementAndGet();</span> <span class="nc" id="L301"> content.add(latestLine);</span> <span class="nc" id="L302"> l = new StringBuilder();</span> <span class="nc" id="L303"> log.trace(&quot;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; {} {}&quot;, name, latestLine);</span> <span class="nc bnc" id="L305" title="All 2 branches missed."> if (listener != null)</span> { <span class="nc" id="L307"> listener.onReceived(latestLine);</span> } } else { <span class="nc" id="L312"> l.append((char)c);</span> <span class="nc" id="L313"> latestLine = l.toString();</span> <span class="nc" id="L314"> li.incrementAndGet();</span> } <span class="nc" id="L317"> synchronized (this)</span> { <span class="nc" id="L319"> notifyAll();</span> <span class="nc" id="L320"> }</span> <span class="nc" id="L321"> }</span> <span class="nc" id="L323"> log.debug(&quot;&gt;&gt;&gt;&gt;&gt;&gt; {} closed&quot;, name);</span> } <span class="nc" id="L325"> }</span> } <span class="nc" id="L328"> private final List&lt;String&gt; arguments = new ArrayList&lt;&gt;();</span> private Process process; <span class="nc" id="L332"> @Getter</span> private ConsoleOutput stdout; <span class="nc" id="L335"> @Getter</span> private ConsoleOutput stderr; private PrintWriter stdin; /******************************************************************************************************************* * * Factory method for associating an executable. It returns an intermediate executor that must be configured and * later started. Under Windows, the '.exe' suffix is automatically appended to the name of the executable. * * @see #start() * * @param executable the executable (with the full path) * @return the executor * ******************************************************************************************************************/ @Nonnull public static DefaultProcessExecutor forExecutable (@Nonnull final String executable) { <span class="nc" id="L354"> final var executor = new DefaultProcessExecutor();</span> <span class="nc bnc" id="L355" title="All 2 branches missed."> executor.arguments.add(new File(executable + (isWindows() ? &quot;.exe&quot; : &quot;&quot;)).getAbsolutePath());</span> <span class="nc" id="L356"> return executor;</span> } // /******************************************************************************************************************* // * // * // ******************************************************************************************************************/ // @Nonnull // private static String findPath (final @Nonnull String executable) // throws NotFoundException // { // for (final String path : System.getenv(&quot;PATH&quot;).split(File.pathSeparator)) // { // final File file = new File(new File(path), executable); // // if (file.canExecute()) // { // return file.getAbsolutePath(); // } // } // // throw new NotFoundException(&quot;Can't find &quot; + executable + &quot; in PATH&quot;); // } /******************************************************************************************************************* * * {@inheritDoc} * ******************************************************************************************************************/ @Override @Nonnull public DefaultProcessExecutor withArgument (@Nonnull final String argument) { <span class="nc" id="L388"> arguments.add(argument);</span> <span class="nc" id="L389"> return this;</span> } /******************************************************************************************************************* * * {@inheritDoc} * ******************************************************************************************************************/ @Override @Nonnull public DefaultProcessExecutor withArguments (@Nonnull final String ... arguments) { <span class="nc" id="L400"> this.arguments.addAll(List.of(arguments));</span> <span class="nc" id="L401"> return this;</span> } /******************************************************************************************************************* * * {@inheritDoc} * ******************************************************************************************************************/ @Override @Nonnull public DefaultProcessExecutor start() throws IOException { <span class="nc" id="L413"> log.info(&quot;&gt;&gt;&gt;&gt; executing {} ...&quot;, arguments);</span> <span class="nc" id="L415"> final List&lt;String&gt; environment = new ArrayList&lt;&gt;();</span> <span class="nc bnc" id="L417" title="All 2 branches missed."> for (final var e : System.getenv().entrySet())</span> { <span class="nc" id="L419"> environment.add(String.format(&quot;%s=%s&quot;, e.getKey(), e.getValue()));</span> <span class="nc" id="L420"> }</span> <span class="nc" id="L422"> log.info(&quot;&gt;&gt;&gt;&gt; environment: {}&quot;, environment);</span> <span class="nc" id="L423"> process = Runtime.getRuntime().exec(arguments.toArray(new String[0]),</span> <span class="nc" id="L424"> environment.toArray(new String[0]));</span> <span class="nc" id="L426"> stdout = new DefaultConsoleOutput(&quot;out&quot;, process.getInputStream()).start();</span> <span class="nc" id="L427"> stderr = new DefaultConsoleOutput(&quot;err&quot;, process.getErrorStream()).start();</span> <span class="nc" id="L428"> stdin = new PrintWriter(process.getOutputStream(), true);</span> <span class="nc" id="L430"> return this;</span> } /******************************************************************************************************************* * * {@inheritDoc} * ******************************************************************************************************************/ @Override public void stop() { <span class="nc" id="L441"> log.info(&quot;stop()&quot;);</span> <span class="nc" id="L442"> process.destroy();</span> <span class="nc" id="L443"> executorService.shutdownNow();</span> <span class="nc" id="L444"> }</span> /******************************************************************************************************************* * * {@inheritDoc} * ******************************************************************************************************************/ @Override @Nonnull public DefaultProcessExecutor waitForCompletion() throws InterruptedException { <span class="nc bnc" id="L455" title="All 2 branches missed."> if (process.waitFor() != 0)</span> { // throw new IOException(&quot;Process exited with &quot; + process.exitValue()); FIXME } <span class="nc" id="L460"> return this;</span> } /******************************************************************************************************************* * * {@inheritDoc} * ******************************************************************************************************************/ @Override @Nonnull public DefaultProcessExecutor send (@Nonnull final String string) { <span class="nc" id="L471"> log.debug(&quot;&gt;&gt;&gt;&gt; sending '{}'...&quot;, string.replaceAll(&quot;\n&quot;, &quot;&lt;CR&gt;&quot;));</span> <span class="nc" id="L472"> stdin.print(string);</span> <span class="nc" id="L473"> stdin.flush();</span> <span class="nc" id="L474"> return this;</span> } /******************************************************************************************************************* * * ******************************************************************************************************************/ private static boolean isWindows() { <span class="nc" id="L483"> return System.getProperty (&quot;os.name&quot;).toLowerCase().startsWith(&quot;windows&quot;);</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>