List of usage examples for java.lang ProcessBuilder redirectErrorStream
boolean redirectErrorStream
To view the source code for java.lang ProcessBuilder redirectErrorStream.
Click Source Link
From source file:com.ibm.liberty.starter.service.swagger.api.v1.ProviderEndpoint.java
private int generateCode(String javaHome, String swaggerCodeGenJarPath, String javaClientTemplates, String codeGenLanguage, String filePath, String outputDir) throws java.io.IOException { try {//from w w w.j av a2 s . c o m final ArrayList<String> commandList = new ArrayList<String>(); if (javaHome == null || javaHome.trim().isEmpty()) { //Get java home javaHome = AccessController.doPrivileged(new PrivilegedAction<String>() { @Override public String run() { return System.getProperty("java.home"); } }); if (!javaHome.endsWith("/")) { javaHome += "/"; } log.fine("Retrieved Java home location from System property : " + javaHome); } commandList.add(javaHome + "bin/java"); commandList.add("-jar"); commandList.add(swaggerCodeGenJarPath); commandList.add("generate"); commandList.add("-l"); commandList.add(codeGenLanguage); if (javaClientTemplates != null && !javaClientTemplates.trim().isEmpty()) { commandList.add("-t"); commandList.add(javaClientTemplates); } commandList.add("-i"); commandList.add(filePath); commandList.add("-o"); commandList.add(outputDir); StringBuilder sb = new StringBuilder(); for (String command : commandList) { sb.append(command); sb.append(" "); } log.finer("Swagger code gen commands:\n" + sb.toString()); //Run the command ProcessBuilder builder = new ProcessBuilder(commandList); builder.redirectErrorStream(true); //merge error and output together Process codeGenProc = builder.start(); int exitVal = codeGenProc.waitFor(); log.finer("Exit values: " + exitVal); if (exitVal != 0) { log.fine("Error : exit value is not 0. exitVal=" + exitVal); log.finer("output=" + getOutput(codeGenProc)); } else { log.finer("Successfully generated code using SwaggerCodegen"); } return exitVal; } catch (Exception e) { log.fine("Exception occurred while executing SwaggerCodegen : e=" + e); return -1; } }
From source file:com.framgia.android.emulator.EmulatorDetector.java
private boolean checkIp() { boolean ipDetected = false; if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.INTERNET) == PackageManager.PERMISSION_GRANTED) { String[] args = { "/system/bin/netcfg" }; StringBuilder stringBuilder = new StringBuilder(); try {/*from w w w . j a v a 2s . c o m*/ ProcessBuilder builder = new ProcessBuilder(args); builder.directory(new File("/system/bin/")); builder.redirectErrorStream(true); Process process = builder.start(); InputStream in = process.getInputStream(); byte[] re = new byte[1024]; while (in.read(re) != -1) { stringBuilder.append(new String(re)); } in.close(); } catch (Exception ex) { // empty catch } String netData = stringBuilder.toString(); log("netcfg data -> " + netData); if (!TextUtils.isEmpty(netData)) { String[] array = netData.split("\n"); for (String lan : array) { if ((lan.contains("wlan0") || lan.contains("tunl0") || lan.contains("eth0")) && lan.contains(IP)) { ipDetected = true; log("Check IP is detected"); break; } } } } return ipDetected; }
From source file:com.rogue.simpleclient.SimpleClient.java
/** * Opens the minecraft client.// w w w. ja va 2 s.com * * @since 1.0.0 * @version 1.0.0 * * @throws SecurityException Lack of permissions to execute a process * @throws IOException Unobserved I/O Error */ public void openMinecraft() throws SecurityException, IOException { MCProc mc = new MCProc(this.natives, this.minecraftDir, this.gameDir, this.version); JSONObject prof = (JSONObject) this.response.get("selectedProfile"); mc.appendTag("username", (String) prof.get("name"), "="); mc.appendTag("version", this.version, " "); mc.appendTag("gameDir", this.minecraftDir.getAbsolutePath(), " "); mc.appendTag("assetsDir", new File(this.minecraftDir, "assets").getAbsolutePath(), " "); mc.appendTag("userProperties", "{}", " "); mc.appendTag("accessToken", (String) this.response.get("accessToken"), " "); mc.appendTag("uuid", (String) prof.get("id"), " "); try { ProcessBuilder pb = new ProcessBuilder(); pb.redirectErrorStream(true); pb.command(mc.getExec()); Process p = Runtime.getRuntime().exec(mc.getExec()); p.waitFor(); try (BufferedReader bf = new BufferedReader(new InputStreamReader(p.getInputStream()))) { String line; while ((line = bf.readLine()) != null) { System.out.println(line); } } } catch (Exception ex) { ex.printStackTrace(); } }
From source file:gr.aueb.dmst.istlab.unixtools.actions.impl.ExecuteCustomCommandAction.java
@Override public void execute(ActionExecutionCallback<DataActionResult<InputStream>> callback) throws IOException, InterruptedException { DataActionResult<InputStream> result; List<String> arguments = EclipsePluginUtil.getSystemShellInfo(); ProcessBuilder pb; if (SystemUtils.IS_OS_WINDOWS) { pb = new ProcessBuilder(arguments.get(0), arguments.get(1), arguments.get(2) + "\"cd " + this.commandToExecute.getShellDirectory() + ";" + this.commandToExecute.getCommand() + "\""); } else {/*from w w w . jav a 2 s . c o m*/ arguments.add(this.commandToExecute.getCommand()); pb = new ProcessBuilder(arguments); pb.directory(new File(this.commandToExecute.getShellDirectory())); } pb.redirectErrorStream(true); Process p; try { p = pb.start(); p.waitFor(); InputStream cmdStream = p.getInputStream(); result = new DataActionResult<>(cmdStream); } catch (IOException e) { logger.fatal("IO problem occurred while executing the command"); result = new DataActionResult<>(e); throw new IOException(e); } catch (InterruptedException e) { logger.fatal("The current thread has been interrupted while executing the command"); result = new DataActionResult<>(e); throw new InterruptedException(); } callback.onCommandExecuted(result); }
From source file:org.kyasuda.docwaza.office.OfficeProcess.java
protected void doStart(boolean retry) throws IOException { String processRegex = "soffice.*" + Pattern.quote(unoUrl.getAcceptString()); String existingPid = processManager.findPid(processRegex); if (existingPid != null) { throw new IllegalStateException( String.format("a process with acceptString '%s' is already running; pid %s", unoUrl.getAcceptString(), existingPid)); }//from w w w . ja va 2 s . c o m if (!retry) { prepareInstanceProfileDir(); prepareFakeBundlesDir(); } List<String> command = new ArrayList<String>(); File executable = OfficeUtils.getOfficeExecutable(officeHome); command.add(executable.getAbsolutePath()); command.add(COMMAND_ARG_PREFIX + "accept=" + unoUrl.getAcceptString() + ";urp;"); command.add("-env:UserInstallation=" + OfficeUtils.toUrl(instanceProfileDir)); if (!PlatformUtils.isWindows()) { command.add("-env:BUNDLED_EXTENSIONS=" + OfficeUtils.toUrl(fakeBundlesDir)); } command.add(COMMAND_ARG_PREFIX + "headless"); command.add(COMMAND_ARG_PREFIX + "nocrashreport"); command.add(COMMAND_ARG_PREFIX + "nodefault"); command.add(COMMAND_ARG_PREFIX + "nofirststartwizard"); command.add(COMMAND_ARG_PREFIX + "nolockcheck"); command.add(COMMAND_ARG_PREFIX + "nologo"); command.add(COMMAND_ARG_PREFIX + "norestore"); ProcessBuilder processBuilder = new ProcessBuilder(command); processBuilder.redirectErrorStream(true); lastCommand = command; if (PlatformUtils.isWindows()) { addBasisAndUrePaths(processBuilder); } logger.info(String.format("starting process with acceptString '%s' and profileDir '%s'", unoUrl, instanceProfileDir)); process = processBuilder.start(); int exitValue = 0; boolean exited = false; for (int i = 0; i < getStartupWatchTime() * 2; i++) { try { // wait for process to start Thread.sleep(500); } catch (Exception e) { } try { exitValue = process.exitValue(); // process is already dead, no need to wait longer ... exited = true; break; } catch (IllegalThreadStateException e) { // process is still up } } if (exited) { if (exitValue == 81) { logger.warning("Restarting OOo after code 81 ..."); process = processBuilder.start(); try { // wait for process to start Thread.sleep(1000); } catch (Exception e) { } } else { logger.warning("Process exited with code " + exitValue); } } manageProcessOutputs(process); if (processManager.canFindPid()) { pid = processManager.findPid(processRegex); if (pid == null) { throw new IllegalStateException( "started process, but can not find the pid, process is probably dead"); } else { logger.info("started process : pid = " + pid); } } else { logger.info("process started with PureJavaProcessManager - cannot check for pid"); } }
From source file:unimelb.distributed_project.gui.JacardSimilarityMeasurePanel.java
/** * This function performs the action of visualization of button. It uses external program, * python, to visualize plot for the result of Jacard similarity measurement between two * training sets.//w ww. ja v a 2 s .co m * * @param e ActionEvent object */ private void visualizedButtonActionPerformed(ActionEvent e) { jcardSimFilePath = simOutputPathTextField.getText(); if (jcardSimFilePath != null && !jcardSimFilePath.equals("")) { File f = new File(jcardSimFilePath); //Visualize it with Python try { if (f.exists()) { String ployPythonFile = f.getParent(); ProcessBuilder processBuilder = new ProcessBuilder("/usr/bin/python", ployPythonFile + "/plot.py", jcardSimFilePath); processBuilder.redirectErrorStream(true); Process process = processBuilder.start(); //TODO add error handling when the plot.py is not in place IOUtils.copy(process.getInputStream(), System.out); } else { log.debug("similarity file doesn't exist"); } } catch (IOException e1) { e1.printStackTrace(); } } }
From source file:net.pms.io.SimpleProcessWrapper.java
/** * Runs a process with the given command {@link List}. * * @param command an array of {@link String} used to build the command line. * @param timeoutMS the process timeout in milliseconds after which the * process is terminated. Use zero for no timeout, but be aware * of the <a href=/* www.j av a 2s . c o m*/ * "https://web.archive.org/web/20121201070147/http://kylecartmell.com/?p=9" * >pitfalls</a> * @param terminateTimeoutMS the timeout in milliseconds to wait for each * termination attempt. * @return The {@link ProcessWrapperResult} from running the process. * @throws InterruptedException If the operation is interrupted. * @throws IllegalArgumentException If {@code command} is {@code null} or * empty. */ @Nonnull public R runProcess(@Nonnull List<String> command, long timeoutMS, long terminateTimeoutMS) throws InterruptedException { if (command == null || command.isEmpty()) { throw new IllegalArgumentException("command can't be null or empty"); } final String executableName; if (isNotBlank(command.get(0))) { Path executable = Paths.get(command.get(0)).getFileName(); if (executable != null) { executableName = executable.toString(); } else { executableName = command.get(0); } } else { executableName = command.get(0); } boolean manageProcess = timeoutMS > 0; ProcessBuilder processBuilder = new ProcessBuilder(command); processBuilder.redirectErrorStream(true); if (LOGGER.isTraceEnabled()) { //XXX: Replace with String.join() in Java 8 LOGGER.trace("Executing \"{}\"", StringUtils.join(command, " ")); } Process process; try { process = processBuilder.start(); } catch (IOException e) { LOGGER.debug("IOException when trying to start \"{}\" process: {}", executableName, e.getMessage()); LOGGER.trace("", e); return consumer.createResult(null, Integer.MIN_VALUE, e); } Future<T> output = consumer.consume(process.getInputStream(), "SPW \"" + executableName + "\" consumer"); if (manageProcess) { Services.processManager().addProcess(process, command.get(0), timeoutMS, terminateTimeoutMS); } int exitCode = Integer.MIN_VALUE; boolean interrupted = false; boolean shutdown = false; do { interrupted = false; try { exitCode = process.waitFor(); } catch (InterruptedException e) { interrupted = Thread.interrupted(); if (!shutdown) { if (manageProcess) { Services.processManager().shutdownProcess(process, executableName); manageProcess = false; } else { Services.processManager().addProcess(process, executableName, 0, terminateTimeoutMS); } shutdown = true; } } } while (interrupted); if (manageProcess) { Services.processManager().removeProcess(process, command.get(0)); } try { return consumer.createResult(output.get(), exitCode, null); } catch (ExecutionException e) { Throwable cause = e.getCause() != null ? e.getCause() : e; LOGGER.error("ExecutionException in \"{}\" consumer, no output will be returned: {}", executableName, cause.getMessage()); LOGGER.trace("", e); return consumer.createResult(null, exitCode, cause); } }
From source file:org.omegat.languagetools.LanguageToolNetworkBridge.java
/** * Get instance spawning and talking to local server * * @param path// w w w . j a va 2s . c o m * local LanguageTool directory * @param port * local port for spawned server to listen * @return new LanguageToolNetworkBridge instance * @throws java.lang.Exception */ public LanguageToolNetworkBridge(Language sourceLang, Language targetLang, String path, int port) throws Exception { // Remember port localPort = port; File serverJar = new File(path); // Check if ClassPath points to a real file if (!serverJar.isFile()) { Log.logWarningRB("LT_BAD_LOCAL_PATH"); throw new Exception(); } // Check if socket is available try { new ServerSocket(port).close(); } catch (Exception e) { Log.logWarningRB("LT_BAD_SOCKET"); throw new Exception(); } // Run the server ProcessBuilder pb = new ProcessBuilder("java", "-cp", serverJar.getAbsolutePath(), SERVER_CLASS_NAME, "--port", Integer.toString(port)); pb.redirectErrorStream(true); server = pb.start(); // Create thread to consume server output new Thread(() -> { try (InputStream is = server.getInputStream()) { @SuppressWarnings("unused") int b; while ((b = is.read()) != -1) { // Discard } } catch (IOException e) { // Do nothing } }).start(); // Wait for server to start int timeout = 10000; int timeWaiting = 0; int interval = 10; while (true) { Thread.sleep(interval); timeWaiting += interval; try { new Socket("localhost", port).close(); break; } catch (Exception e) { } if (timeWaiting >= timeout) { Log.logWarningRB("LT_SERVER_START_TIMEOUT"); server.destroy(); throw new Exception(); } } serverUrl = "http://localhost:" + port + CHECK_PATH; Log.log(OStrings.getString("LT_SERVER_STARTED")); try { init(sourceLang, targetLang); } catch (Exception ex) { stop(); throw ex; } }
From source file:org.opencastproject.workflow.handler.CLIWorkflowOperationHandler.java
/** * {@inheritDoc}//from w w w.j a v a2 s .com * * @see org.opencastproject.workflow.api.WorkflowOperationHandler#start(org.opencastproject.workflow.api.WorkflowInstance, JobContext) */ @Override public WorkflowOperationResult start(WorkflowInstance workflowInstance, JobContext context) throws WorkflowOperationException { WorkflowOperationInstance operation = workflowInstance.getCurrentOperation(); // MediaPackage from previous workflow operations MediaPackage srcPackage = workflowInstance.getMediaPackage(); // Modified media package from our external cli operation, if any MediaPackage resultPackage = null; // Executable attempting to be invoked String exec = operation.getConfiguration("exec"); // Parameters, like argv[] String params = operation.getConfiguration("params"); // Verify that the executable is not null if (StringUtils.isEmpty(exec)) { logger.info("Executable parameter from workflow document is either null or empty: " + exec); throw new WorkflowOperationException("Invalid exec param: " + exec); } // Substitute #{xpath_query} with values from the media package try { params = substituteVariables(params, srcPackage); } catch (Exception e) { throw new WorkflowOperationException( "Failed to create concrete parameters from list, are the xpath variables set correctly?"); } // Start the external process List<String> args = new LinkedList<String>(); args.add(exec); args.addAll(splitParameters(params)); Process p = null; try { // Debug output of the Command being run if (logger.isDebugEnabled()) { StringBuilder sb = new StringBuilder(); for (String str : args) { sb.append(str); sb.append(" "); } logger.debug("Starting subprocess: {}", sb.toString()); } logger.info("Starting subprocess: {}", exec); ProcessBuilder pb = new ProcessBuilder(args); pb.redirectErrorStream(true); // Unfortunately merges but necessary for deadlock prevention p = pb.start(); } catch (IOException e) { // Only log the first argument, the executable, as other arguments may contain sensitive values // e.g. MySQL password/user, paths, etc. that should not be shown to caller logger.error("Could not start subprocess {}", args.get(0)); throw new WorkflowOperationException("Could not start subprocess: " + args.get(0)); } // Attempt to read the output of the command and parse it as a media package try { logger.debug("Reading results from subprocess"); InputStream in = p.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); StringBuffer sb = new StringBuffer(); String line; while ((line = br.readLine()) != null) { sb.append(line); } in.close(); logger.info("Subprocess return data: {}", sb.toString()); // If the response is a media package set the response to it try { resultPackage = MediaPackageBuilderFactory.newInstance().newMediaPackageBuilder() .loadFromXml(sb.toString()); } catch (Exception e) { logger.info("Output text was found but was not deserializable to a MediaPackage object"); } // If the response is a file to a media package set the response to the contents of the file BufferedReader fil = null; try { File f = new File(sb.toString()); if (f.exists()) { StringBuffer fb = new StringBuffer(); fil = new BufferedReader(new FileReader(f)); line = fil.readLine(); while (line != null) { fb.append(line); line = fil.readLine(); } resultPackage = MediaPackageBuilderFactory.newInstance().newMediaPackageBuilder() .loadFromXml(fb.toString()); } } catch (Exception e) { logger.info("Output file was found but was not deserializable to a MediaPackage object"); } finally { try { IOUtils.closeQuietly(fil); } catch (Exception e) { // supressed } } } catch (IOException e) { logger.debug("Unable to read output from subprocess.", e); } // On error return code throw to caller int returnCode = 0; try { returnCode = p.waitFor(); logger.debug("Subprocess returned code {}", String.valueOf(returnCode)); } catch (InterruptedException e) { throw new WorkflowOperationException( "Workflow handler thread interrupted before external process ended."); } if (returnCode != 0) { logger.warn("Non-zero return code from external process"); throw new WorkflowOperationException( "Non-zero return code from external process: " + String.valueOf(returnCode)); } // If there is no resultant mediapackage, pass back the one that was provided to us if (resultPackage == null) { return new WorkflowOperationResultImpl(srcPackage, null, Action.CONTINUE, 0); } return new WorkflowOperationResultImpl(resultPackage, null, Action.CONTINUE, 0); }