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 :: Examples :: Finder :: JPA Finder</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">/*
* *********************************************************************************************************************
*
* TheseFoolishThings: Miscellaneous utilities
* http://tidalwave.it/projects/thesefoolishthings
*
* Copyright (C) 2009 - 2021 by 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.
*
* *********************************************************************************************************************
*
* 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.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<>());</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 (Throwable e)</span>
{
<span class="nc" id="L138"> return;</span>
<span class="nc" id="L139"> }</span>
}
}
};
/***************************************************************************************************************
*
* Should not be used by the programmer.
*
* @return -
*
***************************************************************************************************************/
@Nonnull
public ConsoleOutput start()
{
<span class="nc bnc" id="L154" title="All 2 branches missed."> if (started.getAndSet(true))</span>
{
<span class="nc" id="L156"> throw new IllegalStateException("Already started");</span>
}
<span class="nc" id="L159"> log.info("{} - started", name);</span>
<span class="nc" id="L160"> executorService.submit(reader);</span>
<span class="nc" id="L161"> executorService.submit(logger);</span>
<span class="nc" id="L162"> return this;</span>
}
/***************************************************************************************************************
*
* {@inheritDoc}
*
***************************************************************************************************************/
@Override
public boolean latestLineMatches (@Nonnull final String regexp)
{
<span class="nc" id="L173"> String s = null;</span>
<span class="nc bnc" id="L175" title="All 2 branches missed."> if (latestLine != null)</span>
{
<span class="nc" id="L177"> s = latestLine;</span>
}
<span class="nc bnc" id="L179" title="All 2 branches missed."> else if (!content.isEmpty())</span>
{
<span class="nc" id="L181"> s = content.get(content.size() - 1);</span>
}
<span class="nc" id="L184"> log.trace(">>>> testing '{}' for '{}'", s, regexp);</span>
<span class="nc bnc" id="L185" title="All 4 branches missed."> return (s != null) && 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="L197"> final String string = filteredBy(filterRegexp).get(0);</span>
<span class="nc" id="L198"> return new Scanner(string).useDelimiter(Pattern.compile(delimiterRegexp));</span>
}
/***************************************************************************************************************
*
* {@inheritDoc}
*
***************************************************************************************************************/
@Override @Nonnull
public List<String> filteredBy (@Nonnull final String regexp)
{
<span class="nc" id="L209"> final Pattern pattern = Pattern.compile(regexp);</span>
<span class="nc" id="L210"> final List<String> result = new ArrayList<>();</span>
<span class="nc" id="L211"> final ArrayList<String> strings = new ArrayList<>(content);</span>
// TODO: sync
<span class="nc bnc" id="L214" title="All 2 branches missed."> if (latestLine != null)</span>
{
<span class="nc" id="L216"> strings.add(latestLine);</span>
}
<span class="nc bnc" id="L219" title="All 2 branches missed."> for (final String s : strings)</span>
{
// log.trace(">>>>>>>> matching '{}' with '{}'...", s, filter);
<span class="nc" id="L222"> final Matcher m = pattern.matcher(s);</span>
<span class="nc bnc" id="L224" title="All 2 branches missed."> if (m.matches())</span>
{
<span class="nc" id="L226"> result.add(m.group(1));</span>
}
<span class="nc" id="L228"> }</span>
<span class="nc" id="L230"> return result;</span>
}
/***************************************************************************************************************
*
* {@inheritDoc}
*
***************************************************************************************************************/
@Override @Nonnull
public ConsoleOutput waitFor (@Nonnull final String regexp)
throws InterruptedException, IOException
{
<span class="nc" id="L242"> log.debug("{} - waitFor({})", name, regexp);</span>
<span class="nc bnc" id="L244" title="All 2 branches missed."> while (filteredBy(regexp).isEmpty())</span>
{
try
{
<span class="nc" id="L248"> final int exitValue = process.exitValue();</span>
<span class="nc" id="L249"> throw new IOException("Process exited with " + exitValue);</span>
}
<span class="nc" id="L251"> catch (IllegalThreadStateException e) // ok, process not terminated yet</span>
{
<span class="nc" id="L253"> synchronized (this)</span>
{
<span class="nc" id="L255"> wait(50); // FIXME: polls because it doesn't get notified</span>
<span class="nc" id="L256"> }</span>
<span class="nc" id="L257"> }</span>
}
<span class="nc" id="L260"> return this;</span>
}
/***************************************************************************************************************
*
* {@inheritDoc}
*
***************************************************************************************************************/
@Override
public void clear()
{
<span class="nc" id="L271"> content.clear();</span>
<span class="nc" id="L272"> latestLine = null;</span>
<span class="nc" id="L273"> }</span>
/***************************************************************************************************************
*
*
***************************************************************************************************************/
private void read()
throws IOException
{
<span class="nc bnc" id="L282" title="All 2 branches missed."> @Cleanup final InputStreamReader is = new InputStreamReader(input);</span>
<span class="nc" id="L283"> StringBuilder l = new StringBuilder();</span>
for (;;)
{
<span class="nc" id="L287"> final int c = is.read();</span>
<span class="nc bnc" id="L289" title="All 2 branches missed."> if (c < 0)</span>
{
<span class="nc" id="L291"> break;</span>
}
// if (c == 10)
// {
// continue;
// }
<span class="nc bnc" id="L299" title="All 4 branches missed."> if ((c == 13) || (c == 10))</span>
{
<span class="nc" id="L301"> latestLine = l.toString();</span>
<span class="nc" id="L302"> li++;</span>
<span class="nc" id="L303"> content.add(latestLine);</span>
<span class="nc" id="L304"> l = new StringBuilder();</span>
<span class="nc" id="L305"> log.trace(">>>>>>>> {} {}", name, latestLine);</span>
<span class="nc bnc" id="L307" title="All 2 branches missed."> if (listener != null)</span>
{
<span class="nc" id="L309"> listener.onReceived(latestLine);</span>
}
}
else
{
<span class="nc" id="L314"> l.append((char)c);</span>
<span class="nc" id="L315"> latestLine = l.toString();</span>
<span class="nc" id="L316"> li++;</span>
}
<span class="nc" id="L319"> synchronized (this)</span>
{
<span class="nc" id="L321"> notifyAll();</span>
<span class="nc" id="L322"> }</span>
<span class="nc" id="L323"> }</span>
<span class="nc" id="L325"> log.debug(">>>>>> {} closed", name);</span>
<span class="nc" id="L326"> is.close();</span>
<span class="nc" id="L327"> }</span>
}
<span class="nc" id="L330"> private final List<String> arguments = new ArrayList<>();</span>
private Process process;
<span class="nc" id="L334"> @Getter</span>
private ConsoleOutput stdout;
<span class="nc" id="L337"> @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="L356"> final DefaultProcessExecutor executor = new DefaultProcessExecutor();</span>
<span class="nc bnc" id="L357" title="All 2 branches missed."> executor.arguments.add(new File(executable + (isWindows() ? ".exe" : "")).getAbsolutePath());</span>
<span class="nc" id="L358"> 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 (@Nonnull final String argument)
{
<span class="nc" id="L390"> arguments.add(argument);</span>
<span class="nc" id="L391"> return this;</span>
}
/*******************************************************************************************************************
*
* {@inheritDoc}
*
******************************************************************************************************************/
@Override @Nonnull
public DefaultProcessExecutor withArguments (@Nonnull final String ... arguments)
{
<span class="nc" id="L402"> this.arguments.addAll(Arrays.asList(arguments));</span>
<span class="nc" id="L403"> return this;</span>
}
/*******************************************************************************************************************
*
* {@inheritDoc}
*
******************************************************************************************************************/
@Override @Nonnull
public DefaultProcessExecutor start()
throws IOException
{
<span class="nc" id="L415"> log.info(">>>> executing {} ...", arguments);</span>
<span class="nc" id="L417"> final List<String> environment = new ArrayList<>();</span>
<span class="nc bnc" id="L419" title="All 2 branches missed."> for (final Entry<String, String> e : System.getenv().entrySet())</span>
{
<span class="nc" id="L421"> environment.add(String.format("%s=%s", e.getKey(), e.getValue()));</span>
<span class="nc" id="L422"> }</span>
<span class="nc" id="L424"> log.info(">>>> environment: {}", environment);</span>
<span class="nc" id="L425"> process = Runtime.getRuntime().exec(arguments.toArray(new String[0]),</span>
<span class="nc" id="L426"> environment.toArray(new String[0]));</span>
<span class="nc" id="L428"> stdout = new DefaultConsoleOutput("out", process.getInputStream()).start();</span>
<span class="nc" id="L429"> stderr = new DefaultConsoleOutput("err", process.getErrorStream()).start();</span>
<span class="nc" id="L430"> stdin = new PrintWriter(process.getOutputStream(), true);</span>
<span class="nc" id="L432"> return this;</span>
}
/*******************************************************************************************************************
*
* {@inheritDoc}
*
******************************************************************************************************************/
@Override
public void stop()
{
<span class="nc" id="L443"> log.info("stop()");</span>
<span class="nc" id="L444"> process.destroy();</span>
<span class="nc" id="L445"> executorService.shutdownNow();</span>
<span class="nc" id="L446"> }</span>
/*******************************************************************************************************************
*
* {@inheritDoc}
*
******************************************************************************************************************/
@Override @Nonnull
public DefaultProcessExecutor waitForCompletion()
throws IOException, InterruptedException
{
<span class="nc bnc" id="L457" title="All 2 branches missed."> if (process.waitFor() != 0)</span>
{
// throw new IOException("Process exited with " + process.exitValue()); FIXME
}
<span class="nc" id="L462"> return this;</span>
}
/*******************************************************************************************************************
*
* {@inheritDoc}
*
******************************************************************************************************************/
@Override @Nonnull
public DefaultProcessExecutor send (@Nonnull final String string)
{
<span class="nc" id="L473"> log.debug(">>>> sending '{}'...", string.replaceAll("\n", "<CR>"));</span>
<span class="nc" id="L474"> stdin.print(string);</span>
<span class="nc" id="L475"> stdin.flush();</span>
<span class="nc" id="L476"> return this;</span>
}
/*******************************************************************************************************************
*
*
******************************************************************************************************************/
private static boolean isWindows()
{
<span class="nc" id="L485"> 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>