List of usage examples for java.lang Process getErrorStream
public abstract InputStream getErrorStream();
From source file:com.twosigma.beaker.r.rest.RShellRest.java
private RServer startRserve() throws IOException, RserveException, REXPMismatchException { int port = getPortFromCore(); String pluginInstallDir = System.getProperty("user.dir"); String password = RandomStringUtils.random(40, true, true); String[] command = { "Rscript", writeRserveScript(port, password) }; // Need to clear out some environment variables in order for a // new Java process to work correctly. // XXX not always necessary, use getPluginEnvps from BeakerConfig? // or just delete? List<String> environmentList = new ArrayList<>(); for (Entry<String, String> entry : System.getenv().entrySet()) { if (!("CLASSPATH".equals(entry.getKey()))) { environmentList.add(entry.getKey() + "=" + entry.getValue()); }//from www. j a v a 2 s .c o m } String[] environmentArray = new String[environmentList.size()]; environmentList.toArray(environmentArray); Process rServe = Runtime.getRuntime().exec(command, environmentArray); BufferedReader rServeOutput = new BufferedReader(new InputStreamReader(rServe.getInputStream(), "ASCII")); String line = null; while ((line = rServeOutput.readLine()) != null) { if (line.indexOf("(This session will block until Rserve is shut down)") >= 0) { break; } else { // System.out.println("Rserve>" + line); } } ErrorGobbler errorGobbler = new ErrorGobbler(rServe.getErrorStream()); errorGobbler.start(); ROutputHandler handler = new ROutputHandler(rServe.getInputStream(), BEGIN_MAGIC, END_MAGIC); handler.start(); RConnection rconn = new RConnection("127.0.0.1", port); rconn.login("beaker", password); int pid = rconn.eval("Sys.getpid()").asInteger(); return new RServer(rconn, handler, errorGobbler, port, password, pid); }
From source file:de.flyingsnail.ipv6droid.android.VpnThread.java
/** * Android 4.4 has introduced a bug with VPN routing. The android developers appear very * pleased with their broken idea and unwilling to fix in any forseeable future. * This methods tries to check if our device suffers from this problem. * @return true if routing is OK//from w w w . j a v a 2s . c om */ private boolean checkRouting() { try { Process routeChecker = Runtime.getRuntime() .exec(new String[] { "/system/bin/ip", "-f", "inet6", "route", "show", "default", "::/1" }); BufferedReader reader = new BufferedReader(new InputStreamReader(routeChecker.getInputStream())); BufferedReader errreader = new BufferedReader(new InputStreamReader(routeChecker.getErrorStream())); String output = reader.readLine(); String errors = errreader.readLine(); try { routeChecker.waitFor(); } catch (InterruptedException e) { // we got interrupted, so we kill our process routeChecker.destroy(); } int exitValue = 0; try { exitValue = routeChecker.exitValue(); } catch (IllegalStateException ise) { // command still running. Hmmm. } if (output == null || exitValue != 0) { Log.e(TAG, "error checking route: " + errors); return false; // default route is not set on ipv6 } else return true; } catch (IOException e) { return false; // we cannot even check :-( } }
From source file:com.photon.phresco.framework.commons.QualityUtil.java
public ArrayList<String> getConnAndroidDevices(String command) throws Exception { S_LOGGER.debug("Entering Method QualityUtil.getConnAndroidDevices() for quality tab"); ArrayList<String> output = new ArrayList<String>(); try {//from w w w . j a v a 2s . c om String s = null; Process p = Runtime.getRuntime().exec(command); BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream())); int cnt = 0; while ((s = stdInput.readLine()) != null) { if (cnt > 0) { s = s.substring(0, s.indexOf("\t") + 1); output.add(s.trim()); } cnt++; } stdInput.close(); cnt = 0; while ((s = stdError.readLine()) != null) { if (cnt > 0) { s = s.substring(0, s.indexOf("\t") + 1); output.add(s.trim()); } cnt++; } stdError.close(); } catch (Exception e) { S_LOGGER.error("Entered into catch block of Quality.getConnAndroidDevices()" + FrameworkUtil.getStackTraceAsString(e)); } output.remove(output.size() - 1); return output; }
From source file:fr.ens.biologie.genomique.eoulsan.it.ITCommandExecutor.java
/** * Execute a script from a command line retrieved from the test configuration. * @param scriptConfKey key for configuration to get command line * @param suffixNameOutputFile suffix for standard and error output file on * process// w w w. j av a 2 s. co m * @param desc description on command line * @param isApplicationCmdLine true if application to run, otherwise false * corresponding to annexes script * @return result of execution command line, if command line not found in * configuration return null */ public ITCommandResult executeCommand(final String scriptConfKey, final String suffixNameOutputFile, final String desc, final boolean isApplicationCmdLine) { if (this.testConf.getProperty(scriptConfKey) == null) { return null; } // Get command line from the configuration final String cmdLine = this.testConf.getProperty(scriptConfKey); if (cmdLine.isEmpty()) { return null; } // Save command line in file if (isApplicationCmdLine) { try { com.google.common.io.Files.write(cmdLine + "\n", this.cmdLineFile, Charsets.UTF_8); } catch (final IOException e) { getLogger().warning("Error while writing the application command line in file: " + e.getMessage()); } } // Define stdout and stderr file final File stdoutFile = createSdtoutFile(suffixNameOutputFile); final File stderrFile = createSdterrFile(suffixNameOutputFile); int exitValue = -1; final Stopwatch timer = Stopwatch.createStarted(); final ITCommandResult cmdResult = new ITCommandResult(cmdLine, this.outputTestDirectory, desc, durationMax); try { final Process p = Runtime.getRuntime().exec(cmdLine, this.environmentVariables, this.outputTestDirectory); // Init monitor and start final MonitorThread monitor = new MonitorThread(p, desc, durationMax); // Save stdout if (stdoutFile != null) { new CopyProcessOutput(p.getInputStream(), stdoutFile, "stdout").start(); } // Save stderr if (stderrFile != null) { new CopyProcessOutput(p.getErrorStream(), stderrFile, "stderr").start(); } // Wait the end of the process exitValue = p.waitFor(); // Stop monitor thread monitor.interrupt(); cmdResult.setExitValue(exitValue); // Execution script fail, create an exception if (exitValue != 0) { if (monitor.isKilledProcess()) { cmdResult.asInterruptedProcess(); cmdResult.setException( new EoulsanException("\tKill process.\n\tCommand line: " + cmdLine + "\n\tDirectory: " + this.outputTestDirectory + "\n\tMessage: " + monitor.getMessage())); } else { cmdResult.setException(new EoulsanException("\tCommand line: " + cmdLine + "\n\tDirectory: " + this.outputTestDirectory + "\n\tMessage: bad exit value: " + exitValue)); cmdResult.setErrorFileOnProcess(stderrFile); } } else if (exitValue == 0 && !isApplicationCmdLine) { // Success execution, remove standard and error output file if (!stdoutFile.delete()) { getLogger().warning("Unable to deleted stdout file: " + stdoutFile); } if (!stderrFile.delete()) { getLogger().warning("Unable to deleted stderr file: " + stdoutFile); } } } catch (IOException | InterruptedException e) { cmdResult.setException(e, "\tError before execution.\n\tCommand line: " + cmdLine + "\n\tDirectory: " + this.outputTestDirectory + "\n\tMessage: " + e.getMessage()); } finally { cmdResult.setDuration(timer.elapsed(TimeUnit.MILLISECONDS)); timer.stop(); } return cmdResult; }
From source file:ixa.pipe.ned_ukb.Annotate.java
public void disambiguateNEsToKAF(KAFDocument kaf, String scripts, String ukbExec, String ukbKb, String ukbDict, String wikiDb) throws Exception { String resourceExternalRef = ukbKb.substring(ukbKb.lastIndexOf("/") + 1); List<String> neIds = new ArrayList<String>(); String ukbContext = "naf\n"; List<Entity> entities = kaf.getEntities(); for (Entity entity : entities) { String entityId = entity.getId(); String entityLemma = ""; List<Term> entityTerms = entity.getTerms(); for (Term term : entityTerms) { String tId = term.getId(); neIds.add(tId);/*from w ww . j a va2 s . c om*/ if (!entityLemma.equals("")) { entityLemma += "_"; } entityLemma += term.getLemma().toLowerCase(); } ukbContext += entityLemma + "##" + entityId + "#1 "; } String formsContext2Match = ""; String lemmasContext2Match = ""; List<Term> terms = kaf.getTerms(); for (Term term : terms) { if (!neIds.contains(term.getId())) { if (!(term.getForm().contains("@@")) && !(term.getForm().contains(" "))) { formsContext2Match += term.getForm().toLowerCase() + "@@" + term.getWFs().get(0).getOffset() + " "; lemmasContext2Match += term.getLemma().toLowerCase() + "@@" + term.getWFs().get(0).getOffset() + " "; } } } // create UKB context String[] cmdMatch = { "perl", scripts + "/merge_match.pl", "-d", wikiDb, "--t1", formsContext2Match, "--t2", lemmasContext2Match }; Process pMatch = Runtime.getRuntime().exec(cmdMatch); String matchedContext = ""; String outputLineContext = ""; BufferedReader outputContextStream = new BufferedReader( new InputStreamReader(pMatch.getInputStream(), "UTF-8")); while ((outputLineContext = outputContextStream.readLine()) != null) { matchedContext += outputLineContext + "\n"; } outputContextStream.close(); String errorContext = ""; BufferedReader errorContextStream = new BufferedReader(new InputStreamReader(pMatch.getErrorStream())); while ((errorContext = errorContextStream.readLine()) != null) { System.err.println("MERGE_MATCH ERROR: " + errorContext); } errorContextStream.close(); pMatch.waitFor(); String[] contextStrings = matchedContext.split(" "); for (String contextString : contextStrings) { if (contextString.equals("")) continue; contextString = contextString.trim(); //ContextString = spot_string@@spot_offset String[] contextWordOffset = contextString.split("@@"); ukbContext += contextWordOffset[0] + "##" + contextWordOffset[1] + "#1 "; } File contextTmpFile = File.createTempFile("context", ".tmp"); contextTmpFile.deleteOnExit(); String contextTmpFileName = contextTmpFile.getAbsolutePath(); Writer contextFile = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(contextTmpFile), "UTF-8")); try { contextFile.write(ukbContext); } finally { contextFile.close(); } // run UKB String cmdUkb = ukbExec + " --prank_damping 0.90 --prank_iter 15 --allranks --minput --nopos --ppr_w2w --dict_weight -K " + ukbKb + " -D " + ukbDict + " " + contextTmpFileName; Process pUkb = Runtime.getRuntime().exec(cmdUkb); String outputUkb = ""; String outputLineUkb = ""; BufferedReader outputUkbStream = new BufferedReader(new InputStreamReader(pUkb.getInputStream(), "UTF-8")); while ((outputLineUkb = outputUkbStream.readLine()) != null) { outputUkb += outputLineUkb + "\n"; } outputUkbStream.close(); String errorUkb = ""; BufferedReader errorUkbStream = new BufferedReader(new InputStreamReader(pUkb.getErrorStream())); while ((errorUkb = errorUkbStream.readLine()) != null) { System.err.println("UKB ERROR: " + errorUkb); } errorUkbStream.close(); pUkb.waitFor(); // UKB output (one line): context_id word_id (concept_id(/weight)?)+ !! lemma (there are 2 spaces after word_id) // UKB output example: naf e12 Norvegia/0.999998 Norvegiako_bandera/2.25207e-06 !! norvegia Map<String, String> entityLinks = new HashMap<String, String>(); // e12 --> Norvegia/0.999998 String ukbDisambiguations[] = outputUkb.split("\n"); for (String ukbDisambiguation : ukbDisambiguations) { if (ukbDisambiguation.startsWith("!! -v")) continue; String ukbLine[] = ukbDisambiguation.split(" "); entityLinks.put(ukbLine[1], ukbLine[3]); } // UKB links to KAF for (Entity entity : entities) { String entityId = entity.getId(); if (entityLinks.containsKey(entityId)) { String reference = entityLinks.get(entityId).split("/")[0]; String confidence = entityLinks.get(entityId).split("/")[1]; String ref2 = reference; reference = "http://" + language + ".wikipedia.org/wiki/" + reference; ExternalRef externalRef = kaf.newExternalRef(resourceExternalRef, reference); externalRef.setConfidence(Float.parseFloat(confidence)); externalRef.setSource(language); externalRef.setReftype(language); entity.addExternalRef(externalRef); if (cross) { String mappingRef = getMappingRef(reference); if (mappingRef != null) { ExternalRef enRef = kaf.newExternalRef(this.resourceMapping, mappingRef); enRef.setConfidence(Float.parseFloat(confidence)); enRef.setSource(language); enRef.setReftype("en"); entity.addExternalRef(enRef); } } } else { // UKB didn't assign any link to this entity. Try with MFS String cmdMfs = "perl " + scripts + "/mfs.pl -d " + wikiDb; Process pMfs = Runtime.getRuntime().exec(cmdMfs); String entityLemma = ""; List<Term> entityTerms = entity.getTerms(); for (Term term : entityTerms) { if (!entityLemma.equals("")) { entityLemma += "_"; } entityLemma += term.getLemma().toLowerCase(); } OutputStream stdinMfs = pMfs.getOutputStream(); stdinMfs.write(entityLemma.getBytes()); stdinMfs.flush(); stdinMfs.close(); String outputMfs = ""; BufferedReader outputMfsStream = new BufferedReader( new InputStreamReader(pMfs.getInputStream(), "UTF-8")); outputMfs = outputMfsStream.readLine(); outputMfsStream.close(); String errorMfs = ""; BufferedReader errorMfsStream = new BufferedReader(new InputStreamReader(pMfs.getErrorStream())); while ((errorMfs = errorMfsStream.readLine()) != null) { System.err.println("MFS ERROR: " + errorMfs); } errorMfsStream.close(); pMfs.waitFor(); if (!outputMfs.equals("NILL")) { String reference = outputMfs; String confidence = "1"; reference = "http://" + language + ".wikipedia.org/wiki/" + reference; ExternalRef externalRef = kaf.newExternalRef("MFS_" + resourceExternalRef, reference); externalRef.setConfidence(Float.parseFloat(confidence)); externalRef.setSource(language); externalRef.setReftype(language); entity.addExternalRef(externalRef); if (cross) { String mappingRef = getMappingRef(reference); if (mappingRef != null) { ExternalRef enRef = kaf.newExternalRef(this.resourceMapping, mappingRef); enRef.setConfidence(Float.parseFloat(confidence)); enRef.setSource(language); enRef.setReftype("en"); entity.addExternalRef(enRef); } } } } } }
From source file:metadata.etl.dataset.hdfs.HdfsMetadataEtl.java
private void extractLocal() throws Exception { URL localJarUrl = classLoader.getResource("jar/schemaFetch.jar"); String homeDir = System.getProperty("user.home"); String remoteJarFile = homeDir + "/.wherehows/schemaFetch.jar"; File dest = new File(remoteJarFile); try {//from ww w . ja va 2 s .co m FileUtils.copyURLToFile(localJarUrl, dest); } catch (Exception e) { logger.error(e.toString()); } String outputSchemaFile = prop.getProperty(Constant.HDFS_SCHEMA_LOCAL_PATH_KEY); String outputSampleDataFile = prop.getProperty(Constant.HDFS_SAMPLE_LOCAL_PATH_KEY); String cluster = prop.getProperty(Constant.HDFS_CLUSTER_KEY); String whiteList = prop.getProperty(Constant.HDFS_WHITE_LIST_KEY); String numOfThread = prop.getProperty(Constant.HDFS_NUM_OF_THREAD_KEY, String.valueOf(1)); String hdfsUser = prop.getProperty(Constant.HDFS_REMOTE_USER_KEY); // String hdfsKeyTab = prop.getProperty(Constant.HDFS_REMOTE_KEYTAB_LOCATION_KEY); String hdfsExtractLogFile = outputSchemaFile + ".log"; String[] hadoopCmd = { "hadoop", "jar", remoteJarFile, "-D" + Constant.HDFS_SCHEMA_REMOTE_PATH_KEY + "=" + outputSchemaFile, "-D" + Constant.HDFS_SAMPLE_REMOTE_PATH_KEY + "=" + outputSampleDataFile, "-D" + Constant.HDFS_CLUSTER_KEY + "=" + cluster, "-D" + Constant.HDFS_WHITE_LIST_KEY + "=" + whiteList, "-D" + Constant.HDFS_NUM_OF_THREAD_KEY + "=" + numOfThread, "-D" + Constant.HDFS_REMOTE_USER_KEY + "=" + hdfsUser, "-Dlog.file.name=hdfs_schema_fetch" }; // delete the line (no kerberos needed): "-D" + Constant.HDFS_REMOTE_KEYTAB_LOCATION_KEY + "=" + hdfsKeyTab, ProcessBuilder pb = new ProcessBuilder(hadoopCmd); File logFile = new File(hdfsExtractLogFile); pb.redirectErrorStream(true); pb.redirectOutput(ProcessBuilder.Redirect.appendTo(logFile)); Process process = pb.start(); int pid = -1; if (process.getClass().getName().equals("java.lang.UNIXProcess")) { /* get the PID on unix/linux systems */ try { Field f = process.getClass().getDeclaredField("pid"); f.setAccessible(true); pid = f.getInt(process); } catch (Throwable e) { } } logger.info("executue command [PID=" + pid + "]: " + hadoopCmd); // wait until this process finished. int execResult = process.waitFor(); // if the process failed, log the error and throw exception if (execResult > 0) { BufferedReader br = new BufferedReader(new InputStreamReader(process.getErrorStream())); String errString = "HDFS Metadata Extract Error:\n"; String line = ""; while ((line = br.readLine()) != null) errString = errString.concat(line).concat("\n"); logger.error("*** Process failed, status: " + execResult); logger.error(errString); throw new Exception("Process + " + pid + " failed"); } }
From source file:net.solarnetwork.node.dao.jdbc.derby.DerbyOnlineSyncJob.java
private void performSync(String dbPath) { assert syncCommand != null; List<String> cmd = new ArrayList<String>(syncCommand.size()); for (String param : syncCommand) { param = param.replace(SOURCE_DIRECTORY_PLACEHOLDER, dbPath); param = param.replace(DESTINATION_DIRECTORY_PLACEHOLDER, destinationPath); cmd.add(param);/*from w ww. ja v a2 s.c o m*/ } if (log.isDebugEnabled()) { StringBuilder buf = new StringBuilder(); for (String p : cmd) { if (buf.length() > 0) { buf.append(' '); } buf.append(p); } log.debug("Derby sync command: {}", buf.toString()); } ProcessBuilder pb = new ProcessBuilder(cmd); BufferedReader in = null; PrintWriter out = null; try { Process pr = pb.start(); pr.waitFor(); if (pr.exitValue() == 0) { if (log.isDebugEnabled()) { in = new BufferedReader(new InputStreamReader(pr.getInputStream())); StringBuilder buf = new StringBuilder(); String line = null; while ((line = in.readLine()) != null) { buf.append(line).append('\n'); } log.debug("Derby sync command output:\n{}", buf.toString()); } log.info("Derby backup sync complete"); } else { StringBuilder buf = new StringBuilder(); in = new BufferedReader(new InputStreamReader(pr.getErrorStream())); String line = null; while ((line = in.readLine()) != null) { buf.append(line).append('\n'); } log.error("Sync command returned non-zero exit code {}: {}", pr.exitValue(), buf.toString().trim()); } } catch (IOException e) { throw new RuntimeException(e); } catch (InterruptedException e) { throw new RuntimeException(e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { // ignore } } if (out != null) { out.flush(); out.close(); } } }
From source file:jeplus.EPlusWinTools.java
public static int runReadVars(EPlusConfig config, String WorkDir, String rvifile, String freq, String csvfile) { int ExitValue = -99; try {//from w w w .jav a 2 s .c om Process EPProc; // Run EnergyPlus ReadVarsESO String CmdLine = config.getResolvedReadVars() + " \"" + rvifile + "\" " + freq + " unlimited"; EPProc = Runtime.getRuntime().exec( new String[] { config.getResolvedReadVars(), rvifile, freq, "unlimited" }, null, new File(WorkDir)); // Console logger try (PrintWriter outs = (config.getScreenFile() == null) ? null : new PrintWriter(new FileWriter(WorkDir + "/" + config.getScreenFile(), true));) { if (outs != null) { outs.println("# Calling ReadVarsESO - " + (new SimpleDateFormat()).format(new Date())); outs.println("# Command line: " + WorkDir + ">" + CmdLine); outs.flush(); } StreamPrinter p_out = new StreamPrinter(EPProc.getInputStream(), "OUTPUT", outs); StreamPrinter p_err = new StreamPrinter(EPProc.getErrorStream(), "ERROR"); p_out.start(); p_err.start(); ExitValue = EPProc.waitFor(); p_out.join(); p_err.join(); // Copy the result file (eplusout.csv) to the target csv file name File csv = new File(WorkDir + EPlusConfig.getEPDefOutCSV()); boolean ok = false; // Clear the existing output csv file File csvout = new File(WorkDir + csvfile); if (csvout.exists()) csvout.delete(); // Rename the new csv to the output csv if (csv.exists() && csv.renameTo(csvout)) { ok = true; } if (outs != null) { outs.println("# ReadVarsESO returns: " + ExitValue); outs.println(ok ? csv.getPath() + " renamed to " + csvfile : "Processing " + rvifile + " has failed."); outs.flush(); } } // set it to successful ExitValue = 0; } catch (IOException | InterruptedException ex) { logger.error("Error executing ReadVars.", ex); } return ExitValue; }
From source file:com.xpn.xwiki.plugin.graphviz.GraphVizPlugin.java
/** * Executes GraphViz, writes the resulting image (in the requested format) in a temporary file on disk, and returns * the generated content from that file. * /*from ww w .j ava 2 s . co m*/ * @param hashCode the hascode of the content, to be used as the temporary file name * @param content the dot source code * @param extension the output file extension * @param dot which engine to execute: {@code dot} if {@code true}, {@code neato} if {@code false} * @return the content of the generated file * @throws IOException if writing the input or output files to the disk fails, or if writing the response body fails */ private byte[] getDotImage(int hashCode, String content, String extension, boolean dot) throws IOException { File dfile = getTempFile(hashCode, "input.dot", dot); if (!dfile.exists()) { FileUtils.write(dfile, content, XWiki.DEFAULT_ENCODING); } File ofile = getTempFile(hashCode, extension, dot); if (!ofile.exists()) { Runtime rt = Runtime.getRuntime(); String[] command = new String[5]; command[0] = dot ? this.dotPath : this.neatoPath; command[1] = "-T" + extension; command[2] = dfile.getAbsolutePath(); command[3] = "-o"; command[4] = ofile.getAbsolutePath(); Process p = rt.exec(command); int exitValue = -1; final Thread thisThread = Thread.currentThread(); Thread t = new Thread(new Hangcheck(thisThread), "dot-hangcheck"); t.run(); try { exitValue = p.waitFor(); t.interrupt(); } catch (InterruptedException ex) { p.destroy(); LOGGER.error("Timeout while generating image from dot", ex); } if (exitValue != 0) { LOGGER.error("Error while generating image from dot: " + IOUtils.toString(p.getErrorStream(), XWiki.DEFAULT_ENCODING)); } } return FileUtils.readFileToByteArray(ofile); }