List of usage examples for java.lang Process getErrorStream
public abstract InputStream getErrorStream();
From source file:com.mtgi.analytics.test.AbstractPerformanceTestCase.java
private void runTest(ServerSocket listener, ProcessBuilder launcher, StatisticsMBean stats, byte[] jobData) throws IOException, InterruptedException { Process proc = launcher.start(); //connect stdout and stderr to parent process streams if (log.isDebugEnabled()) { new PipeThread(proc.getInputStream(), System.out).start(); new PipeThread(proc.getErrorStream(), System.err).start(); } else {// www . ja va2 s.c o m NullOutput sink = new NullOutput(); new PipeThread(proc.getInputStream(), sink).start(); new PipeThread(proc.getErrorStream(), sink).start(); } //wait for the incoming connection from the child process. Socket sock = listener.accept(); try { //connection established, send the job. OutputStream os = sock.getOutputStream(); os.write(jobData); os.flush(); //read measurements back. DataInputStream dis = new DataInputStream(sock.getInputStream()); for (long measure = dis.readLong(); measure >= 0; measure = dis.readLong()) stats.add(measure); //send ack byte to tell the child proc its ok to hang up. os.write(1); os.flush(); } finally { sock.close(); } assertEquals("Child process ended successfully", 0, proc.waitFor()); }
From source file:com.thoughtworks.go.agent.AgentProcessParentImplTest.java
private Process mockProcess(final InputStream outputStream, final InputStream errorStream, final OutputStream inputStream) throws InterruptedException { final Process subProcess = mock(Process.class); when(subProcess.waitFor()).thenReturn(42); when(subProcess.getInputStream()).thenReturn(outputStream); when(subProcess.getErrorStream()).thenReturn(errorStream); when(subProcess.getOutputStream()).thenReturn(inputStream); return subProcess; }
From source file:org.gofleet.openLS.monav.MoNaVConnector.java
/** * Route plan using monav daemon. Only geometry. * //from w w w . j av a 2 s . c o m * @param param * @return * @throws IOException * @throws ParseException * @throws JAXBException * @throws InterruptedException */ @Override public DetermineRouteResponseType routePlan(DetermineRouteRequestType param, int maxResponses) { DetermineRouteResponseType res = new DetermineRouteResponseType(); Double cost = null; String cmd = "/opt/monav/bin/daemon-test /var/www/monav/routing_yes/"; RouteGeometryType routeGeometry = new RouteGeometryType(); WayPointListType wayPointList = param.getRoutePlan().getWayPointList(); Point point = GeoUtil.getPoint(wayPointList.getStartPoint(), null); cmd += " " + point.getY() + " " + point.getX(); for (WayPointType wayPoint : wayPointList.getViaPoint()) { point = GeoUtil.getPoint(wayPoint, null); cmd += " " + point.getY() + " " + point.getX(); } point = GeoUtil.getPoint(wayPointList.getEndPoint(), null); cmd += " " + point.getY() + " " + point.getX(); LOG.debug(cmd); Process p; try { p = Runtime.getRuntime().exec(cmd); } catch (IOException ex) { throw new RuntimeException(ex); } BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream())); LineStringType lst = new LineStringType(); List<JAXBElement<?>> list = new LinkedList<JAXBElement<?>>(); String l; try { l = br.readLine(); } catch (IOException ex) { throw new RuntimeException(ex); } while (l != null) { LOG.info(l); try { if (cost == null && l.indexOf("distance:") >= 0) cost = -1d;// TODO Double x = Double.parseDouble(l.substring(0, l.indexOf(" "))); Double y = Double.parseDouble(l.substring(1 + l.indexOf(" "))); DirectPositionListType e = new DirectPositionListType(); e.getValue().add(y); e.getValue().add(x); JAXBElement<DirectPositionListType> elem = new JAXBElement<DirectPositionListType>( new QName("http://www.opengis.net/gml", "pos", "gml"), DirectPositionListType.class, e); list.add(elem); } catch (Throwable t) { // LOG.error(t); } try { l = br.readLine(); } catch (IOException ex) { throw new RuntimeException(ex); } } try { lst.setPosOrPointPropertyOrPointRep(list); routeGeometry.setLineString(lst); res.setRouteGeometry(routeGeometry); res.setRouteHandle(new RouteHandleType()); res.setRouteInstructionsList(new RouteInstructionsListType()); res.setRouteMap(new LinkedList<RouteMapType>()); res.setRouteSummary(new RouteSummaryType()); } catch (Throwable t) { LOG.error("Error generating route response: " + t, t); } return res; }
From source file:com.docd.purefm.tasks.SearchCommandLineTask.java
@Override protected Void doInBackground(String... params) { final CommandFind command = new CommandFind(mStartDirectory.getAbsolutePath(), params); // NOTE this doesn't use Shell because we can't create a new CommandLineFile from // CommandOutput because executing readlink (which is done in CommandLineFile constructor) // will freeze the whole Shell DataOutputStream os = null;/*from ww w. j ava2 s . co m*/ BufferedReader is = null; BufferedReader err = null; Process process = null; try { process = Runtime.getRuntime().exec(mSettings.isSuEnabled() ? "su" : "sh"); os = new DataOutputStream(process.getOutputStream()); is = new BufferedReader(new InputStreamReader(process.getInputStream())); err = new BufferedReader(new InputStreamReader(process.getErrorStream())); os.writeBytes(command.toString()); os.writeBytes("exit\n"); os.flush(); String line; try { while (!isCancelled() && (line = is.readLine()) != null) { this.publishProgress(CommandLineFile.fromLSL(null, line)); } } catch (EOFException e) { //ignore } try { while (!isCancelled() && (line = err.readLine()) != null) { final Matcher denied = DENIED.matcher(line); if (denied.matches()) { this.mDenied.add(denied.group(1)); } } } catch (EOFException e) { //ignore } process.waitFor(); } catch (Exception e) { Log.w("Exception while searching", e.toString()); } finally { IOUtils.closeQuietly(os); IOUtils.closeQuietly(is); IOUtils.closeQuietly(err); if (process != null) { try { process.destroy(); } catch (Exception e) { //ignored } } } return null; }
From source file:com.laex.j2objc.ToObjectiveCDelegate.java
@Override public boolean visit(final IResource resource) throws CoreException { // cancel the job if (monitor.isCanceled()) { onCancelled();//from w w w . j a va 2 s .c o m resource.getProject().refreshLocal(IResource.DEPTH_INFINITE, monitor); monitor.done(); return false; } if (!(resource.getType() == IResource.FILE)) { return true; } if (!JavaCore.isJavaLikeFileName(resource.getName())) { return true; } String sourcePath = resource.getLocation().makeAbsolute().toOSString(); // As per the discussion with Tom Ball, the output of compilation is // stored in the project's root source folder // See // https://groups.google.com/forum/?fromgroups=#!topic/j2objc-discuss/lJGzN-pxmkQ String outputPath = resource.getProject().getFolder("src").getLocation().makeAbsolute().toOSString(); try { String cmd = buildCommand(this.display, prefs, resource.getProject(), resource, sourcePath, outputPath); monitor.subTask(resource.getName()); Process p = Runtime.getRuntime().exec(cmd); Scanner scanInput = new Scanner(p.getInputStream()); Scanner scanErr = new Scanner(p.getErrorStream()); MessageConsoleStream mct = MessageUtil.findConsole(MessageUtil.J2OBJC_CONSOLE).newMessageStream(); mct.write(cmd); mct.write(MessageUtil.NEW_LINE_CONSTANT); while (scanInput.hasNext()) { MessageUtil.resetConsoleColor(display, mct); mct.write(scanInput.nextLine()); mct.write(MessageUtil.NEW_LINE_CONSTANT); } while (scanErr.hasNext()) { MessageUtil.setConsoleColor(display, mct, SWT.COLOR_RED); mct.write(scanErr.nextLine()); mct.write(MessageUtil.NEW_LINE_CONSTANT); } mct.write(MessageUtil.NEW_LINE_CONSTANT); } catch (IOException e) { LogUtil.logException(e); } monitor.worked(1); return true; }
From source file:com.synopsys.integration.blackduck.codelocation.signaturescanner.command.ScanCommandCallable.java
@Override public ScanCommandOutput call() { String commandToExecute = "command_not_yet_configured"; try {/*from w w w. j a va2s .co m*/ final ScanPaths scanPaths = scanPathsUtility .determineSignatureScannerPaths(scanCommand.getInstallDirectory()); final List<String> cmd = scanCommand.createCommandForProcessBuilder(logger, scanPaths, scanCommand.getOutputDirectory().getAbsolutePath()); cmd.add(scanCommand.getTargetPath()); commandToExecute = createPrintableCommand(cmd); logger.info(String.format("Black Duck CLI command: %s", commandToExecute)); final File standardOutFile = scanPathsUtility.createStandardOutFile(scanCommand.getOutputDirectory()); try (FileOutputStream outputFileStream = new FileOutputStream(standardOutFile)) { final ScannerSplitStream splitOutputStream = new ScannerSplitStream(logger, outputFileStream); final ProcessBuilder processBuilder = new ProcessBuilder(cmd); processBuilder.environment().putAll(intEnvironmentVariables.getVariables()); if (!scanCommand.isDryRun()) { if (!StringUtils.isEmpty(scanCommand.getApiToken())) { processBuilder.environment().put("BD_HUB_TOKEN", scanCommand.getApiToken()); } else { processBuilder.environment().put("BD_HUB_PASSWORD", scanCommand.getPassword()); } } processBuilder.environment().put("BD_HUB_NO_PROMPT", "true"); final Process blackDuckCliProcess = processBuilder.start(); // The cli logs go the error stream for some reason final StreamRedirectThread redirectThread = new StreamRedirectThread( blackDuckCliProcess.getErrorStream(), splitOutputStream); redirectThread.start(); int returnCode = -1; try { returnCode = blackDuckCliProcess.waitFor(); // the join method on the redirect thread will wait until the thread is dead // the thread will die when it reaches the end of stream and the run method is finished redirectThread.join(); } finally { if (blackDuckCliProcess.isAlive()) { blackDuckCliProcess.destroy(); } if (redirectThread.isAlive()) { redirectThread.interrupt(); } } splitOutputStream.flush(); logger.info(IOUtils.toString(blackDuckCliProcess.getInputStream(), StandardCharsets.UTF_8)); logger.info("Black Duck Signature Scanner return code: " + returnCode); logger.info( "You can view the logs at: '" + scanCommand.getOutputDirectory().getCanonicalPath() + "'"); if (returnCode != 0) { return ScanCommandOutput.FAILURE(scanCommand.getName(), logger, scanCommand, commandToExecute, returnCode); } } } catch (final Exception e) { final String errorMessage = String.format("There was a problem scanning target '%s': %s", scanCommand.getTargetPath(), e.getMessage()); return ScanCommandOutput.FAILURE(scanCommand.getName(), logger, scanCommand, commandToExecute, errorMessage, e); } if (!scanCommand.isDryRun() && cleanupOutput) { FileUtils.deleteQuietly(scanCommand.getOutputDirectory()); } else if (scanCommand.isDryRun() && cleanupOutput) { // delete everything except dry run files final File[] outputFiles = scanCommand.getOutputDirectory().listFiles(); for (final File outputFile : outputFiles) { if (!DRY_RUN_FILES_TO_KEEP.contains(outputFile.getName())) { FileUtils.deleteQuietly(outputFile); } } } return ScanCommandOutput.SUCCESS(scanCommand.getName(), logger, scanCommand, commandToExecute); }
From source file:com.gwac.job.FileTransferServiceImpl.java
public void transFile3() { if (isBeiJingServer) { return;/*w w w . j av a2 s. co m*/ } if (running == true) { log.info("start job fileTransferJob..."); running = false; } else { log.info("job fileTransferJob is running, jump this scheduler."); return; } String s = null; try { String command = "curl http://159.226.88.94:8077/gwac/realTimeOtDstImageUpload.action " + "-F fileUpload=@/home/gwac/data/m1_01_140624_200060_0000_0011.fits"; log.info("execute command:"); log.info(command); long startMili = System.currentTimeMillis(); Process p = Runtime.getRuntime().exec(command); BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream())); log.info("command return result:"); while ((s = stdInput.readLine()) != null) { log.info(s); } log.info("command return error (if any):"); while ((s = stdError.readLine()) != null) { log.info(s); } p.waitFor(); long endMili = System.currentTimeMillis(); double speed = 1.07 * 1000 / (endMili - startMili); log.info("total consume time: " + (endMili - startMili) / 1000 + "s"); log.info("transmit speed is: " + speed + "MB/s"); Calendar c1 = Calendar.getInstance(); c1.setTime(new Date()); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd H:m:s"); PrintWriter out = new PrintWriter( new BufferedWriter(new FileWriter("/home/gwac/transferRecord.log", true))); out.println(format.format(c1.getTime()) + "\t" + speed); out.close(); } catch (Exception e) { log.info("exception happened - here"); e.printStackTrace(); } if (running == false) { running = true; log.info("job fileTransferJob is done."); } }
From source file:cz.muni.pdfjbim.Jbig2enc.java
/** * run jbig2enc with symbol coding used and output in format suitable for PDF * * @param basename base//w ww .j a v a2s . c o m * @param imageList list of images to be compressed * @throws PdfRecompressionException if any problem occurs while running jbig2enc */ public void run(List<String> imageList, String basename) throws PdfRecompressionException { if (basename == null) { basename = "output"; } if (imageList == null) { throw new NullPointerException("imageList"); } if (imageList.isEmpty()) { log.info("there are no images for running jbig2enc at (given list is empty)"); return; } List<String> toRun = new ArrayList<String>(); toRun.add(jbig2enc); toRun.add("-s"); toRun.add("-p"); toRun.add("-b"); toRun.add(basename); toRun.add("-t"); toRun.add(String.valueOf(defaultThresh)); toRun.add("-T"); toRun.add(String.valueOf(bwThresh)); if (segment) { toRun.add("-S"); } if (autoThresh) { toRun.add("--auto-thresh"); if (useOcr) { toRun.add("--use-ocr"); if (lang != null) { toRun.add("--lang"); toRun.add(lang); } } } if (forced) { toRun.add("-ff"); } toRun.addAll(imageList); String[] run = new String[toRun.size()]; run = toRun.toArray(run); Runtime runtime = Runtime.getRuntime(); Process pr1; BufferedReader reader = null; try { log.debug("Executing {}", toRun); pr1 = runtime.exec(run); OutputRedirector errRedirectThread = new OutputRedirector(pr1.getErrorStream()); OutputRedirector outRedirectThread = new OutputRedirector(pr1.getInputStream()); errRedirectThread.start(); outRedirectThread.start(); int exitValue = pr1.waitFor(); if (exitValue != 0) { log.warn("jbig2enc ended with error " + exitValue); Tools.deleteFilesFromList(imageList); throw new PdfRecompressionException("jbig2enc ended with error " + exitValue); } } catch (IOException ex) { log.warn("running jbig2enc caused IOException", ex); } catch (InterruptedException ex2) { log.warn("running jbig2enc was interupted", ex2); } finally { IOUtils.closeQuietly(reader); Tools.deleteFilesFromList(imageList); } }
From source file:br.unb.bionimbuz.storage.bucket.methods.CloudMethodsAmazonGoogle.java
private void CheckStorageUpBandwith(BioBucket bucket) throws Exception { //Upload/*from w w w.j a v a2 s .com*/ String command = "/bin/dd if=/dev/zero of=" + bucket.getMountPoint() + "/testfile-" + myId + " bs=30M count=1 iflag=nocache oflag=nocache"; Runtime rt = Runtime.getRuntime(); Process proc = rt.exec(command); //System.out.println("\nRunning command: " + command); InputStream stderr = proc.getErrorStream(); InputStreamReader isr = new InputStreamReader(stderr); BufferedReader br = new BufferedReader(isr); String line; List<String> output = new ArrayList<>(); while ((line = br.readLine()) != null) { output.add(line); //System.out.println("[command] " + line); } int exitVal = proc.waitFor(); //System.out.println("[command] Process exitValue: " + exitVal); if (exitVal != 0) { throw new Exception("Error in command: " + command); } int pos1, pos2; pos1 = output.get(output.size() - 1).indexOf(" copied, "); pos1 += 9; pos2 = output.get(output.size() - 1).indexOf(" s, "); String aux; aux = output.get(output.size() - 1).substring(pos1, pos2); aux = aux.replace(',', '.'); float value = Float.parseFloat(aux); bucket.setUpBandwith((31 * 1024 * 1024) / value); }
From source file:br.unb.bionimbuz.storage.bucket.methods.CloudMethodsAmazonGoogle.java
private void CheckStorageDlBandwith(BioBucket bucket) throws Exception { //Download //from w ww. j av a 2 s .co m String command = "/bin/dd if=" + bucket.getMountPoint() + "/testfile-" + myId + " of=/tmp/testfile bs=30M count=1 iflag=nocache oflag=nocache"; Runtime rt = Runtime.getRuntime(); Process proc = rt.exec(command); //System.out.println("\nRunning command: " + command); InputStream stderr = proc.getErrorStream(); InputStreamReader isr = new InputStreamReader(stderr); BufferedReader br = new BufferedReader(isr); String line; List<String> output = new ArrayList<>(); while ((line = br.readLine()) != null) { output.add(line); //System.out.println("[command] " + line); } int exitVal = proc.waitFor(); //System.out.println("[command] Process exitValue: " + exitVal); if (exitVal != 0) { throw new Exception("Error in command: " + command); } int pos1, pos2; pos1 = output.get(output.size() - 1).indexOf(" copied, "); pos1 += 9; pos2 = output.get(output.size() - 1).indexOf(" s, "); String aux; aux = output.get(output.size() - 1).substring(pos1, pos2); aux = aux.replace(',', '.'); float value = Float.parseFloat(aux); bucket.setDlBandwith((31 * 1024 * 1024) / value); }