List of usage examples for java.lang Runtime exec
public Process exec(String[] cmdarray, String[] envp, File dir) throws IOException
From source file:ninja.command.PackageCommand.java
private void packageStandaloneApp() throws IOException, InterruptedException { count = 0;/*w w w . ja v a2s. co m*/ conflicts = 0; zipManifest.clear(); FileUtils.copyDirectory(project.getClassesDir(), packageFolder); // FIXME This is a hack for the views FileUtils.copyDirectory(new File(project.getSourceDir(), "views"), new File(packageFolder, "views")); for (Lib lib : project.getLibs()) { // System.out.println("Unzipping: " + lib.jarPath); unzip(new File(lib.getJarPath()), packageFolder); } String jarName = project.getName() + ".jar"; // FileUtils.deleteDirectory(new File(packageFolder, "META-INF")); new File(packageFolder, "META-INF/MANIFEST.MF").delete(); new File(packageFolder, "META-INF/INDEX.LIST").delete(); Runtime rt = Runtime.getRuntime(); Process pr = rt.exec(String.format("jar -cfe ../%s ninja.standalone.NinjaJetty .", jarName), null, packageFolder); int result = pr.waitFor(); if (result == 0) info(String.format("Jar created '%s'.", jarName)); else info(String.format("Error while creating '%s'.", jarName)); info(String.format("%d files, %d conflicts", count, conflicts)); }
From source file:piramide.multimodal.applicationserver.rest.CompilationsManager.java
private void compile() throws ResourceException { final boolean USE_PROCESS_BUILDER = System.getProperty("os.name").toLowerCase() == "linux"; final File configurationDirectory = new File(this.directoriesManager.getConfigurationDirectoryName()); final File compilationDirectory = new File(this.directoriesManager.getCompilationDirectoryName()); try {/*from ww w . j a v a 2 s. c o m*/ FileUtils.copyDirectory(configurationDirectory, compilationDirectory); final Process process; if (USE_PROCESS_BUILDER) { process = new ProcessBuilder(LAUNCH_SCRIPT_ARGS).directory(compilationDirectory).start(); } else { final Runtime rt = Runtime.getRuntime(); process = rt.exec(LAUNCH_SCRIPT_ARGS, new String[] {}, compilationDirectory); } final int returnCode = process.waitFor(); final String inputStream = IOUtils.toString(process.getInputStream()); final String errorStream = IOUtils.toString(process.getErrorStream()); if (returnCode != 0 || DEBUG) { System.out.println(inputStream); System.out.println(errorStream); } if (returnCode != 0) { throw new ResourceException(Status.SERVER_ERROR_INTERNAL, "Couldn't compile file! " + inputStream.replaceAll("\n", "<br>") + "; errors: " + errorStream.replaceAll("\n", "<br>")); } } catch (IOException e) { e.printStackTrace(); throw new ResourceException(Status.SERVER_ERROR_INTERNAL, "Couldn't find ant script!", e); } catch (InterruptedException e) { e.printStackTrace(); throw new ResourceException(Status.SERVER_ERROR_INTERNAL, "Compiling process interrupted!", e); } }
From source file:processing.app.CommandLineTest.java
@Test public void testCommandLineBuildWithRelativePath() throws Exception { Runtime rt = Runtime.getRuntime(); File wd = new File(buildPath, "build/shared/examples/01.Basics/Blink/"); Process pr = rt.exec(arduinoPath + " --board arduino:avr:uno --verify Blink.ino", null, wd); IOUtils.copy(pr.getInputStream(), System.out); pr.waitFor();// w w w.j a v a 2s. c o m assertEquals(0, pr.exitValue()); }
From source file:org.onecmdb.ui.gwt.desktop.server.command.exec.JavaExec.java
/** * /*from www . ja v a 2 s.c o m*/ * Start the handled program * @param unpackdir Directory containing the files in the Job Definition * @throws IOException */ public ExecResult doExec() { ExecResult result = new ExecResult(); String program = reolveProgram(); List<String> shellArgs = resolveShell(program); List<String> params = reloveParams(); List<String> cmdList = new ArrayList<String>(); cmdList.addAll(shellArgs); cmdList.add(program); cmdList.addAll(params); liveLog("CMD-LIST : " + cmdList.toString()); log.info("Startup Directory:" + startDir); for (int i = 0; i < cmdList.size(); i++) { log.info("$" + i + ": " + cmdList.get(i)); } // Do some checks. if (!startDir.isDirectory()) { result.setRc(ExecResult.ERROR_NO_STARTUP_DIR); result.setMessage("Starup directory `" + startDir + "' not accessible."); return (result); } File f = new File(program); if (!f.exists()) { result.setRc(ExecResult.ERROR_NO_PROGRAM); result.setMessage("Program `" + program + "' is not found."); return (result); } if (f.isDirectory()) { result.setRc(ExecResult.ERROR_NO_PROGRAM); result.setMessage("Program `" + program + "' is a directory."); return (result); } try { // let us start it now... Runtime runtime = Runtime.getRuntime(); this.process = runtime.exec(cmdList.toArray(new String[0]), null, startDir); // handle the streams if (this.streamHandler != null) { streamHandler.setStdin(new OutputStreamWriter(this.process.getOutputStream())); streamHandler.setStdout(new BufferedReader(new InputStreamReader(this.process.getInputStream()))); streamHandler.setStderr(new BufferedReader(new InputStreamReader(this.process.getErrorStream()))); } // according to the contract for `doExec' we should wait until the // the process has finished. int rc = this.process.waitFor(); result.setRc(rc); this.process = null; } catch (InterruptedException e) { log.info("Execution interrupted. " + e.getMessage()); result.setRc(ExecResult.ERROR_INTERRUPTED); result.setMessage("Execution interrupted. " + e.getMessage()); } catch (Throwable e) { log.error("Failed to compleate execution. " + e.getMessage(), e); result.setRc(ExecResult.ERROR_EXCEPTION); result.setMessage("Execution <" + program + "> failed. Reason " + e.getMessage()); } return result; }
From source file:com.appcel.core.encoder.executor.FfmpegEncoderExecutor.java
/** * Executes the ffmpeg process with the previous given arguments. * //from w w w .ja va2s . c o m * @throws IOException * If the process call fails. */ public void execute(File directory) throws EncoderException { LOGGER.info("==========>>> ffmpeg ?..."); try { int argsSize = args.size(); String[] cmd = new String[argsSize + 1]; cmd[0] = executablePath; for (int i = 0; i < argsSize; i++) { cmd[i + 1] = args.get(i); } LOGGER.info("Ffmpeg ===>>> " + args); Runtime runtime = Runtime.getRuntime(); ffmpeg = runtime.exec(cmd, null, directory); ffmpegKiller = new ProcessKiller(ffmpeg); runtime.addShutdownHook(ffmpegKiller); inputStream = ffmpeg.getInputStream(); outputStream = ffmpeg.getOutputStream(); errorStream = ffmpeg.getErrorStream(); LOGGER.info("==========>>> ffmpeg ??."); } catch (IOException e) { LOGGER.error("==========>>> ffmpeg ? Message: " + e.getMessage()); LOGGER.error("==========>>> ffmpeg ? Cause: " + e.getCause()); e.printStackTrace(); } finally { destroy(); } }
From source file:org.shept.util.CommandShellExecute.java
/** * Run the command shell// w w w . ja v a 2 s . c om */ public void run() { String[] cmd = new String[3]; Assert.notNull(cmdString); try { isRunning = true; exitVal = -1; // noit yet started String osName = System.getProperty("os.name"); if (osName.equals("Windows 95")) { cmd[0] = "command.com"; cmd[1] = "/C"; cmd[2] = cmdString; } else if (osName.startsWith("Windows")) { cmd[0] = "cmd.exe"; cmd[1] = "/C"; cmd[2] = cmdString; } else if (osName.startsWith("Linux")) { cmd[0] = "/bin/bash"; cmd[1] = "-c"; cmd[2] = cmdString; } else { log.error("Unsupported operating system " + osName + " for command processing: " + cmdString); } Runtime rt = Runtime.getRuntime(); log.info("Executing " + cmd[0] + " " + cmd[1] + " " + cmd[2]); Process proc = rt.exec(cmd, envp, workingDirectory); // any error message? StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), true); // any output? StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), false); // kick them off errorGobbler.start(); outputGobbler.start(); exitVal = proc.waitFor(); log.info("Result: " + exitVal.toString()); } catch (Throwable t) { log.error("Execution Error: " + cmd[0] + " " + cmd[1] + " " + cmd[2], t); } finally { isRunning = false; } return; }
From source file:com.mweagle.tereus.commands.evaluation.common.LambdaUtils.java
public String createFunction(final String logicalResourceName, final String lambdaSourceRoot, final String bucketName, final String s3KeyName) throws IOException, InterruptedException, NoSuchAlgorithmException { // Build it, zip it, and upload it. Return: /*/* ww w. j ava 2s .c om*/ { "S3Bucket" : String, "S3Key" : String, "S3ObjectVersion" : "TODO - not yet implemented" } */ this.logger.info("Looking for source {} relative to {}", lambdaSourceRoot, templateRoot); final String lambdaDir = this.templateRoot.resolve(lambdaSourceRoot).normalize().toAbsolutePath() .toString(); final Path lambdaPath = Paths.get(lambdaDir); // Build command? final Optional<String> buildCommand = lambdaBuildCommand(lambdaDir); if (buildCommand.isPresent()) { this.logger.info("{} Lambda source: {}", buildCommand.get(), lambdaDir); try { Runtime rt = Runtime.getRuntime(); Process pr = rt.exec(buildCommand.get(), null, new File(lambdaDir)); this.logger.info("Waiting for `{}` to complete", buildCommand.get()); final int buildExitCode = pr.waitFor(); if (0 != buildExitCode) { logger.error("Failed to `{}`: {}", buildCommand.get(), buildExitCode); throw new IOException(buildCommand.get() + " failed for: " + lambdaDir); } } catch (Exception ex) { final String processPath = System.getenv("PATH"); this.logger.error("`{}` failed. Confirm that PATH contains the required executable.", buildCommand.get()); this.logger.error("$PATH: {}", processPath); throw ex; } } else { this.logger.debug("No additional Lambda build file detected"); } Path lambdaSource = null; boolean cleanupLambdaSource = false; MessageDigest md = MessageDigest.getInstance("SHA-256"); try { final BiPredicate<Path, java.nio.file.attribute.BasicFileAttributes> matcher = (path, fileAttrs) -> { final String fileExtension = com.google.common.io.Files.getFileExtension(path.toString()); return (fileExtension.toLowerCase().compareTo("jar") == 0); }; // Find/compress the Lambda source // If there is a JAR file in the source root, then use that for the upload List<Path> jarFiles = Files.find(lambdaPath, 1, matcher).collect(Collectors.toList()); if (!jarFiles.isEmpty()) { Preconditions.checkArgument(jarFiles.size() == 1, "More than 1 JAR file detected in directory: {}", lambdaDir); lambdaSource = jarFiles.get(0); md.update(Files.readAllBytes(lambdaSource)); } else { lambdaSource = Files.createTempFile("lambda-", ".zip"); this.logger.info("Zipping lambda source code: {}", lambdaSource.toString()); final FileOutputStream os = new FileOutputStream(lambdaSource.toFile()); final ZipOutputStream zipOS = new ZipOutputStream(os); createStableZip(zipOS, lambdaPath, lambdaPath, md); zipOS.close(); this.logger.info("Compressed filesize: {} bytes", lambdaSource.toFile().length()); cleanupLambdaSource = true; } // Upload it final String sourceHash = Hex.encodeHexString(md.digest()); this.logger.info("Lambda source hash: {}", sourceHash); if (!s3KeyName.isEmpty()) { this.logger.warn( "User supplied S3 keyname overrides content-addressable name. Automatic updates disabled."); } final String keyName = !s3KeyName.isEmpty() ? s3KeyName : String.format("%s-lambda-%s.%s", logicalResourceName, sourceHash, com.google.common.io.Files.getFileExtension(lambdaSource.toString())); JsonObject jsonObject = new JsonObject(); jsonObject.add("S3Bucket", new JsonPrimitive(bucketName)); jsonObject.add("S3Key", new JsonPrimitive(keyName)); // Upload it to s3... final FileInputStream fis = new FileInputStream(lambdaSource.toFile()); try (S3Resource resource = new S3Resource(bucketName, keyName, fis, Optional.of(lambdaSource.toFile().length()))) { this.logger.info("Source payload S3 URL: {}", resource.getS3Path()); if (resource.exists()) { this.logger.info("Source {} already uploaded to S3", keyName); } else if (!this.dryRun) { Optional<String> result = resource.upload(); this.logger.info("Uploaded Lambda source to: {}", result.get()); resource.setReleased(true); } else { this.logger.info("Dry run requested (-n/--noop). Lambda payload upload bypassed."); } } final Gson serializer = new GsonBuilder().disableHtmlEscaping().enableComplexMapKeySerialization() .create(); return serializer.toJson(jsonObject); } finally { if (cleanupLambdaSource) { this.logger.debug("Deleting temporary file: {}", lambdaSource.toString()); Files.deleteIfExists(lambdaSource); } } }
From source file:octopus.teamcity.agent.OctopusBuildProcess.java
private void startOcto(final OctopusCommandBuilder command) throws RunBuildException { String[] userVisibleCommand = command.buildMaskedCommand(); String[] realCommand = command.buildCommand(); logger = runningBuild.getBuildLogger(); logger.activityStarted("Octopus Deploy", DefaultMessagesInfo.BLOCK_TYPE_INDENTATION); logger.message(// w w w .j a v a2s . c o m "Running command: octo.exe " + StringUtils.arrayToDelimitedString(userVisibleCommand, " ")); logger.progressMessage(getLogMessage()); try { Runtime runtime = Runtime.getRuntime(); String octopusVersion = getSelectedOctopusVersion(); ArrayList<String> arguments = new ArrayList<String>(); arguments.add(new File(extractedTo, octopusVersion + "\\octo.exe").getAbsolutePath()); arguments.addAll(Arrays.asList(realCommand)); process = runtime.exec(arguments.toArray(new String[arguments.size()]), null, context.getWorkingDirectory()); final LoggingProcessListener listener = new LoggingProcessListener(logger); standardError = new OutputReaderThread(process.getErrorStream(), new OutputWriter() { public void write(String text) { listener.onErrorOutput(text); } }); standardOutput = new OutputReaderThread(process.getInputStream(), new OutputWriter() { public void write(String text) { listener.onStandardOutput(text); } }); standardError.start(); standardOutput.start(); } catch (IOException e) { final String message = "Error from Octo.exe: " + e.getMessage(); Logger.getInstance(getClass().getName()).error(message, e); throw new RunBuildException(message); } }
From source file:br.com.riselabs.cotonet.builder.commands.ExternalGitCommand.java
/** * OBS: this method returns {@code null} when calling ' * {@code git reset --hard}'./*www . ja v a 2 s.co m*/ * * @return * @throws IOException */ public List<ConflictChunk<CommandLineBlameResult>> call() throws BlameException { Runtime run = Runtime.getRuntime(); Process pr = null; String cmd = null; String[] env = {}; BufferedReader buf; List<ConflictChunk<CommandLineBlameResult>> conflicts = null; int exitCode; try { switch (type) { case RESET: cmd = "git reset --hard"; pr = run.exec(cmd, env, file); break; case BLAME: default: cmd = "git blame -p --line-porcelain"; env = new String[1]; // we need this to disable the pager env[0] = "GIT_PAGER=cat"; pr = run.exec(cmd + " " + file, env, file.getParentFile()); // parse output buf = new BufferedReader(new InputStreamReader(pr.getInputStream())); conflicts = new ArrayList<ConflictChunk<CommandLineBlameResult>>(); final String CONFLICT_START = "<<<<<<<"; final String CONFLICT_SEP = "======="; final String CONFLICT_END = ">>>>>>>"; boolean addBlame = false; ConflictChunk<CommandLineBlameResult> conflict = new ConflictChunk<CommandLineBlameResult>( file.getCanonicalPath()); CommandLineBlameResult bResult; bResult = new CommandLineBlameResult(file.getCanonicalPath()); Blame<CommandLineBlameResult> cBlame; cBlame = new Blame<CommandLineBlameResult>(scenario.getLeft(), bResult); List<String> block; while ((block = readPorcelainBlock(buf)) != null) { String commit = block.get(0).split(" ")[0]; // for (String line : block) // System.out.println(line); Map<PKeys, String> data = getDataFromPorcelainBlock(block); String contentLine = data.get(PKeys.content); int n; if ((n = contentLine.trim().indexOf(" ")) == -1) { // line without blank space contentLine = contentLine.trim(); } else { contentLine = contentLine.trim().substring(0, n); } if (contentLine.equals(CONFLICT_START)) { addBlame = true; continue; } else if (contentLine.equals(CONFLICT_SEP)) { addBlame = true; cBlame.setRevision(scenario.getLeft()); conflict.setBase(scenario.getBase()); conflict.setLeft(cBlame); bResult = new CommandLineBlameResult(file.getCanonicalPath()); cBlame = new Blame<CommandLineBlameResult>(scenario.getRight(), bResult); continue; } else if (contentLine.equals(CONFLICT_END)) { conflict.setRight(cBlame); conflict.setLine(Integer.valueOf(data.get(PKeys.linenumber))); conflicts.add(conflict); addBlame = false; bResult = new CommandLineBlameResult(file.getCanonicalPath()); cBlame = new Blame<CommandLineBlameResult>(scenario.getLeft(), bResult); //@gustavo added this line conflict = new ConflictChunk<CommandLineBlameResult>(file.getCanonicalPath()); } else if (addBlame) { // we are in one of the conflicting chunks Integer linenumber = Integer.valueOf(data.get(PKeys.linenumber)); contentLine = data.get(PKeys.content); String name = data.get(PKeys.authorname); String email = data.get(PKeys.authormail); DeveloperNode dev = new DeveloperNode(name, email); conflict.setLine(linenumber); bResult.addLineAuthor(linenumber, dev); bResult.addLineContent(linenumber, contentLine); bResult.addLineCommit(linenumber, commit); continue; } } buf.close(); break; } /* * already finished to execute the process. now, we should process * the error output. */ buf = new BufferedReader(new InputStreamReader(pr.getErrorStream())); String stdErr = IOUtils.toString(pr.getErrorStream(), StandardCharsets.UTF_8).trim(); IOUtils.closeQuietly(pr.getInputStream()); IOUtils.closeQuietly(pr.getErrorStream()); IOUtils.closeQuietly(pr.getOutputStream()); exitCode = pr.waitFor(); buf.close(); if (!stdErr.isEmpty()) { Logger.log(String.format("Execution of '%s' returned standard error output:%n%s", cmd, stdErr)); throw new RuntimeException( String.format("Error on external call with exit code %d", pr.exitValue())); } } catch (IOException io) { try { throw new BlameException(file.getCanonicalPath(), "IO Exception", io); } catch (IOException e) { } } catch (InterruptedException ie) { // waitFor() exception exitCode = 666; try { throw new BlameException(file.getCanonicalPath(), String.format( "Interrupted while waiting for '%s' to finish. Error code: '%s'", cmd, exitCode), ie); } catch (IOException io) { } } catch (RuntimeException re) { try { throw new BlameException(file.getCanonicalPath(), "Runtime Exception", re); } catch (IOException e) { } } finally { run.freeMemory(); } pr.destroyForcibly(); return conflicts; }
From source file:org.squale.squalix.util.process.ProcessManager.java
/** * Lancement du processus externe//w w w. java2 s. co m * * @param pHandler interface de traitement des erreurs * @return code de retour d'excution * @throws IOException si erreur * @throws InterruptedException si erreur */ public int startProcess(ProcessErrorHandler pHandler) throws IOException, InterruptedException { int result; Runtime runtime = Runtime.getRuntime(); // Informations de debug if (LOGGER.isDebugEnabled()) { LOGGER.debug(Messages.getString("process.dir") + mDir); for (int i = 0; i < mCommand.length; i++) { LOGGER.debug(Messages.getString("process.argument") + i + " " + mCommand[i]); } } // Vrification de l'existence du rpertoire de lancement // cel peut tre l'origine de situations de blocage if ((mDir != null) && (!mDir.exists() || !mDir.isDirectory())) { throw new IOException("unexisting directory: " + mDir); } Process processCheck = runtime.exec(mCommand, mEnvp, mDir); /* * Pour viter le lock du process, il faut envoyer le flux d'erreur et le flux de sortie sur des threads. */ ProcessErrorStream err = new ProcessErrorStream(processCheck.getErrorStream(), pHandler); Thread errorThread = new Thread(err, "StderrStreamConsumer"); errorThread.start(); ProcessOutputStream outp = createOutputStream(processCheck.getInputStream(), mOutputHandler); Thread outputThread = new Thread(outp, "StdoutStreamConsumer"); outputThread.start(); /* Obtention du code de retour du process */ result = processCheck.waitFor(); // Attente de la terminaison des threads // pour etre certain de recuperer les donnes // Voir bugid 4422496 de Sun outputThread.join(); errorThread.join(); return result; }