List of usage examples for java.lang Process getInputStream
public abstract InputStream getInputStream();
From source file:eu.stratosphere.nephele.instance.HardwareDescriptionFactory.java
/** * Returns the size of the physical memory in bytes on Windows. * /*w w w . j av a2 s . c om*/ * @return the size of the physical memory in bytes or <code>-1</code> if * the size could not be determined */ private static long getSizeOfPhysicalMemoryForWindows() { BufferedReader bi = null; try { Process proc = Runtime.getRuntime().exec("wmic memorychip get capacity"); bi = new BufferedReader(new InputStreamReader(proc.getInputStream())); String line = bi.readLine(); if (line == null) { return -1L; } if (!line.startsWith("Capacity")) { return -1L; } long sizeOfPhyiscalMemory = 0L; while ((line = bi.readLine()) != null) { if (line.isEmpty()) { continue; } line = line.replaceAll(" ", ""); sizeOfPhyiscalMemory += Long.parseLong(line); } return sizeOfPhyiscalMemory; } catch (Exception e) { LOG.error("Cannot determine the size of the physical memory using 'wmic memorychip': " + e.getMessage(), e); return -1L; } finally { if (bi != null) { try { bi.close(); } catch (Throwable t) { } } } }
From source file:Main.java
public static String runScript(String script) { String sRet = ""; try {// w w w . ja va 2 s . co m final Process m_process = Runtime.getRuntime().exec(script); final StringBuilder sbread = new StringBuilder(); Thread tout = new Thread(new Runnable() { public void run() { BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(m_process.getInputStream()), 8192); String ls_1 = null; try { while ((ls_1 = bufferedReader.readLine()) != null) { sbread.append(ls_1).append("\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } } }); tout.start(); final StringBuilder sberr = new StringBuilder(); Thread terr = new Thread(new Runnable() { public void run() { BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(m_process.getErrorStream()), 8192); String ls_1 = null; try { while ((ls_1 = bufferedReader.readLine()) != null) { sberr.append(ls_1).append("\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } } }); terr.start(); // int retvalue = m_process.waitFor(); while (tout.isAlive()) { Thread.sleep(50); } if (terr.isAlive()) terr.interrupt(); String stdout = sbread.toString(); String stderr = sberr.toString(); sRet = stdout + stderr; } catch (Exception e) { e.printStackTrace(); return null; } return sRet; }
From source file:net.pickapack.io.cmd.CommandLineHelper.java
/** * * @param cmd// w w w . ja v a 2 s .c om * @return */ public static List<String> invokeNativeCommandAndGetResult(String[] cmd) { List<String> outputList = new ArrayList<String>(); try { Runtime r = Runtime.getRuntime(); Process ps = r.exec(cmd); // ProcessBuilder pb = new ProcessBuilder(cmd); // pb.redirectErrorStream(true); // Process ps = pb.start(); BufferedReader rdr = new BufferedReader(new InputStreamReader(ps.getInputStream())); String in = rdr.readLine(); while (in != null) { outputList.add(in); in = rdr.readLine(); } int exitValue = ps.waitFor(); if (exitValue != 0) { System.out.println("WARN: Process exits with non-zero code: " + exitValue); } ps.destroy(); } catch (Exception e) { e.printStackTrace(); } return outputList; }
From source file:Main.java
public static String runScript(String script) { String sRet = ""; try {/*from w ww. j ava 2s .c o m*/ final Process m_process = Runtime.getRuntime().exec(script); final StringBuilder sbread = new StringBuilder(); Thread tout = new Thread(new Runnable() { public void run() { BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(m_process.getInputStream()), 8192); String ls_1 = null; try { while ((ls_1 = bufferedReader.readLine()) != null) { sbread.append(ls_1).append("\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } } }); tout.start(); final StringBuilder sberr = new StringBuilder(); Thread terr = new Thread(new Runnable() { public void run() { BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(m_process.getErrorStream()), 8192); String ls_1 = null; try { while ((ls_1 = bufferedReader.readLine()) != null) { sberr.append(ls_1).append("\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } } }); terr.start(); int retvalue = m_process.waitFor(); while (tout.isAlive()) { Thread.sleep(50); } if (terr.isAlive()) terr.interrupt(); String stdout = sbread.toString(); String stderr = sberr.toString(); sRet = stdout + stderr; } catch (Exception e) { e.printStackTrace(); return null; } return sRet; }
From source file:com.dtolabs.rundeck.core.utils.ScriptExecUtil.java
/** * Run a command with environment variables in a working dir, and copy the streams * * @param command the command array to run * @param envMap the environment variables to pass in * @param workingdir optional working dir location (or null) * @param outputStream stream for stdout * @param errorStream stream for stderr * * @return the exit code of the command//from w w w.j a v a2 s. c om * * @throws IOException if any IO exception occurs * @throws InterruptedException if interrupted while waiting for the command to finish */ public static int runLocalCommand(final String[] command, final Map<String, String> envMap, final File workingdir, final OutputStream outputStream, final OutputStream errorStream) throws IOException, InterruptedException { final String[] envarr = createEnvironmentArray(envMap); final Runtime runtime = Runtime.getRuntime(); final Process exec = runtime.exec(command, envarr, workingdir); final Streams.StreamCopyThread errthread = Streams.copyStreamThread(exec.getErrorStream(), errorStream); final Streams.StreamCopyThread outthread = Streams.copyStreamThread(exec.getInputStream(), outputStream); errthread.start(); outthread.start(); exec.getOutputStream().close(); final int result = exec.waitFor(); errthread.join(); outthread.join(); if (null != outthread.getException()) { throw outthread.getException(); } if (null != errthread.getException()) { throw errthread.getException(); } return result; }
From source file:com.modelon.oslc.adapter.fmi.integration.FMUConnector.java
public static FMU loadSingleFMU(String fmuInterfaceCMDPath, String fmuPath, String unzipTempDir) throws IOException { File cmd = new File(fmuInterfaceCMDPath); File fmu = new File(fmuPath); File fmuTempDir = new File(unzipTempDir + File.separator + fmu.getName()); fmuTempDir.mkdirs();/* w ww. j a v a 2 s . c o m*/ try { ProcessBuilder builder = new ProcessBuilder(cmd.getPath(), "read", fmu.getPath(), fmuTempDir.getPath()); builder.redirectErrorStream(true); Process p = builder.start(); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); StringBuilder sbuilder = new StringBuilder(); String aux = ""; while ((aux = reader.readLine()) != null) { aux = aux.replaceAll("\\\\", "\\\\\\\\"); aux += "\r\n"; sbuilder.append(aux); } String json = sbuilder.toString(); ObjectMapper mapper = new ObjectMapper(); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); FMU fmuObject = mapper.readValue(json, FMU.class); if (fmuObject.fmiVersion != null) return mapper.readValue(json, FMU.class); else return null; } catch (Exception e) { e.printStackTrace(); return null; } }
From source file:io.hops.hopsworks.common.security.PKIUtils.java
public static String getSubjectFromCSR(String csr) throws IOException, InterruptedException { File csrFile = File.createTempFile(System.getProperty("java.io.tmpdir"), ".csr"); FileUtils.writeStringToFile(csrFile, csr); List<String> cmds = new ArrayList<>(); //openssl req -in certs-dir/hops-site-certs/csr.pem -noout -subject cmds.add("openssl"); cmds.add("req"); cmds.add("-in"); cmds.add(csrFile.getAbsolutePath()); cmds.add("-noout"); cmds.add("-subject"); StringBuilder sb = new StringBuilder("/usr/bin/ "); for (String s : cmds) { sb.append(s).append(" "); }//from www .j av a 2 s. co m logger.info(sb.toString()); Process process = new ProcessBuilder(cmds).directory(new File("/usr/bin/")).redirectErrorStream(true) .start(); BufferedReader br = new BufferedReader( new InputStreamReader(process.getInputStream(), Charset.forName("UTF8"))); String line; StringBuilder lines = new StringBuilder(""); while ((line = br.readLine()) != null) { logger.info(line); lines.append(line); } process.waitFor(); int exitValue = process.exitValue(); if (exitValue != 0) { throw new RuntimeException("Failed to get subject. Exit value: " + exitValue); } return lines.toString(); }
From source file:io.hops.hopsworks.common.security.PKIUtils.java
public static String getSerialNumberFromCert(String cert) throws IOException, InterruptedException { File csrFile = File.createTempFile(System.getProperty("java.io.tmpdir"), ".pem"); FileUtils.writeStringToFile(csrFile, cert); List<String> cmds = new ArrayList<>(); //openssl x509 -in certs-dir/hops-site-certs/pub.pem -noout -serial cmds.add("openssl"); cmds.add("x509"); cmds.add("-in"); cmds.add(csrFile.getAbsolutePath()); cmds.add("-noout"); cmds.add("-serial"); StringBuilder sb = new StringBuilder("/usr/bin/ "); for (String s : cmds) { sb.append(s).append(" "); }//from ww w . j ava 2 s. c o m logger.info(sb.toString()); Process process = new ProcessBuilder(cmds).directory(new File("/usr/bin/")).redirectErrorStream(true) .start(); BufferedReader br = new BufferedReader( new InputStreamReader(process.getInputStream(), Charset.forName("UTF8"))); String line; StringBuilder lines = new StringBuilder(""); while ((line = br.readLine()) != null) { logger.info(line); lines.append(line); } process.waitFor(); int exitValue = process.exitValue(); if (exitValue != 0) { throw new RuntimeException("Failed to get Serial Number. Exit value: " + exitValue); } return lines.toString(); }
From source file:org.cloudifysource.azure.AbstractCliAzureDeploymentTest.java
public static String runCliCommands(File cliExecutablePath, List<List<String>> commands, boolean isDebug) throws IOException, InterruptedException { if (!cliExecutablePath.isFile()) { throw new IllegalArgumentException(cliExecutablePath + " is not a file"); }// w w w . j ava 2s. co m File workingDirectory = cliExecutablePath.getAbsoluteFile().getParentFile(); if (!workingDirectory.isDirectory()) { throw new IllegalArgumentException(workingDirectory + " is not a directory"); } int argsCount = 0; for (List<String> command : commands) { argsCount += command.size(); } // needed to properly intercept error return code String[] cmd = new String[(argsCount == 0 ? 0 : 1) + 4 /* cmd /c call cloudify.bat ["args"] */]; int i = 0; cmd[i] = "cmd"; i++; cmd[i] = "/c"; i++; cmd[i] = "call"; i++; cmd[i] = cliExecutablePath.getAbsolutePath(); i++; if (argsCount > 0) { cmd[i] = "\""; //TODO: Use StringBuilder for (List<String> command : commands) { if (command.size() > 0) { for (String arg : command) { if (cmd[i].length() > 0) { cmd[i] += " "; } cmd[i] += arg; } cmd[i] += ";"; } } cmd[i] += "\""; } final ProcessBuilder pb = new ProcessBuilder(cmd); pb.directory(workingDirectory); pb.redirectErrorStream(true); String extCloudifyJavaOptions = ""; if (isDebug) { extCloudifyJavaOptions += "-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=9000 -Xnoagent -Djava.compiler=NONE"; } pb.environment().put("EXT_CLOUDIFY_JAVA_OPTIONS", extCloudifyJavaOptions); final StringBuilder sb = new StringBuilder(); logger.info("running: " + cliExecutablePath + " " + Arrays.toString(cmd)); // log std output and redirected std error Process p = pb.start(); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = reader.readLine(); while (line != null) { sb.append(line).append('\n'); line = reader.readLine(); logger.info(line); } final String readResult = sb.toString(); final int exitValue = p.waitFor(); logger.info("Exit value = " + exitValue); if (exitValue != 0) { Assert.fail("Cli ended with error code: " + exitValue); } return readResult; }
From source file:org.ambientdynamix.web.WebUtils.java
private static List<UidPortMapping> getUidPortMappings(String path) { // Create a return List of mappings List<UidPortMapping> mappings = new ArrayList<WebUtils.UidPortMapping>(); try {/*from ww w.j a v a 2s . c om*/ // Try to 'cat' the path java.lang.Process proc = Runtime.getRuntime().exec(new String[] { "cat", path }); // Create a reader for the proc's input stream BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()), 8192); String line = null; // Parse each line of the file while ((line = reader.readLine()) != null) { // Make sure we're not parsing a header if (!line.contains("local_address")) { // Replace multiple spaces with single spaces String clean = line.trim().replaceAll(" +", " "); // Split the clean string into tokens String[] tokens = clean.split(" "); // Token 1 is the 'local_address' String[] localAdd = tokens[1].split(":"); // Token 7 is the 'uid' String uid = tokens[7]; // Add the UidPortMapping mappings.add(new UidPortMapping(Integer.parseInt(uid), Integer.parseInt(localAdd[1], 16))); } } } catch (Exception e) { Log.w(TAG, e); } return mappings; }