1 package org.coolreader.crengine; 2 3 // By Muzikant@stackoverflow.com 4 // See https://stackoverflow.com/a/19272315 for details 5 6 import java.io.ByteArrayOutputStream; 7 import java.io.IOException; 8 import java.io.InputStream; 9 10 public class ProcessIOWithTimeout extends Thread { 11 12 public static final int EXIT_CODE_TIMEOUT = Integer.MIN_VALUE; 13 14 final private Process m_process; 15 private int m_exitCode = EXIT_CODE_TIMEOUT; 16 private final ByteArrayOutputStream m_outputStream; 17 private final byte[] m_buffer; 18 ProcessIOWithTimeout(Process process, int buffSize)19 public ProcessIOWithTimeout(Process process, int buffSize) { 20 m_process = process; 21 m_buffer = new byte[buffSize]; 22 m_outputStream = new ByteArrayOutputStream(); 23 } 24 waitForProcess(long timeout)25 public int waitForProcess(long timeout) { 26 start(); 27 try { 28 join(timeout); 29 } catch (InterruptedException e) { 30 interrupt(); 31 } 32 return m_exitCode; 33 } 34 receivedData()35 public byte[] receivedData() { 36 return m_outputStream.toByteArray(); 37 } 38 39 @Override run()40 public void run() { 41 try { 42 InputStream inputStream = m_process.getInputStream(); 43 int rb; 44 while ((rb = inputStream.read(m_buffer)) != -1) { 45 m_outputStream.write(m_buffer, 0, rb); 46 } 47 // at this point the process should already be terminated 48 // just get exit code 49 m_exitCode = m_process.waitFor(); 50 inputStream.close(); 51 } catch (InterruptedException ignore) { 52 // Do nothing 53 } catch (IOException ignored) { 54 // Do nothing 55 } catch (Exception ex) { 56 // Unexpected exception 57 } 58 } 59 } 60