List of usage examples for java.lang Process destroy
public abstract void destroy();
From source file:uk.co.markfrimston.tasktree.TaskTree.java
public void synchronise(MergeConfirmer mergeConfirmer) throws Exception { if (loadUrl == null) { throw new Exception("No load URL defined"); }/*from ww w. ja va 2 s. c om*/ if (saveUrl == null) { throw new Exception("No save URL defined"); } if (mergeCommand == null) { throw new Exception("No merge command defined"); } Long newTimestamp = new Date().getTime(); HttpClient client = new DefaultHttpClient(); DocumentBuilderFactory builderFact = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = builderFact.newDocumentBuilder(); // make load request HttpPost post = new HttpPost(loadUrl); HttpResponse response = client.execute(post); if (response.getStatusLine().getStatusCode() != 200) { throw new Exception("Unexpected load response from server: " + response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase()); } // get timestamp header Header[] tsHeaders = response.getHeaders("Timestamp"); Long timestamp; if (tsHeaders == null || tsHeaders.length < 1) { throw new Exception("Missing timestamp from server"); } try { timestamp = Long.parseLong(tsHeaders[0].getValue()); } catch (NumberFormatException e) { throw new Exception("Invalid timestamp from server \"" + tsHeaders[0].getValue() + "\""); } if (timestamp != 0 && timestamp < lastSyncTime) { throw new Exception("Remote timestamp earlier than local timestamp"); } // parse xml Document doc; try { doc = builder.parse(response.getEntity().getContent()); } catch (Exception e) { throw new Exception("Failed to parse load response from server"); } // if remote version is more up to date if (timestamp > lastSyncTime) { // if local changes made, merge if (unsynchedChanges) { // save local tree save(); // save remote tree to temp file makeFilePath(); FileOutputStream fileStream = new FileOutputStream(filePath + MERGE_FILENAME); writeDocToStream(doc, fileStream); fileStream.close(); // execute merge command to perform merge String commandString = StringUtils.template(mergeCommand, filePath + FILENAME, filePath + MERGE_FILENAME); Process proc = Runtime.getRuntime().exec(commandString); proc.waitFor(); proc.destroy(); if (!mergeConfirmer.confirmMerge()) { throw new Exception("Merge aborted"); } // remove temp file new File(filePath + MERGE_FILENAME).delete(); // load the newly merged local tree load(); } else { // just load xml from remote loadFromDocument(doc); // save to file save(); } } // save back to remote every time, to update remote with new sync timestamp. // write xml to byte array doc = saveToDocument(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); writeDocToStream(doc, baos); baos.close(); // make save request post = new HttpPost(saveUrl); post.addHeader("Timestamp", String.valueOf(newTimestamp)); ByteArrayEntity bare = new ByteArrayEntity(baos.toByteArray()); bare.setContentType("application/xml"); post.setEntity(bare); response = client.execute(post); if (response.getStatusLine().getStatusCode() != 200) { throw new Exception("Unexpected save response from server: " + response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase()); } // server should echo back same xml to confirm Document echoDoc; try { echoDoc = builder.parse(response.getEntity().getContent()); } catch (Exception e) { throw new Exception("Failed to parse save response from server"); } if (!nodesEqual(doc, echoDoc)) { throw new Exception("Bad save response from server"); } unsynchedChanges = false; lastSyncTime = newTimestamp; // save config saveConfig(); }
From source file:org.openmicroscopy.shoola.util.file.TestIOUtil.java
/** * Unzips the file using the command line. Return <code>true</code> * if successful, <code>false</code> otherwise. * // w w w. j a v a 2s . com * @param zip The file to unzip. * @param destDir The destination folder. * @return See above. */ private boolean unzip(File zip, File destDir) { Process p = null; try { List<String> cmds = new ArrayList<String>(); cmds.add("unzip"); cmds.add(zip.getAbsolutePath()); cmds.add("-d"); cmds.add(destDir.getAbsolutePath()); ProcessBuilder pb = new ProcessBuilder(cmds); p = pb.start(); if (p.waitFor() != 0) return false; } catch (Exception e) { return false; } finally { if (p != null) { //just in case. closeStream(p.getErrorStream()); closeStream(p.getInputStream()); p.destroy(); } } return true; }
From source file:org.apache.accumulo.minicluster.MiniAccumuloCluster.java
public void killProcess(ServerType type, ProcessReference proc) throws ProcessNotFoundException, InterruptedException { boolean found = false; switch (type) { case MASTER://www .ja v a2s .c o m if (proc.equals(masterProcess)) { masterProcess.destroy(); masterProcess = null; found = true; } break; case TABLET_SERVER: synchronized (tabletServerProcesses) { for (Process tserver : tabletServerProcesses) { if (proc.equals(tserver)) { tabletServerProcesses.remove(tserver); tserver.destroy(); found = true; break; } } } break; case ZOOKEEPER: if (proc.equals(zooKeeperProcess)) { zooKeeperProcess.destroy(); zooKeeperProcess = null; found = true; } break; case GARBAGE_COLLECTOR: if (proc.equals(gcProcess)) { gcProcess.destroy(); gcProcess = null; found = true; } break; } if (!found) throw new ProcessNotFoundException(); }
From source file:net.sourceforge.vulcan.shell.ShellBuildTool.java
public void buildProject(ProjectConfigDto projectConfig, ProjectStatusDto buildStatus, File logFile, BuildDetailCallback buildDetailCallback) throws BuildFailedException, ConfigException { final String[] arguments = projectPluginConfig.getArguments(); if (arguments.length == 0) { throw new ConfigException("shell.missing.arguments"); }//from ww w . ja v a2 s . c o m final String[] environment = createEnvironment(buildStatus); final File dir = new File(projectConfig.getWorkDir()); final Process process; try { process = execute(arguments, environment, dir); } catch (IOException e) { throw new ConfigException("shell.exec.failure", e, arguments[0], e.getMessage()); } startOutputProcessors(process, logFile, buildDetailCallback); try { final int exitCode = process.waitFor(); if (exitCode != 0) { throw new BuildFailedException("Process ended with exit code " + exitCode, null, exitCode); } } catch (InterruptedException e) { process.destroy(); return; } finally { stopOutputProcessors(); } }
From source file:com.varaneckas.hawkscope.plugins.execute.InputCommandKeyListener.java
/** * Gets synchronous command executor//from ww w . j a v a 2s. c o m * * @param cmd * @return */ private Runnable getSyncExecutor(final String cmd) { return new Runnable() { public void run() { try { final long start = System.currentTimeMillis(); final Process p = Runtime.getRuntime().exec(cmd); new Thread(new Runnable() { public void run() { while (true) { try { p.exitValue(); return; } catch (final Exception e) { //logging would spam } if ((System.currentTimeMillis() - start) > 30000) { p.destroy(); shell.getDisplay().syncExec(new Runnable() { public void run() { output.append("Synchronous process timeout: " + cmd + '\n'); } }); return; } try { Thread.sleep(50L); } catch (final InterruptedException e) { log.warn("Interrupted while executing task:" + cmd, e); } } } }).start(); final InputStream in = p.getInputStream(); int c; while ((c = in.read()) != -1) { output.append(String.valueOf((char) c)); } in.close(); } catch (final Exception e) { output.append(e.getMessage() + '\n'); } } }; }
From source file:org.apache.accumulo.miniclusterImpl.MiniAccumuloClusterImpl.java
/** * Stops Accumulo and Zookeeper processes. If stop is not called, there is a shutdown hook that is * setup to kill the processes. However it's probably best to call stop in a finally block as soon * as possible.// w ww . jav a 2 s . c o m */ @Override public synchronized void stop() throws IOException, InterruptedException { if (executor == null) { // keep repeated calls to stop() from failing return; } MiniAccumuloClusterControl control = getClusterControl(); control.stop(ServerType.GARBAGE_COLLECTOR, null); control.stop(ServerType.MASTER, null); control.stop(ServerType.TABLET_SERVER, null); control.stop(ServerType.ZOOKEEPER, null); // ACCUMULO-2985 stop the ExecutorService after we finished using it to stop accumulo procs if (executor != null) { List<Runnable> tasksRemaining = executor.shutdownNow(); // the single thread executor shouldn't have any pending tasks, but check anyways if (!tasksRemaining.isEmpty()) { log.warn("Unexpectedly had {} task(s) remaining in threadpool for execution when being stopped", tasksRemaining.size()); } executor = null; } if (config.useMiniDFS() && miniDFS != null) miniDFS.shutdown(); for (Process p : cleanup) { p.destroy(); p.waitFor(); } miniDFS = null; }
From source file:com.legstar.protobuf.cobol.ProtoCobol.java
/** * From Google's org.waveprotocol.pst.PstFileDescriptor. * <p/>/*from w w w . jav a 2s. c o m*/ * Will kill a process if it takes too long. * * @param delay how long to wait ( * @param unit the unit of time delay is expressed in * @param process the process to kill */ protected void killProcessAfter(final long delay, final TimeUnit unit, final Process process) { Thread processKiller = new Thread() { @Override public void run() { try { Thread.sleep(unit.toMillis(delay)); process.destroy(); } catch (InterruptedException e) { } } }; processKiller.setDaemon(true); processKiller.start(); }
From source file:com.tw.go.plugin.material.artifactrepository.yum.exec.command.ProcessRunner.java
public ProcessOutput execute(String[] command, Map<String, String> envMap) { ProcessBuilder processBuilder = new ProcessBuilder(command); Process process = null; ProcessOutput processOutput = null;// w ww . j av a2 s .com try { processBuilder.environment().putAll(envMap); process = processBuilder.start(); int returnCode = process.waitFor(); List outputStream = IOUtils.readLines(process.getInputStream()); List errorStream = IOUtils.readLines(process.getErrorStream()); processOutput = new ProcessOutput(returnCode, outputStream, errorStream); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } finally { if (process != null) { closeQuietly(process.getInputStream()); closeQuietly(process.getErrorStream()); closeQuietly(process.getOutputStream()); process.destroy(); } } return processOutput; }
From source file:com.androchill.call411.MainActivity.java
private Phone getHardwareSpecs() { ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE); PhoneBuilder pb = new PhoneBuilder(); pb.setModelNumber(Build.MODEL);/* w w w . j a va 2s .co m*/ pb.setManufacturer(Build.MANUFACTURER); Process p = null; String board_platform = "No data available"; try { p = new ProcessBuilder("/system/bin/getprop", "ro.chipname").redirectErrorStream(true).start(); BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = ""; while ((line = br.readLine()) != null) { board_platform = line; } p.destroy(); } catch (IOException e) { e.printStackTrace(); board_platform = "No data available"; } pb.setProcessor(board_platform); ActivityManager.MemoryInfo mInfo = new ActivityManager.MemoryInfo(); activityManager.getMemoryInfo(mInfo); pb.setRam((int) (mInfo.totalMem / 1048576L)); pb.setBatteryCapacity(getBatteryCapacity()); pb.setTalkTime(-1); pb.setDimensions("No data available"); WindowManager mWindowManager = getWindowManager(); Display mDisplay = mWindowManager.getDefaultDisplay(); Point mPoint = new Point(); mDisplay.getSize(mPoint); pb.setScreenResolution(mPoint.x + " x " + mPoint.y + " pixels"); DisplayMetrics mDisplayMetrics = new DisplayMetrics(); mDisplay.getMetrics(mDisplayMetrics); int mDensity = mDisplayMetrics.densityDpi; pb.setScreenSize( Math.sqrt(Math.pow(mPoint.x / (double) mDensity, 2) + Math.pow(mPoint.y / (double) mDensity, 2))); Camera camera = Camera.open(0); android.hardware.Camera.Parameters params = camera.getParameters(); List sizes = params.getSupportedPictureSizes(); Camera.Size result = null; ArrayList<Integer> arrayListForWidth = new ArrayList<Integer>(); ArrayList<Integer> arrayListForHeight = new ArrayList<Integer>(); for (int i = 0; i < sizes.size(); i++) { result = (Camera.Size) sizes.get(i); arrayListForWidth.add(result.width); arrayListForHeight.add(result.height); } if (arrayListForWidth.size() != 0 && arrayListForHeight.size() != 0) { pb.setCameraMegapixels( Collections.max(arrayListForHeight) * Collections.max(arrayListForWidth) / (double) 1000000); } else { pb.setCameraMegapixels(-1); } camera.release(); pb.setPrice(-1); pb.setWeight(-1); pb.setSystem("Android " + Build.VERSION.RELEASE); StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath()); StatFs statInternal = new StatFs(Environment.getRootDirectory().getAbsolutePath()); double storageSize = ((stat.getBlockSizeLong() * stat.getBlockCountLong()) + (statInternal.getBlockSizeLong() * statInternal.getBlockCountLong())) / 1073741824L; pb.setStorageOptions(storageSize + " GB"); TelephonyManager telephonyManager = ((TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE)); String operatorName = telephonyManager.getNetworkOperatorName(); if (operatorName.length() == 0) operatorName = "No data available"; pb.setCarrier(operatorName); pb.setNetworkFrequencies("No data available"); pb.setImage(null); return pb.createPhone(); }
From source file:android_network.hetnet.vpn_service.Util.java
private static StringBuilder getLogcat() { StringBuilder builder = new StringBuilder(); Process process1 = null;//from w w w. j a va 2 s .c o m Process process2 = null; BufferedReader br = null; try { String[] command1 = new String[] { "logcat", "-d", "-v", "threadtime" }; process1 = Runtime.getRuntime().exec(command1); br = new BufferedReader(new InputStreamReader(process1.getInputStream())); int count = 0; String line; while ((line = br.readLine()) != null) { count++; builder.append(line).append("\r\n"); } Log.i(TAG, "Logcat lines=" + count); } catch (IOException ex) { Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); } finally { if (br != null) try { br.close(); } catch (IOException ignored) { } if (process2 != null) try { process2.destroy(); } catch (Throwable ex) { Log.w(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); } if (process1 != null) try { process1.destroy(); } catch (Throwable ex) { Log.w(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex)); } } return builder; }