private Integer startTunnelSSH(Instance instance) throws InterruptedException { Instance tunnelInstance = runningInstances(tunnelResourceId).get(0); Integer localPort = Double.valueOf(Randoms.number(3000, 10000)).intValue(); CountDownLatch latch = new CountDownLatch(1); Thread tunnelThread = new Thread( () -> { Process process = null; try { Path keyPath = KeyPair.keyFile(tunnelInstance.getKeyName(), env); String userAndHost = "ubuntu@" + hostName(tunnelInstance); String portBinding = Strings.format("{}:{}:22", localPort, instance.getPrivateIpAddress()); List<String> command = tunnelCommand(keyPath, userAndHost, portBinding); logger.info("tunnel command => {}", String.join(" ", command)); process = new ProcessBuilder().command(command).start(); process.getInputStream().read(); // wait until there is output latch.countDown(); process.waitFor(); } catch (InterruptedException | IOException e) { throw new IllegalStateException(e); } finally { if (process != null) process.destroy(); } }); tunnelThread.setDaemon(true); tunnelThread.start(); latch.await(); return localPort; }
public static int RefreshDatabase() { if (ERROR == SendHttp("http://" + HOST + ":" + REST_PORT + "/" + DATABASEINDEX, REQ_DELETE)) { System.out.println(PROMPT + "Delete log database index failed!"); return ERROR; } if (ERROR == SendHttp("http://" + HOST + ":" + REST_PORT + "/" + DATABASEINDEX, REQ_PUT)) { System.out.println(PROMPT + "Create log database index failed!"); return ERROR; } // Set mapping manually try { String cmd = "curl -XPUT " + HOST + ':' + REST_PORT + "/" + DATABASEINDEX + '/' + DATABASETYPE + "/_mapping --data-binary @./data/Log/map.json"; Process ps = Runtime.getRuntime().exec(cmd); ps.waitFor(); BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream())); String line; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (Exception e) { e.printStackTrace(); return ERROR; } return SUCCESS; }
/** this void method runs the command created in the constructor. */ public void runTesseract() { LOGGER.info( "Trying to run command: " + command[0] + " " + command[1] + " " + command[2] + " " + command[3] + " " + command[4]); System.out.println("Trying to run command: " + Arrays.toString(command)); try { Runtime rt = Runtime.getRuntime(); Process pr = rt.exec(command); BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream())); String line; while ((line = input.readLine()) != null) { System.out.println(line); } int exitVal = pr.waitFor(); System.out.println("Exited with error code " + exitVal); } catch (Exception e) { System.out.println(e.toString()); e.printStackTrace(); } }
public String getLauncherDetails(String prefix) { try { final String javaVersionCommand = javaCommand + " -version"; Process proc = Runtime.getRuntime().exec(javaVersionCommand); try { InputStream inputStream = proc.getErrorStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line = null; StringBuffer buffer = new StringBuffer(); while ((line = reader.readLine()) != null) { buffer.append(prefix); buffer.append(line); buffer.append('\n'); } return buffer.toString(); } finally { proc.destroy(); } } catch (Exception e) { throw new RuntimeException(e); } }
/** * Gets the token. * * @param scope the scope * @return the token */ private String getToken(String scope) { Process curlProc; String outputString; DataInputStream curlIn = null; String access_token = null; String command = "curl -X POST -H Content-Type:application/x-www-form-urlencoded " + adminUrl + "/oauth2/token --insecure --data" + " client_id=" + client_id + "&" + "client_secret=" + client_secret + "&grant_type=client_credentials&scope=" + scope; try { curlProc = Runtime.getRuntime().exec(command); curlIn = new DataInputStream(curlProc.getInputStream()); while ((outputString = curlIn.readLine()) != null) { JSONObject obj = new JSONObject(outputString); access_token = obj.getString("access_token"); } } catch (IOException e1) { e1.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return access_token; }
public static void main(String[] args) { TestReport pdfReport = new TestReport(); String reportName = "c://reportFileName.pdf"; pdfReport.setPrintDate("101/02/20 16:43:32"); pdfReport.setReportFileName(reportName); pdfReport.setFontPath("c:/windows/fonts/KAIU.TTF"); pdfReport.setReportSize(PDFReport.REPORTSIZE_A4_LANDSCAPE); pdfReport.setPosition(10); pdfReport.setOfficeName("內政部"); pdfReport.doReport(); try { System.out.println("##### == " + getPath()); File file = new File(reportName); System.out.println("reportName === " + file.getAbsolutePath()); Process pr = Runtime.getRuntime().exec("cmd /c " + reportName); pr.waitFor(); System.out.println("reportend"); // 刪除列印檔案 file.delete(); } catch (IOException e1) { e1.printStackTrace(); } catch (InterruptedException e1) { e1.printStackTrace(); } System.out.println("done..."); }
public SerialPort(File device, int baudrate, int flags) throws SecurityException, IOException { /* Check access permission */ if (!device.canRead() || !device.canWrite()) { try { /* Missing read/write permission, trying to chmod the file */ Process su; su = Runtime.getRuntime().exec("/system/bin/su"); String cmd = "chmod 666 " + device.getAbsolutePath() + "\n" + "exit\n"; su.getOutputStream().write(cmd.getBytes()); if ((su.waitFor() != 0) || !device.canRead() || !device.canWrite()) { throw new SecurityException(); } } catch (Exception e) { e.printStackTrace(); throw new SecurityException(); } } mFd = open(device.getAbsolutePath(), baudrate, flags); if (mFd == null) { Log.e(TAG, "native open returns null"); throw new IOException(); } mFileInputStream = new FileInputStream(mFd); mFileOutputStream = new FileOutputStream(mFd); mDevPath = device.getAbsolutePath(); }
private void writeLogcat(String name) { CharSequence timestamp = DateFormat.format("yyyyMMdd_kkmmss", System.currentTimeMillis()); String filename = name + "_" + timestamp + ".log"; String[] args = {"logcat", "-v", "time", "-d"}; try { Process process = Runtime.getRuntime().exec(args); InputStreamReader input = new InputStreamReader(process.getInputStream()); OutputStreamWriter output = new OutputStreamWriter(new FileOutputStream(filename)); BufferedReader br = new BufferedReader(input); BufferedWriter bw = new BufferedWriter(output); String line; while ((line = br.readLine()) != null) { bw.write(line); bw.newLine(); } bw.close(); output.close(); br.close(); input.close(); } catch (IOException e) { e.printStackTrace(); } }
/** * Execute the given command and optionally wait and dump the results to standard out * * @param args command and arguments * @param wait true =wait for either completion or timeout time and dump output, false don't wait * and ignore the output. * @exception Exception */ private static void execCmdDumpResults(String[] args, boolean wait) throws Exception { // We need the process inputstream and errorstream ProcessStreamResult prout = null; ProcessStreamResult prerr = null; System.out.flush(); bos.flush(); BufferedOutputStream _bos = bos; if (!wait) { // not interested in the output, don't expect a huge amount. // information will just be written to the byte array in // memory and never used. _bos = new BufferedOutputStream(new ByteArrayOutputStream()); } // Start a process to run the command Process pr = execCmd(args); // Note, the timeout handling will only come into effect when we make // the Wait() call on ProcessStreamResult. prout = new ProcessStreamResult(pr.getInputStream(), _bos, timeoutMinutes); prerr = new ProcessStreamResult(pr.getErrorStream(), _bos, timeoutMinutes); if (!wait) return; // wait until all the results have been processed or if we timed out prout.Wait(); prerr.Wait(); _bos.flush(); System.out.flush(); }
public String execRecognizer() { try { String inputFile = new File(tmpdir, "input").getAbsolutePath(); String[] args = new String[] {"java", "-classpath", tmpdir + pathSep + CLASSPATH, "Test", inputFile}; // String cmdLine = "java -classpath "+CLASSPATH+pathSep+tmpdir+" Test " + new File(tmpdir, // "input").getAbsolutePath(); // System.out.println("execParser: "+cmdLine); Process process = Runtime.getRuntime().exec(args, null, new File(tmpdir)); StreamVacuum stdoutVacuum = new StreamVacuum(process.getInputStream()); StreamVacuum stderrVacuum = new StreamVacuum(process.getErrorStream()); stdoutVacuum.start(); stderrVacuum.start(); process.waitFor(); stdoutVacuum.join(); stderrVacuum.join(); String output = null; output = stdoutVacuum.toString(); if (stderrVacuum.toString().length() > 0) { this.stderrDuringParse = stderrVacuum.toString(); System.err.println("exec stderrVacuum: " + stderrVacuum); } return output; } catch (Exception e) { System.err.println("can't exec recognizer"); e.printStackTrace(System.err); } return null; }
/** * Creates new symbolic file system link from file or folder to another filesystem file. The * target path has to be present on disk. * * @param linkPath - filesystem path of the link being created. * @param realPath - file or folder on the file system, the target of the link. * @throws UnsupportedOperationException on Windows where links are not supported. * @throws IOException if execution of the command fails. */ public static void createSymbolicLink(IPath linkPath, IPath realPath) throws IOException { if (!isSymbolicLinkSupported()) { throw new UnsupportedOperationException("Windows links .lnk are not supported."); } String command = "ln -s " + realPath.toOSString() + ' ' + linkPath.toOSString(); Process process = Runtime.getRuntime().exec(command); // Wait for up to 2.5s... for (int i = 0; i < 5; i++) { try { Assert.assertTrue("ln process exited with non-zero status", process.waitFor() == 0); // If exitValue succeeded, then the process has exitted successfully. break; } catch (InterruptedException e) { // Clear interrupted state, see Java bug http://bugs.sun.com/view_bug.do?bug_id=6420270 Thread.interrupted(); } // wait for a 500ms before checking again try { Thread.sleep(500); } catch (InterruptedException e) { /*don't care*/ } } Assert.assertTrue( "Symbolic link not created, command=[" + command + "]", linkPath.toFile().exists()); }
/** 读取当前网速 */ public static long getNetSpeed() { ProcessBuilder cmd; long readBytes = 0; BufferedReader rd = null; try { String[] args = {"/system/bin/cat", "/proc/net/dev"}; cmd = new ProcessBuilder(args); Process process = cmd.start(); rd = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; // int linecount = 0; while ((line = rd.readLine()) != null) { // linecount++; if (line.contains("lan0") || line.contains("eth0")) { String[] delim = line.split(":"); if (delim.length >= 2) { readBytes = parserNumber(delim[1].trim()); break; } } } rd.close(); } catch (Exception ex) { ex.printStackTrace(); } finally { if (rd != null) { try { rd.close(); } catch (IOException e) { e.printStackTrace(); } } } return readBytes; }
private String getSDKProperties(String javaPath, String path) throws IOException { Runtime runtime = Runtime.getRuntime(); try { String[] command = new String[5]; command[0] = javaPath; command[1] = "-classpath"; // NOI18N command[2] = InstalledFileLocator.getDefault() .locate( "modules/ext/org-netbeans-modules-visage-platform-probe.jar", "org.netbeans.modules.visage.platform", false) .getAbsolutePath(); // NOI18N command[3] = "org.netbeans.modules.visage.platform.wizard.SDKProbe"; // NOI18N command[4] = path; final Process process = runtime.exec(command); // PENDING -- this may be better done by using ExecEngine, since // it produces a cancellable task. process.waitFor(); int exitValue = process.exitValue(); if (exitValue != 0) throw new IOException(); return command[2]; } catch (InterruptedException ex) { IOException e = new IOException(); ErrorManager.getDefault().annotate(e, ex); throw e; } }
public String execSu(String cmd) { Log.d(TAG, "^ Executing as SU '" + cmd + "'"); try { Process process = Runtime.getRuntime().exec("su"); DataInputStream is = new DataInputStream(process.getInputStream()); DataOutputStream os = new DataOutputStream(process.getOutputStream()); os.writeBytes(cmd + "\n"); os.writeBytes("exit\n"); os.flush(); os.close(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); try { String fullOutput = ""; String line; while ((line = reader.readLine()) != null) { fullOutput = fullOutput + line + "\n"; } return fullOutput; } catch (IOException e) { // It seems IOException is thrown when it reaches EOF. e.printStackTrace(); Log.e(TAG, "^ execSU, IOException 1"); } process.waitFor(); } catch (IOException e) { e.printStackTrace(); Log.e(TAG, "^ execSU, IOException 2"); } catch (InterruptedException e) { e.printStackTrace(); Log.e(TAG, "^ execSU, InterruptedException"); } return ""; }
/** * Change local file's permission. * * @param filePath that will change permission * @param perms the permission, e.g. "775" * @throws IOException */ public static void changeLocalFilePermission(String filePath, String perms) throws IOException { // TODO switch to java's Files.setPosixFilePermissions() if java 6 support is dropped List<String> commands = new ArrayList<String>(); commands.add("/bin/chmod"); commands.add(perms); File file = new File(filePath); commands.add(file.getAbsolutePath()); try { ProcessBuilder builder = new ProcessBuilder(commands); Process process = builder.start(); process.waitFor(); redirectIO(process); if (process.exitValue() != 0) { throw new IOException( "Can not change the file " + file.getAbsolutePath() + " 's permission to be " + perms); } } catch (InterruptedException e) { LOG.error(e.getMessage()); throw new IOException(e); } }
private ProBInstance startProlog() { ProcessHandle processTuple = processProvider.get(); Process process = processTuple.getProcess(); String key = processTuple.getKey(); final BufferedReader stream = new BufferedReader( new InputStreamReader(process.getInputStream(), Charset.defaultCharset())); Map<Class<? extends AbstractCliPattern<?>>, AbstractCliPattern<?>> cliInformation = extractCliInformation(stream); Integer port = ((PortPattern) cliInformation.get(PortPattern.class)).getValue(); Long userInterruptReference = ((InterruptRefPattern) cliInformation.get(InterruptRefPattern.class)).getValue(); ProBConnection connection = new ProBConnection(key, port); try { processCounter.incrementAndGet(); connection.connect(); ProBInstance cli = new ProBInstance( process, stream, userInterruptReference, connection, home, osInfo, processCounter); processes.add(new WeakReference<ProBInstance>(cli)); return cli; } catch (IOException e) { processCounter.decrementAndGet(); logger.error("Error connecting to Prolog binary.", e); return null; } }
public static String getSDCardPath() { String cmd = "cat /proc/mounts"; Runtime run = Runtime.getRuntime(); // 返回与当前 Java 应用程序相关的运行时对象 try { Process p = run.exec(cmd); // 启动另一个进程来执行命令 BufferedInputStream in = new BufferedInputStream(p.getInputStream()); BufferedReader inBr = new BufferedReader(new InputStreamReader(in)); String lineStr; while ((lineStr = inBr.readLine()) != null) { // 获得命令执行后在控制台的输出信息 // Log.i("CommonUtil:getSDCardPath", lineStr); if (lineStr.contains("sdcard") && lineStr.contains(".android_secure")) { String[] strArray = lineStr.split(" "); if (strArray != null && strArray.length >= 5) { String result = strArray[1].replace("/.android_secure", ""); return result; } } // 检查命令是否执行失败。 if (p.waitFor() != 0 && p.exitValue() == 1) { // p.exitValue()==0表示正常结束,1:非正常结束 Log.e("CommonUtil:getSDCardPath", "命令执行失败!"); } } inBr.close(); in.close(); } catch (Exception e) { // Log.e("CommonUtil:getSDCardPath", e.toString()); return Environment.getExternalStorageDirectory().getPath(); } return Environment.getExternalStorageDirectory().getPath(); }
public static void main(String[] args) { try { String ls_1; Process process = null; // File handle = new File("../tmp/ctb_v1/data"); File handle = new File("../tmp/ctb_v6/data/bracketed"); BufferedWriter bout = new BufferedWriter( new OutputStreamWriter(new FileOutputStream("../tmp/malt.train"), "UTF-8")); for (File sub : Arrays.asList(handle.listFiles())) { String file = sub.getAbsolutePath(); if (!file.endsWith(".fid")) continue; clean(file); process = Runtime.getRuntime() .exec( "cmd /c java -jar ../tmp/Penn2Malt.jar " + file + " ../tmp/headrules.txt 3 2 chtb"); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); while ((ls_1 = bufferedReader.readLine()) != null) { System.out.println(ls_1); } bufferedReader = new BufferedReader(new InputStreamReader(process.getErrorStream())); while ((ls_1 = bufferedReader.readLine()) != null) { System.out.println(ls_1); } } } catch (IOException e) { System.err.println(e); } }
public void generateDiagram(String outputDirectory, File dotFile) { try { Runtime run = Runtime.getRuntime(); Process pr = run.exec( "dot " + dotFile.getAbsolutePath() + " -Tpng -o" + outputDirectory + FILE_SEPARATOR + "graph.png"); pr.waitFor(); // BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream())); // should the output be really printed? // String line; // while ( ( line = buf.readLine() ) != null ) // { // System.out.println(line) ; // } // FIXME how to handle exceptions in listener? } catch (IOException e) { e .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } catch (InterruptedException e) { e .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } }
/* uses badsource and badsink */ public void bad() throws Throwable { String data; if (privateTrue) { /* get system property user.home */ /* POTENTIAL FLAW: Read data from a system property */ data = System.getProperty("user.home"); } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; } String osCommand; if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) { /* running on Windows */ osCommand = "c:\\WINDOWS\\SYSTEM32\\cmd.exe /c dir "; } else { /* running on non-Windows */ osCommand = "/bin/ls "; } /* POTENTIAL FLAW: command injection */ Process process = Runtime.getRuntime().exec(osCommand + data); process.waitFor(); }
/** * Initializes the xml-rpc communication. * * @param port the port where the communication should happen. * @param process this is the process that was spawned (server for the XML-RPC) * @throws MalformedURLException */ public PydevConsoleCommunication(int port, Process process, int clientPort) throws Exception { stdOutReader = new ThreadStreamReader(process.getInputStream()); stdErrReader = new ThreadStreamReader(process.getErrorStream()); stdOutReader.start(); stdErrReader.start(); // start the server that'll handle input requests this.webServer = new WebServer(clientPort); XmlRpcServer serverToHandleRawInput = this.webServer.getXmlRpcServer(); serverToHandleRawInput.setHandlerMapping( new XmlRpcHandlerMapping() { public XmlRpcHandler getHandler(String handlerName) throws XmlRpcNoSuchHandlerException, XmlRpcException { return PydevConsoleCommunication.this; } }); this.webServer.start(); IXmlRpcClient client = new ScriptXmlRpcClient(process, stdErrReader, stdOutReader); client.setPort(port); this.client = client; }
/* goodG2B1() - use goodsource and badsink by changing privateTrue to privateFalse */ private void goodG2B1() throws Throwable { String data; if (privateFalse) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run * but ensure data is inititialized before the Sink to avoid compiler errors */ data = null; } else { /* FIX: Use a hardcoded string */ data = "foo"; } String osCommand; if (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) { /* running on Windows */ osCommand = "c:\\WINDOWS\\SYSTEM32\\cmd.exe /c dir "; } else { /* running on non-Windows */ osCommand = "/bin/ls "; } /* POTENTIAL FLAW: command injection */ Process process = Runtime.getRuntime().exec(osCommand + data); process.waitFor(); }
public static TByteArrayList transformByExternalCommand( final String command, final InputStream input) throws IOException { final Process process = Runtime.getRuntime().exec(command); final InputStream in = process.getInputStream(); final OutputStream out = process.getOutputStream(); final TByteArrayList bytes = new TByteArrayList(100500); final byte[] buffer = new byte[1024 * 1024]; try { int read; while ((read = input.read(buffer)) > 0) { out.write(buffer, 0, read); if (in.available() > 0) { read = in.read(buffer); bytes.add(buffer, 0, read); } } out.close(); while ((read = in.read(buffer)) > 0) { bytes.add(buffer, 0, read); } in.close(); } catch (IOException ioe) { System.err.println(readByteStream(process.getErrorStream())); LOG.error(ioe); throw ioe; } return bytes; }
/* * Combines audio input with video input at specified time * @see javax.swing.SwingWorker#doInBackground() */ @Override protected Void doInBackground() throws Exception { // Extract the audio from the video and save it as a hidden file in MP3Files String cmd = "ffmpeg -y -i " + videoPath + " -map 0:1 ./MP3Files/.vidAudio.mp3"; ProcessBuilder builder = new ProcessBuilder("/bin/bash", "-c", cmd); Process process = builder.start(); process.waitFor(); for (int i = 1; i < 25; i++) { // Update progress bar when above process is complete Thread.sleep(40); progress.updateProgress(i); } if (time == 0) { // Create a hidden mp3 file output.mp3 that combines the video audio and selected mp3 audio at // time 0 cmd = "ffmpeg -y -i " + audioPath + " -i ./MP3Files/.vidAudio.mp3 -filter_complex amix=inputs=2 ./MP3Files/.output.mp3"; } else { // Create a hidden mp3 file output.mp3 that combines the video audio and selected mp3 audio at // specified time cmd = "ffmpeg -y -i " + audioPath + " -i ./MP3Files/.vidAudio.mp3 -filter_complex \"[0:0]adelay=" + time + "[aud1];[aud1][1:0]amix=inputs=2\" ./MP3Files/.output.mp3"; } builder = new ProcessBuilder("/bin/bash", "-c", cmd); process = builder.start(); process.waitFor(); for (int i = 1; i < 50; i++) { // Update progress bar Thread.sleep(40); progress.updateProgress(25 + i); } // Creates an output.avi file from merging existing video stream (1:0) and combined audio (0:0) cmd = "ffmpeg -i " + videoPath + " -i ./MP3Files/.output.mp3 -map 0:0 -map 1:0 -acodec copy -vcodec copy ./VideoFiles/" + name + ".avi"; builder = new ProcessBuilder("/bin/bash", "-c", cmd); process = builder.start(); process.waitFor(); for (int i = 1; i < 25; i++) { // Update progress bar Thread.sleep(40); progress.updateProgress(75 + i); } return null; }
public static String cpuArch() { if (mCPUArch == null) { /** * Email from [email protected] in 2014/06/27 said their new x86 ROM modifies the * android.os.abi to make the Build.CPU_ABI to always return "armeabi-v7a" and recommended * following method to get real CPU arch. */ BufferedReader ibr = null; try { Process process = Runtime.getRuntime().exec("getprop ro.product.cpu.abi"); ibr = new BufferedReader(new InputStreamReader(process.getInputStream())); mCPUArch = ibr.readLine(); } catch (IOException e) { } finally { if (ibr != null) { try { ibr.close(); } catch (IOException e) { } } } if (TextUtils.isEmpty(mCPUArch)) { // if meet something wrong, get cpu arch from android sdk. mCPUArch = Build.CPU_ABI; } } return mCPUArch; }
private static Architecture getUnixArchitecture() { BufferedReader input = null; try { String line; Process proc = Runtime.getRuntime().exec("uname -m"); input = new BufferedReader(new InputStreamReader(proc.getInputStream())); while ((line = input.readLine()) != null) { if (line.length() > 0) { if (line.contains("64")) { return Architecture.x86_64; } } } } catch (Exception e) { throw new OsDetectionException(e); } finally { try { if (input != null) { input.close(); } } catch (Exception ignored) { // ignore } } return Architecture.x86; }
private void serve(InputStream sis, OutputStream sos) throws IOException { // kills the process if client closes the stream; // closes the stream if process is terminated/ended output. // therefore we need the interruption mechanism. Process process = Runtime.getRuntime().exec("bash"); InputStream pis = process.getInputStream(); InputStream pes = process.getErrorStream(); OutputStream pos = process.getOutputStream(); try { threads.add(new CopyThread(pis, sos)); threads.add(new CopyThread(pes, sos)); threads.add(new CopyThread(sis, pos)); threads.add( new InterruptibleThread() { protected void run0() throws InterruptedException { process.waitFor(); } }); Util.startJoin(threads); } finally { process.destroy(); } }
private static Architecture getMacOSXArchitecture() { BufferedReader input = null; try { String line; Process proc = Runtime.getRuntime().exec("sysctl hw"); input = new BufferedReader(new InputStreamReader(proc.getInputStream())); while ((line = input.readLine()) != null) { if (line.length() > 0) { if ((line.contains("cpu64bit_capable")) && (line.trim().endsWith("1"))) { return Architecture.x86_64; } } } } catch (Exception e) { throw new OsDetectionException(e); } finally { try { if (input != null) { input.close(); } } catch (Exception ignored) { // ignore } } return Architecture.x86; }
// Java Client for GeoNames Webservices private String getPhysicalPlaceOnGeonames(double lat, double lng) { String sPlaceName = ""; String sGeoNameId = ""; String hostname = "www.geonames.org"; try { Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 " + hostname); int returnVal = p1.waitFor(); boolean reachable = (returnVal == 0); if (reachable) { WebService.setUserName("betaas"); PostalCodeSearchCriteria postalCodeSearchCriteria = new PostalCodeSearchCriteria(); postalCodeSearchCriteria.setLatitude(lat); postalCodeSearchCriteria.setLongitude(lng); List<Toponym> placeNames = WebService.findNearbyPlaceName(lat, lng); for (int i = 0; i < placeNames.size(); i++) { sGeoNameId = String.valueOf(placeNames.get(i).getGeoNameId()); sPlaceName = "<" + PREFIX_GEONAMES + sGeoNameId + ">"; } } // else // mLogger.info("[CM] Adaptation Context Manager, Geonames function. Service " + // hostname + " unavailable."); } catch (Exception e) { // mLogger // .error("[CM] Adaptation Context Manager, Geonames function. It has not been // executed correctly. Probably there is not Internet connection."); } return sPlaceName; }
public static String runFile(final Project project, String filePath) { String result = ""; try { String path = new File(filePath).getPath().replaceFirst("file:\\\\", ""); if (Utils.debug) { Utils.print("running: perl " + "\"" + path + "\""); } String cmd = ((project == null) ? getPerlPath("") : getPerlPath(project)); ; String[] params = {cmd, ((os.equals(os.Windows)) ? "\"" + path + "\"" : path)}; Process p = Runtime.getRuntime().exec(params); BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader err = new BufferedReader(new InputStreamReader(p.getErrorStream())); result = printStream(input); printStream(err); int resultCode = p.waitFor(); if (resultCode != 0) { throw new Exception("Failed to run perl - Code (" + resultCode + ")"); } } catch (Exception e) { e.printStackTrace(); } return result; }