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> > <a href="../index.html" class="el_bundle">it-tidalwave-util</a> > <a href="index.source.html" class="el_package">it.tidalwave.util.spi</a> > <span class="el_source">DefaultProcessExecutor.java</span></div><h1>DefaultProcessExecutor.java</h1><pre class="source lang-java linenums">/*
* #%L
* *********************************************************************************************************************
*
* These Foolish Things - Miscellaneous utilities
* http://thesefoolishthings.tidalwave.it - git clone git@bitbucket.org:tidalwave/thesefoolishthings-src.git
* %%
* Copyright (C) 2009 - 2021 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.spi;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.concurrent.ThreadSafe;
import java.util.ArrayList;
import java.util.Arrays;
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.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Matcher;
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.Cleanup;
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="L63">@ThreadSafe @NoArgsConstructor(access=AccessLevel.PRIVATE) @Slf4j</span>
public class DefaultProcessExecutor implements ProcessExecutor
{
<span class="nc" id="L66"> private final ExecutorService executorService = Executors.newFixedThreadPool(10);</span>
/*******************************************************************************************************************
*
*
******************************************************************************************************************/
<span class="nc bnc" id="L72" 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="L81"> @Getter</span>
<span class="nc" id="L82"> private final List<String> content = Collections.synchronizedList(new ArrayList<String>());</span>
private volatile String latestLine;
<span class="nc" id="L86"> private volatile int li = 0;</span>
<span class="nc" id="L88"> private final AtomicBoolean started = new AtomicBoolean();</span>
<span class="nc" id="L90"> @CheckForNull @Setter @Getter</span>
private Listener listener;
/***************************************************************************************************************
*
*
***************************************************************************************************************/
<span class="nc" id="L97"> private final Runnable reader = new Runnable()</span>
<span class="nc" id="L98"> {</span>
@Override
public void run()
{
try
{
<span class="nc" id="L104"> read();</span>
}
<span class="nc" id="L106"> catch (IOException e)</span>
{
<span class="nc" id="L108"> log.warn("while reading from " + name, e);</span>
<span class="nc" id="L109"> }</span>
<span class="nc" id="L110"> }</span>
};
/***************************************************************************************************************
*
*
***************************************************************************************************************/
<span class="nc" id="L117"> private final Runnable logger = new Runnable()</span>
<span class="nc" id="L118"> {</span>
@Override
public void run()
{
<span class="nc" id="L122"> int l = 0;</span>
for (;;)
{
try
{
<span class="nc bnc" id="L128" title="All 4 branches missed."> if ((l != li) && (latestLine != null))</span>
{
<span class="nc" id="L130"> log.trace(">>>>>>>> {} {}", name, latestLine);</span>
}
<span class="nc" id="L133"> l = li;</span>
<span class="nc" id="L134"> Thread.sleep(500);</span>
}
<span class="nc" id="L136"> catch (InterruptedException e)</span>
{
<span class="nc" id="L138"> return;</span>
}
<span class="nc" id="L140"> catch (Throwable e)</span>
{
<span class="nc" id="L142"> return;</span>
<span class="nc" id="L143"> }</span>
}
}
};
/***************************************************************************************************************
*
* Should not be used by the programmer.
*
***************************************************************************************************************/
@Nonnull
public ConsoleOutput start()
{
<span class="nc bnc" id="L156" title="All 2 branches missed."> if (started.getAndSet(true))</span>
{
<span class="nc" id="L158"> throw new IllegalStateException("Already started");</span>
}
<span class="nc" id="L161"> log.info("{} - started", name);</span>
<span class="nc" id="L162"> executorService.submit(reader);</span>
<span class="nc" id="L163"> executorService.submit(logger);</span>
<span class="nc" id="L164"> return this;</span>
}
/***************************************************************************************************************
*
* {@inheritDoc}
*
***************************************************************************************************************/
@Override
public boolean latestLineMatches (final @Nonnull String regexp)
{
<span class="nc" id="L175"> String s = null;</span>
<span class="nc bnc" id="L177" title="All 2 branches missed."> if (latestLine != null)</span>
{
<span class="nc" id="L179"> s = latestLine;</span>
}
<span class="nc bnc" id="L181" title="All 2 branches missed."> else if (!content.isEmpty())</span>
{
<span class="nc" id="L183"> s = content.get(content.size() - 1);</span>
}
<span class="nc" id="L186"> log.trace(">>>> testing '{}' for '{}'", s, regexp);</span>
<span class="nc bnc" id="L187" title="All 2 branches missed."> return (s == null) ? false : Pattern.compile(regexp).matcher(s).matches();</span>
// FIXME: sync
}
/***************************************************************************************************************
*
* {@inheritDoc}
*
***************************************************************************************************************/
@Override @Nonnull
public Scanner filteredAndSplitBy (final @Nonnull String filterRegexp, final @Nonnull String delimiterRegexp)
{
<span class="nc" id="L199"> final String string = filteredBy(filterRegexp).get(0);</span>
<span class="nc" id="L200"> return new Scanner(string).useDelimiter(Pattern.compile(delimiterRegexp));</span>
}
/***************************************************************************************************************
*
* {@inheritDoc}
*
***************************************************************************************************************/
@Override @Nonnull
public List<String> filteredBy (final @Nonnull String regexp)
{
<span class="nc" id="L211"> final Pattern pattern = Pattern.compile(regexp);</span>
<span class="nc" id="L212"> final List<String> result = new ArrayList<>();</span>
<span class="nc" id="L213"> final ArrayList<String> strings = new ArrayList<>(content);</span>
// TODO: sync
<span class="nc bnc" id="L216" title="All 2 branches missed."> if (latestLine != null)</span>
{
<span class="nc" id="L218"> strings.add(latestLine);</span>
}
<span class="nc bnc" id="L221" title="All 2 branches missed."> for (final String s : strings)</span>
{
// log.trace(">>>>>>>> matching '{}' with '{}'...", s, filter);
<span class="nc" id="L224"> final Matcher m = pattern.matcher(s);</span>
<span class="nc bnc" id="L226" title="All 2 branches missed."> if (m.matches())</span>
{
<span class="nc" id="L228"> result.add(m.group(1));</span>
}
<span class="nc" id="L230"> }</span>
<span class="nc" id="L232"> return result;</span>
}
/***************************************************************************************************************
*
* {@inheritDoc}
*
***************************************************************************************************************/
@Override @Nonnull
public ConsoleOutput waitFor (final @Nonnull String regexp)
throws InterruptedException, IOException
{
<span class="nc" id="L244"> log.debug("{} - waitFor({})", name, regexp);</span>
<span class="nc bnc" id="L246" title="All 2 branches missed."> while (filteredBy(regexp).isEmpty())</span>
{
try
{
<span class="nc" id="L250"> final int exitValue = process.exitValue();</span>
<span class="nc" id="L251"> throw new IOException("Process exited with " + exitValue);</span>
}
<span class="nc" id="L253"> catch (IllegalThreadStateException e) // ok, process not terminated yet</span>
{
<span class="nc" id="L255"> synchronized (this)</span>
{
<span class="nc" id="L257"> wait(50); // FIXME: polls because it doesn't get notified</span>
<span class="nc" id="L258"> }</span>
<span class="nc" id="L259"> }</span>
}
<span class="nc" id="L262"> return this;</span>
}
/***************************************************************************************************************
*
* {@inheritDoc}
*
***************************************************************************************************************/
@Override
public void clear()
{
<span class="nc" id="L273"> content.clear();</span>
<span class="nc" id="L274"> latestLine = null;</span>
<span class="nc" id="L275"> }</span>
/***************************************************************************************************************
*
*
***************************************************************************************************************/
private void read()
throws IOException
{
<span class="nc bnc" id="L284" title="All 2 branches missed."> final @Cleanup InputStreamReader is = new InputStreamReader(input);</span>
<span class="nc" id="L285"> StringBuilder l = new StringBuilder();</span>
for (;;)
{
<span class="nc" id="L289"> int c = is.read();</span>
<span class="nc bnc" id="L291" title="All 2 branches missed."> if (c < 0)</span>
{
<span class="nc" id="L293"> break;</span>
}
// if (c == 10)
// {
// continue;
// }
<span class="nc bnc" id="L301" title="All 4 branches missed."> if ((c == 13) || (c == 10))</span>
{
<span class="nc" id="L303"> latestLine = l.toString();</span>
<span class="nc" id="L304"> li++;</span>
<span class="nc" id="L305"> content.add(latestLine);</span>
<span class="nc" id="L306"> l = new StringBuilder();</span>
<span class="nc" id="L307"> log.trace(">>>>>>>> {} {}", name, latestLine);</span>
<span class="nc bnc" id="L309" title="All 2 branches missed."> if (listener != null)</span>
{
<span class="nc" id="L311"> listener.onReceived(latestLine);</span>
}
}
else
{
<span class="nc" id="L316"> l.append((char)c);</span>
<span class="nc" id="L317"> latestLine = l.toString();</span>
<span class="nc" id="L318"> li++;</span>
}
<span class="nc" id="L321"> synchronized (this)</span>
{
<span class="nc" id="L323"> notifyAll();</span>
<span class="nc" id="L324"> }</span>
<span class="nc" id="L325"> }</span>
<span class="nc" id="L327"> log.debug(">>>>>> {} closed", name);</span>
<span class="nc" id="L328"> is.close();</span>
<span class="nc" id="L329"> }</span>
}
<span class="nc" id="L332"> private final List<String> arguments = new ArrayList<>();</span>
private Process process;
<span class="nc" id="L336"> @Getter</span>
private ConsoleOutput stdout;
<span class="nc" id="L339"> @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 (final @Nonnull String executable)
{
<span class="nc" id="L358"> final DefaultProcessExecutor executor = new DefaultProcessExecutor();</span>
<span class="nc bnc" id="L359" title="All 2 branches missed."> executor.arguments.add(new File(executable + (isWindows() ? ".exe" : "")).getAbsolutePath());</span>
<span class="nc" id="L360"> return executor;</span>
}
// /*******************************************************************************************************************
// *
// *
// ******************************************************************************************************************/
// @Nonnull
// private static String findPath (final @Nonnull String executable)
// throws NotFoundException
// {
// for (final String path : System.getenv("PATH").split(File.pathSeparator))
// {
// final File file = new File(new File(path), executable);
//
// if (file.canExecute())
// {
// return file.getAbsolutePath();
// }
// }
//
// throw new NotFoundException("Can't find " + executable + " in PATH");
// }
/*******************************************************************************************************************
*
* {@inheritDoc}
*
******************************************************************************************************************/
@Override @Nonnull
public DefaultProcessExecutor withArgument (final @Nonnull String argument)
{
<span class="nc" id="L392"> arguments.add(argument);</span>
<span class="nc" id="L393"> return this;</span>
}
/*******************************************************************************************************************
*
* {@inheritDoc}
*
******************************************************************************************************************/
@Override @Nonnull
public DefaultProcessExecutor withArguments (final @Nonnull String ... arguments)
{
<span class="nc" id="L404"> this.arguments.addAll(Arrays.asList(arguments));</span>
<span class="nc" id="L405"> return this;</span>
}
/*******************************************************************************************************************
*
* {@inheritDoc}
*
******************************************************************************************************************/
@Override @Nonnull
public DefaultProcessExecutor start()
throws IOException
{
<span class="nc" id="L417"> log.info(">>>> executing {} ...", arguments);</span>
<span class="nc" id="L419"> final List<String> environment = new ArrayList<>();</span>
<span class="nc bnc" id="L421" title="All 2 branches missed."> for (final Entry<String, String> e : System.getenv().entrySet())</span>
{
<span class="nc" id="L423"> environment.add(String.format("%s=%s", e.getKey(), e.getValue()));</span>
<span class="nc" id="L424"> }</span>
<span class="nc" id="L426"> log.info(">>>> environment: {}", environment);</span>
<span class="nc" id="L427"> process = Runtime.getRuntime().exec(arguments.toArray(new String[0]),</span>
<span class="nc" id="L428"> environment.toArray(new String[0]));</span>
<span class="nc" id="L430"> stdout = new DefaultConsoleOutput("out", process.getInputStream()).start();</span>
<span class="nc" id="L431"> stderr = new DefaultConsoleOutput("err", process.getErrorStream()).start();</span>
<span class="nc" id="L432"> stdin = new PrintWriter(process.getOutputStream(), true);</span>
<span class="nc" id="L434"> return this;</span>
}
/*******************************************************************************************************************
*
* {@inheritDoc}
*
******************************************************************************************************************/
@Override
public void stop()
{
<span class="nc" id="L445"> log.info("stop()");</span>
<span class="nc" id="L446"> process.destroy();</span>
<span class="nc" id="L447"> executorService.shutdownNow();</span>
<span class="nc" id="L448"> }</span>
/*******************************************************************************************************************
*
* {@inheritDoc}
*
******************************************************************************************************************/
@Override @Nonnull
public DefaultProcessExecutor waitForCompletion()
throws IOException, InterruptedException
{
<span class="nc bnc" id="L459" title="All 2 branches missed."> if (process.waitFor() != 0)</span>
{
// throw new IOException("Process exited with " + process.exitValue()); FIXME
}
<span class="nc" id="L464"> return this;</span>
}
/*******************************************************************************************************************
*
* {@inheritDoc}
*
******************************************************************************************************************/
@Override @Nonnull
public DefaultProcessExecutor send (final @Nonnull String string)
throws IOException
{
<span class="nc" id="L476"> log.debug(">>>> sending '{}'...", string.replaceAll("\n", "<CR>"));</span>
<span class="nc" id="L477"> stdin.print(string);</span>
<span class="nc" id="L478"> stdin.flush();</span>
<span class="nc" id="L479"> return this;</span>
}
/*******************************************************************************************************************
*
*
******************************************************************************************************************/
private static boolean isWindows()
{
<span class="nc" id="L488"> return System.getProperty ("os.name").toLowerCase().startsWith("windows");</span>
}
}
</pre><div class="footer"><span class="right">Created with <a href="http://www.jacoco.org/jacoco">JaCoCo</a> 0.8.6.202009150832</span></div></body></html>