List of usage examples for java.lang IllegalThreadStateException getMessage
public String getMessage()
From source file:com.tascape.qa.th.Utils.java
/** * Executes command, and waits for the expected pass/fail phrase in console printout within timeout, * * @param command command line/*w w w .j a v a2 s. co m*/ * @param pass skip checking if null * @param fail skip checking if null * @param timeout set 0 for not to check the output message, otherwise, waiting for timeout * @param workingDir working directory * * @return console output as a list of strings * * @throws IOException for command error * @throws InterruptedException when interrupted */ public static List<String> cmd(String[] command, final String pass, final String fail, final long timeout, final String workingDir) throws IOException, InterruptedException { ProcessBuilder pb = new ProcessBuilder(command); if (workingDir != null) { pb.directory(new File(workingDir)); } pb.redirectErrorStream(true); LOG.debug("Running command: " + pb.command().toString().replace(",", "")); final Process p = pb.start(); Thread thread; final List<String> output = new ArrayList<>(); if (timeout == 0) { LOG.debug("This is a start-and-exit command"); output.add(PASS); return output; } else { thread = new Thread() { @Override public void run() { try { LOG.debug("Command timeouts in {} ms", timeout); Thread.sleep(timeout); try { p.exitValue(); } catch (IllegalThreadStateException ex) { LOG.debug("killing subprocess {} - {}", p, ex.getMessage()); p.destroy(); } } catch (InterruptedException ex) { LOG.warn(ex.getMessage()); } } }; thread.setName(Thread.currentThread().getName() + "-" + p.hashCode()); thread.setDaemon(true); thread.start(); } BufferedReader stdIn = new BufferedReader(new InputStreamReader(p.getInputStream())); String c = p + " - "; for (String line = stdIn.readLine(); line != null;) { LOG.trace("{}{}", c, line); output.add(line); try { line = stdIn.readLine(); } catch (IOException ex) { LOG.warn(ex.getMessage()); break; } } LOG.debug("Command exit code {}", p.waitFor()); thread.interrupt(); try { stdIn.close(); } catch (IOException ex) { LOG.warn("", ex); } for (String s : output) { if (pass != null && (s.contains(pass) || s.matches(pass))) { output.add(PASS); break; } else if (fail != null && s.contains(fail)) { output.add(FAIL); break; } } return output; }
From source file:com.hellblazer.process.JavaProcessTest.java
public void testOnDemandInputOutputStreams() throws Exception { copyTestClassFile();/*from w ww .j a v a 2s. co m*/ JavaProcess process = new JavaProcessImpl(processFactory.create()); process.setArguments(new String[] { "-loglines" }); process.setJavaClass(HelloWorld.class.getCanonicalName()); process.setDirectory(testDir); process.setJavaExecutable(javaBin); // Try it before launching process try { process.getStdOutTail(200); fail("Expected an illegal thread state exception because the process hasn't started yet"); } catch (IllegalThreadStateException e) { System.out.println("Caught expected exception : " + e.getMessage()); } try { process.getStdErrTail(200); fail("Expected an illegal thread state exception because the process hasn't started yet"); } catch (IllegalThreadStateException e) { System.out.println("Caught expected exception : " + e.getMessage()); } try { launchProcess(process); String stdout = process.getStdOutTail(200).trim(); assertTrue(stdout.startsWith("Line #4800")); assertTrue(stdout.endsWith("Line #4999")); String stderr = process.getStdErrTail(200).trim(); assertTrue(stderr.startsWith("Line #4800")); assertTrue(stderr.endsWith("Line #4999")); } finally { if (process != null) { process.destroy(); } } }
From source file:com.emc.ecs.sync.filter.ShellCommandFilter.java
@Override public void filter(SyncObject obj) { getNext().filter(obj);//from w ww.j av a2 s .c o m String[] cmdLine = new String[] { command, obj.getSourceIdentifier(), obj.getTargetIdentifier() }; try { Process p = Runtime.getRuntime().exec(cmdLine); InputStream stdout = p.getInputStream(); InputStream stderr = p.getErrorStream(); while (true) { try { int exitCode = p.exitValue(); if (exitCode != 0) { throw new RuntimeException( "Command: " + Arrays.asList(cmdLine) + "exited with code " + exitCode); } else { return; } } catch (IllegalThreadStateException e) { // ignore; process running } // Drain stdout and stderr. Many processes will hang if you // dont do this. drain(stdout, System.out); drain(stderr, System.err); } } catch (IOException e) { throw new RuntimeException("Error executing command: " + Arrays.asList(cmdLine) + ": " + e.getMessage(), e); } }
From source file:dataflow.docker.DockerProcess.java
/** * Wait for the process to finish and periodically grab the output. * * @param builder// ww w .j a va 2 s . c o m * @param prefix * @param command * @param logger * @param outStream * @return */ public int waitForAndLogProcess(Logger logger, PrintStream outStream) { String commandText = StringUtils.join(command, " "); try { synchronized (process) { BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream())); // In milliseconds. final long TIMEOUT = 1000; boolean wait = true; while (wait) { // We periodically check if the process has terminated and if not, // print out all the processes output process.wait(TIMEOUT); // Print all the output String line; while ((stdInput.ready()) && ((line = stdInput.readLine()) != null)) { if (outStream != null) { outStream.println(line); } else { logger.info(line); } } while ((stdError.ready()) && ((line = stdError.readLine()) != null)) { // TODO(jlewi): We should use logger.log and use function arguments // to specify what priority the output should be logged at. logger.error(line); } try { process.exitValue(); // Process is done. wait = false; } catch (IllegalThreadStateException e) { // Process hasn't completed yet. } } logger.info("Exit Value: " + process.exitValue()); if (process.exitValue() != 0) { logger.error("Command: " + commandText + " exited with non-zero status."); } } return process.exitValue(); } catch (IOException e) { throw new RuntimeException("There was a problem executing the command:\n" + commandText + "\n. The Exception was:\n" + e.getMessage()); } catch (InterruptedException e) { throw new RuntimeException("Execution was interupted. The command was:\n" + commandText + "\n. The Exception was:\n" + e.getMessage()); } }
From source file:com.emc.vipr.sync.source.FilesystemSource.java
protected void delete(File file) { // Try to lock the file first. If this fails, the file is // probably open for write somewhere. // Note that on a mac, you can apparently delete files that // someone else has open for writing, and can lock files // too.//w ww . j a v a 2 s. c o m // Must make sure to throw exceptions when necessary to flag actual failures as opposed to skipped files. if (file.isDirectory()) { File metaDir = getMetaFile(file).getParentFile(); if (metaDir.exists()) metaDir.delete(); // Just try and delete dir if (!file.delete()) { LogMF.warn(l4j, "Failed to delete directory {0}", file); } } else { boolean tryDelete = true; if (deleteOlderThan > 0) { if (System.currentTimeMillis() - file.lastModified() < deleteOlderThan) { LogMF.info(l4j, "not deleting {0}; it is not at least {1} ms old", file, deleteOlderThan); tryDelete = false; } } if (deleteCheckScript != null) { String[] args = new String[] { deleteCheckScript.getAbsolutePath(), file.getAbsolutePath() }; try { l4j.debug("delete check: " + Arrays.asList(args)); Process p = Runtime.getRuntime().exec(args); while (true) { try { int exitCode = p.exitValue(); if (exitCode == 0) { LogMF.debug(l4j, "delete check OK, exit code {0}", exitCode); } else { LogMF.info(l4j, "delete check failed, exit code {0}. Not deleting file.", exitCode); tryDelete = false; } break; } catch (IllegalThreadStateException e) { // Ignore. } } } catch (IOException e) { LogMF.info(l4j, "error executing delete check script: {0}. Not deleting file.", e.toString()); tryDelete = false; } } RandomAccessFile raf = null; if (tryDelete) { try { raf = new RandomAccessFile(file, "rw"); FileChannel fc = raf.getChannel(); FileLock flock = fc.lock(); // If we got here, we should be good. flock.release(); if (!file.delete()) { throw new RuntimeException(MessageFormat.format("Failed to delete {0}", file)); } } catch (IOException e) { throw new RuntimeException(MessageFormat .format("File {0} not deleted, it appears to be open: {1}", file, e.getMessage())); } finally { if (raf != null) { try { raf.close(); } catch (IOException e) { // Ignore. } } } } } }
From source file:org.scantegrity.scanner.ScannerController.java
/** * Return a ballot image from the scanner. The scan is in duplex, so this * will always return an array of size 2. The elements inside *may* be null, * however.//from w ww. j a v a2s.com * * @return * @throws IOException */ public BufferedImage[] getImagesFromScanner() throws IOException { Process l_p; int l_pid = 0; String l_cmd = c_binpath + c_scanimgcmd + " " + c_inpath + c_scanopts; //Execute the scan command l_p = Runtime.getRuntime().exec(l_cmd); l_pid = getPid(c_scanimgcmd); if (l_pid == 0) { try { l_p.exitValue(); } catch (IllegalThreadStateException l_e) { c_log.log(Level.WARNING, c_binpath + c_scanimgcmd + " failed to exec." + getErrorMsg(l_p)); } l_pid = -1; } synchronized (this) { //Wait for it to end. int l_hang = 0; do { for (int l_i = 0; l_i < c_timeout; l_i += 200) { if (l_pid != getPid(c_scanimgcmd)) break; try { wait(200); } catch (InterruptedException e) { //do nothing. } } // If it's still alive after 3s send a signal to it // to see if it's still responding. if (l_pid == getPid(c_scanimgcmd)) { // If it doesn't respond and it's still running kill the // process and throw an error (which should cause us to // try again) if (!isAlive(l_pid)) { c_log.log(Level.WARNING, c_scanimgcmd + " did not die."); killPid(l_pid); } else { //Countdown, if it's still going after 12s, do something if (l_hang >= c_hangup) { killPid(l_pid); break; } else { l_hang += c_timeout; } } } } while (l_pid == getPid(c_scanimgcmd)); // Java does not close these streams, so we need to do that here // to prevent too many open files error closeProcess(l_p); } //try to read in the images BufferedImage l_imgs[] = new BufferedImage[2]; for (int l_i = 0; l_i < 2; l_i++) { try { File l_imgFile = new File(c_inpath + String.format(c_scanfmt, l_i + 1)); if (l_imgFile.exists()) { try { RenderedOp l_op = JAI.create("FileLoad", l_imgFile.getAbsolutePath()); l_imgs[l_i] = l_op.createInstance().getAsBufferedImage(); } catch (Exception l_e) { l_imgs[l_i] = null; c_log.log(Level.WARNING, "Read Error: " + l_e.getMessage()); //Handle the error image by moving it } //Delete or move the scanned image after reading. try { if (l_imgs[l_i] == null) { FileUtils.copyFile(l_imgFile, new File(c_outpath + "readerror-" + c_err + ".tiff")); c_err++; } if (c_delete) { FileUtils.forceDelete(l_imgFile); } else { FileUtils.copyFile(l_imgFile, new File(c_outpath)); FileUtils.forceDelete(l_imgFile); } } catch (Exception l_e) { c_log.log(Level.WARNING, "Unable to move or delete the" + " ballot image file.. Changing the" + " scanformat name."); c_suffix++; c_scanopts += "-" + c_suffix; c_scanfmt += "-" + c_suffix; } } else { l_imgs[l_i] = null; c_log.log(Level.FINE, "Could not read " + l_imgFile.getName()); //IT does not exist, so we can't move it. } } catch (Exception l_e) { //Couldn't even open it... l_imgs[l_i] = null; c_log.log(Level.WARNING, "Error: " + l_e.getMessage()); } } //If we failed, check the return value. Log it. if (l_imgs == null || (l_imgs[0] == null && l_imgs[1] == null)) { int l_err = l_p.exitValue(); switch (l_err) { case 0: case 7: //This is the "out of documents" error. break; default: c_log.log(Level.WARNING, "Scanner exited with error code " + l_err + "\n Message: " + getErrorMsg(l_p)); break; } } return l_imgs; }