List of usage examples for java.lang Process getErrorStream
public abstract InputStream getErrorStream();
From source file:at.ait.dme.yuma.server.image.ImageTilesetGenerator.java
/** * generates TMS tiles for the given image. it starts a separate process and executes * the configured command (gdal2tiles).// w w w . j av a2 s .c o m * * @param url * @return tileset * @throws TilesetGenerationException */ public Tileset generateTilesetFromUrl(String url) throws TilesetGenerationException { try { String tilesDir = rootPath + "/" + createPathForImage(url); if (new File(tilesDir).mkdir()) { String imageFile = storeImage(tilesDir, url); Process p = Runtime.getRuntime().exec(generationCommand + " " + imageFile + " " + tilesDir); // consume the input stream, so the process does not hang InputStream stderr = p.getInputStream(); InputStreamReader isr = new InputStreamReader(stderr); BufferedReader br = new BufferedReader(isr); while ((br.readLine()) != null) ; if (p.waitFor() != 0) { String errorMessage = ""; InputStream errorStream = p.getErrorStream(); if (errorStream != null) errorMessage = IOUtils.toString(errorStream, "UTF-8"); throw new TilesetGenerationException("failed to create tiles: " + errorMessage); } } return createTileset(url, tilesDir); } catch (Throwable t) { logger.fatal(t.getMessage(), t); throw new TilesetGenerationException(t); } }
From source file:is.iclt.jcorpald.CorpaldModel.java
private void performRunQuery() throws Exception { String queryFile = null;//w ww . ja va 2 s. c o m String outputFile = null; String targetFile = null; if (this.file == null) { queryFile = new File(this.getTempQueryPath()).getPath(); // outputFile = this.getTempOutputPath(); } else { queryFile = this.file.getPath(); // outputFile = queryFile.substring(0,queryFile.length()-2)+".out"; } outputFile = queryFile.substring(0, queryFile.length() - 2) + ".out"; targetFile = outputFile.substring(0, outputFile.length() - 4) + ".txt"; try { // FileUtils.deleteQui(new File(outputFile)); new File(outputFile).delete(); System.out.println("Deleted: " + outputFile); } catch (Exception ex) { System.out.println(ex.getMessage()); ex.printStackTrace(); } // Write the query to a temporary file this.file = new File(queryFile); FileUtils.writeStringToFile(file, this.constructQueryFile(), "utf-8"); String cmd = "java -classpath lib/CS_2.002.75.jar csearch.CorpusSearch \"" + new File(queryFile).getPath() + "\" corpora/" + CorpaldSettings.getInstance().getProperty("corpus.directory") + "/*.psd -out \"" + new File(outputFile).getPath() + "\""; if (!OSValidator.isWindows()) { cmd = cmd.replace("\"", ""); } result = cmd; System.out.println(cmd); /* Runtime run = Runtime.getRuntime(); Process pr = null; pr = run.exec(cmd); pr.waitFor(); */ //hhhhhhhh Process application = Runtime.getRuntime().exec(cmd); StringBuffer inBuffer = new StringBuffer(); InputStream inStream = application.getInputStream(); new InputStreamHandler(inBuffer, inStream); StringBuffer errBuffer = new StringBuffer(); InputStream errStream = application.getErrorStream(); new InputStreamHandler(errBuffer, errStream); application.waitFor(); // TODO deal with somehow // System.out.println(stdout); // System.out.println(stderr); String result = FileUtils.readFileToString(new File(outputFile), "utf-8"); FileUtils.deleteQuietly(new File(targetFile)); FileUtils.moveFile(new File(outputFile), new File(targetFile)); //String line; //boolean error = false; //String stdout = IOUtils.toString(pr.getInputStream()).trim(); // String stderr = "x"; // IOUtils.toString(pr.getErrorStream()).trim(); // if( pr.getErrorStream() // System.out.println(stderr); if (errBuffer.toString().indexOf("ERROR!") > -1) { result = "Unfortunately there is a problem with your query.\nCorpusSearch was unable to " + "come up with results.\n\n" + "Did you misspell a keyword, a logical operator or a reference to the definitions file?\n" + "- those are displayed in orange, blue and green respectively if well-formed\n" + "Did you use the correct number of arguments for all search functions?\n" + "- for example, 'idoms' requires two arguments while 'idomsmod' requires three \n" + "- see CorpusSearch documentation (http://corpussearch.sourceforge.net)\n" + "Do you have unmatched parentheses or brackets?\n"; } this.setModified(false); this.notifyQueryObservsers(); setResult(result); }
From source file:net.ostis.scpdev.builder.M4ScpFileBuilder.java
@Override public void buildImpl(IFolder binroot) throws CoreException { String m4 = ScCoreModule.getM4Path(); String m4scp = ScCoreModule.getM4ScpPath(); String sourceOsPath = source.getLocation().toOSString(); String includeOsPath = source.getParent().getLocation().toOSString(); try {/*w w w.java 2 s . com*/ Process processM4Scp2SCs = Runtime.getRuntime().exec( String.format("\"%s\" -I\"%s\" \"%s\" \"%s\"", m4, includeOsPath, m4scp, sourceOsPath), null, new File(includeOsPath)); File converted = File.createTempFile(source.getName(), ""); try { OutputStream out = new FileOutputStream(converted); try { IOUtils.copy(processM4Scp2SCs.getInputStream(), out); } finally { out.close(); } if (processM4Scp2SCs.waitFor() != 0) { System.err.println(IOUtils.toString(processM4Scp2SCs.getErrorStream())); } else { InputStream errorStream = convertSCsSource(converted.getAbsolutePath(), binroot); if (errorStream != null) applySCsErrors(source, errorStream); } } finally { converted.delete(); } } catch (Exception e) { log.error("Unexpected exception", e); throw new CoreException(new Status(IStatus.ERROR, ScpdevPlugin.PLUGIN_ID, "Unexpected exception", e)); } }
From source file:com.ibm.bi.dml.yarn.DMLYarnClient.java
/** * This is our fallback strategy for obtaining our SystemML.jar that we need * to submit as resource for the yarn application. We repackage the unzipped * jar to a temporary jar and later copy it to hdfs. * /*from www. j ava 2 s. co m*/ * @param dir * @return * @throws IOException * @throws InterruptedException */ private String createJar(String dir) throws IOException, InterruptedException { //construct jar command String jarname = dir + "/" + DML_JAR_NAME; File fdir = new File(dir); File[] tmp = fdir.listFiles(); StringBuilder flist = new StringBuilder(); for (File ftmp : tmp) { flist.append(ftmp.getName()); flist.append(" "); } //get jdk home (property 'java.home' gives jre-home of parent jdk or standalone) String javahome = System.getProperty("java.home"); File fjdkhome = new File(new File(javahome).getParent() + File.separator + "bin"); String jarPrefix = ""; if (fjdkhome.exists()) { //exists if jdk jarPrefix = fjdkhome.getAbsolutePath(); jarPrefix += File.separator; } if (jarPrefix.isEmpty()) LOG.warn("Failed to find jdk home of running jre (java.home=" + javahome + ")."); //execute jar command String command = jarPrefix + "jar cf " + jarname + " " + flist.subSequence(0, flist.length() - 1); LOG.debug("Packaging jar of unzipped files: " + command); Process child = Runtime.getRuntime().exec(command, null, fdir); int c = 0; while ((c = child.getInputStream().read()) != -1) System.out.print((char) c); while ((c = child.getErrorStream().read()) != -1) System.err.print((char) c); child.waitFor(); return jarname; }
From source file:it.grid.storm.namespace.util.userinfo.UserInfoCommand.java
/** * /*from w ww . java2s . c om*/ * @param command * String[] * @return String */ private String getOutput(String[] command) throws UserInfoException { String result = ""; try { Process child = Runtime.getRuntime().exec(command); log.debug("Command executed: " + ArrayUtils.toString(command)); BufferedReader stdInput = null; BufferedReader stdError = null; // Get the input stream and read from it if (child != null) { stdInput = new BufferedReader(new InputStreamReader(child.getInputStream())); stdError = new BufferedReader(new InputStreamReader(child.getErrorStream())); } if (stdInput != null) { // process the Command Output (Input for StoRM ;) ) String line; int row = 0; log.trace("UserInfo Command Output :"); while ((line = stdInput.readLine()) != null) { log.trace(row + ": " + line); boolean lineOk = processOutput(row, line); if (lineOk) { result = result + line + "\n"; } row++; } // process the Errors String errLine; if (stdError != null) { while ((errLine = stdError.readLine()) != null) { log.warn("User Info Command Output contains an ERROR message " + errLine); throw new UserInfoException(errLine); } } } } catch (IOException ex) { log.error("getUserInfo (id) I/O Exception: " + ex); throw new UserInfoException(ex); } return result; }
From source file:org.energyos.espi.datacustodian.web.api.ManageRESTController.java
/** * Provides access to administrative commands through the pattern: * DataCustodian/manage?command=[resetDataCustodianDB | * initializeDataCustodianDB]/*from w ww. j av a2 s .com*/ * * @param response * Contains text version of stdout of the command * @param params * [["command" . ["resetDataCustodianDB" | * "initializeDataCustodianDB"]]] * @param stream * @throws IOException */ @RequestMapping(value = Routes.DATA_CUSTODIAN_MANAGE, method = RequestMethod.GET, produces = "text/plain") @ResponseBody public void doCommand(HttpServletResponse response, @RequestParam Map<String, String> params, InputStream stream) throws IOException { response.setContentType(MediaType.TEXT_PLAIN_VALUE); try { try { String commandString = params.get("command"); System.out.println("[Manage] " + commandString); ServletOutputStream output = response.getOutputStream(); output.println("[Manage] Restricted Management Interface"); output.println("[Manage] Request: " + commandString); String command = null; // parse command if (commandString.contains("resetDataCustodianDB")) { command = "/etc/OpenESPI/DataCustodian/resetDatabase.sh"; } else if (commandString.contains("initializeDataCustodianDB")) { command = "/etc/OpenESPI/DataCustodian/initializeDatabase.sh"; } if (command != null) { Process p = Runtime.getRuntime().exec(command); p.waitFor(); output.println("[Manage] Result: "); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = reader.readLine(); while (line != null) { System.out.println("[Manage] " + line); output.println("[Manage]: " + line); line = reader.readLine(); } reader = new BufferedReader(new InputStreamReader(p.getErrorStream())); output.println("[Manage] Errors: "); line = reader.readLine(); while (line != null) { System.out.println("[Manage] " + line); output.println("[Manage]: " + line); line = reader.readLine(); } } } catch (IOException e1) { } catch (InterruptedException e2) { } System.out.println("[Manage] " + "Done"); } catch (Exception e) { System.out.printf("**** [Manage] Error: %s\n", e.toString()); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } }
From source file:com.diversityarrays.kdxplore.trialdesign.RscriptFinderPanel.java
private void doCheckScriptPath() { String scriptPath = scriptPathField.getText().trim(); BackgroundTask<Either<String, String>, Void> task = new BackgroundTask<Either<String, String>, Void>( "Checking...", true) { @Override/* w w w . j av a 2 s .c o m*/ public Either<String, String> generateResult(Closure<Void> arg0) throws Exception { ProcessBuilder findRScript = new ProcessBuilder(scriptPath, "--version"); Process p = findRScript.start(); while (!p.waitFor(1000, TimeUnit.MILLISECONDS)) { if (backgroundRunner.isCancelRequested()) { p.destroy(); throw new CancellationException(); } } if (0 == p.exitValue()) { String output = Algorithms.readContent(null, p.getInputStream()); versionNumber = Algorithms.readContent(null, p.getErrorStream()); return Either.right(output); } errorOutput = Algorithms.readContent("Error Output:", p.getErrorStream()); if (errorOutput.isEmpty()) { errorOutput = "No error output available"; return Either.left(errorOutput); } return Either.left(errorOutput); } @Override public void onException(Throwable t) { onScriptPathChecked.accept(Either.left(t)); } @Override public void onCancel(CancellationException ce) { onScriptPathChecked.accept(Either.left(ce)); } @Override public void onTaskComplete(Either<String, String> either) { if (either.isLeft()) { MsgBox.error(RscriptFinderPanel.this, either.left(), "Error Output"); } else { TrialDesignPreferences.getInstance().setRscriptPath(scriptPath); onScriptPathChecked.accept(Either.right(scriptPath)); checkOutput = either.right(); } } }; backgroundRunner.runBackgroundTask(task); }
From source file:ch.entwine.weblounge.common.impl.util.process.ProcessExecutor.java
/** * Executes the process. During execution, {@link #onLineRead(String)} will be * called for process output. When finished, {@link #onProcessFinished(int)} * is called.//from www .j av a2 s . c o m * * @throws ProcessExcecutorException * if an error occurs during execution */ public final void execute() throws ProcessExcecutorException { BufferedReader in = null; Process process = null; StreamHelper errorStreamHelper = null; try { // create process. // no special working directory is set which means the working directory // of the current java process is used. ProcessBuilder pbuilder = new ProcessBuilder(commandLine); pbuilder.redirectErrorStream(redirectErrorStream); process = pbuilder.start(); // Consume error stream if necessary if (!redirectErrorStream) { errorStreamHelper = new StreamHelper(process.getErrorStream()); } // Read input and in = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = in.readLine()) != null) { if (!onLineRead(line)) break; } // wait until the task is finished process.waitFor(); int exitCode = process.exitValue(); onProcessFinished(exitCode); } catch (Throwable t) { String msg = null; if (errorStreamHelper != null) { msg = errorStreamHelper.contentBuffer.toString(); } else { msg = t.getMessage(); } // TODO: What if the error stream has been redirected? Can we still get // the error message? throw new ProcessExcecutorException(msg, t); } finally { if (process != null) process.destroy(); IOUtils.closeQuietly(in); } }
From source file:com.telefonica.euro_iaas.sdc.pupperwrapper.services.tests.ActionsServiceTest.java
@Test(expected = IOException.class) public void isNodeRegisteredException() throws IOException { Process shell = mock(Process.class); String[] cmd = { anyString() }; when(processBuilderFactory.createProcessBuilder(cmd)).thenReturn(shell); String str = ""; when(shell.getInputStream()).thenReturn(new ByteArrayInputStream(str.getBytes("UTF-8"))); String strEr = " "; when(shell.getErrorStream()).thenReturn(new ByteArrayInputStream(strEr.getBytes("UTF-8"))); Assert.assertTrue(actionsService.isNodeRegistered("1")); }
From source file:egovframework.com.utl.sys.fsm.service.FileSystemUtils.java
/** * Performs the os command./* w ww. jav a 2 s . c o m*/ * * @param cmdAttribs the command line parameters * @param max The maximum limit for the lines returned * @return the parsed data * @throws IOException if an error occurs */ List performCommand(String[] cmdAttribs, int max) throws IOException { // this method does what it can to avoid the 'Too many open files' error // based on trial and error and these links: // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4784692 // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4801027 // http://forum.java.sun.com/thread.jspa?threadID=533029&messageID=2572018 // however, its still not perfect as the JDK support is so poor // (see commond-exec or ant for a better multi-threaded multi-os solution) List lines = new ArrayList(20); Process proc = null; InputStream in = null; OutputStream out = null; InputStream err = null; BufferedReader inr = null; try { proc = openProcess(cmdAttribs); in = proc.getInputStream(); out = proc.getOutputStream(); err = proc.getErrorStream(); inr = new BufferedReader(new InputStreamReader(in)); String line = inr.readLine(); while (line != null && lines.size() < max) { line = line.toLowerCase().trim(); lines.add(line); line = inr.readLine(); } proc.waitFor(); if (proc.exitValue() != 0) { // os command problem, throw exception throw new IOException("Command line returned OS error code '" + proc.exitValue() + "' for command " + Arrays.asList(cmdAttribs)); } if (lines.size() == 0) { // unknown problem, throw exception throw new IOException( "Command line did not return any info " + "for command " + Arrays.asList(cmdAttribs)); } return lines; } catch (InterruptedException ex) { throw new IOException("Command line threw an InterruptedException '" + ex.getMessage() + "' for command " + Arrays.asList(cmdAttribs)); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); IOUtils.closeQuietly(err); IOUtils.closeQuietly(inr); if (proc != null) { proc.destroy(); } } }