List of usage examples for java.lang ProcessBuilder start
public Process start() throws IOException
From source file:husky.server.HuskyMaster.java
@Override public void run() { try {/*from w w w .j a va2 s . c om*/ LOG.info("Starting husky master process"); ProcessBuilder mHuskyMasterProcess = new ProcessBuilder(getCommands()); if (!mAppMaster.getLdLibraryPath().isEmpty()) { mHuskyMasterProcess.environment().put("LD_LIBRARY_PATH", mAppMaster.getLdLibraryPath()); } mHuskyMasterProcess.redirectOutput(new File(mAppMaster.getAppMasterLogDir() + "/HuskyMaster.stdout")); mHuskyMasterProcess.redirectError(new File(mAppMaster.getAppMasterLogDir() + "/HuskyMaster.stderr")); Process p = mHuskyMasterProcess.start(); p.waitFor(); if (p.exitValue() == 0) { LOG.info("Husky master exits successfully"); } else { LOG.info("Husky master exits with code " + p.exitValue()); } } catch (Exception e) { LOG.log(Level.SEVERE, " Failed to start c++ husky master process: ", e); } finally { if (!mAppMaster.getLogPathToHDFS().isEmpty()) { try { mAppMaster.getFileSystem().copyFromLocalFile(false, true, new Path[] { new Path(mAppMaster.getAppMasterLogDir() + "/HuskyMaster.stdout"), new Path(mAppMaster.getAppMasterLogDir() + "/HuskyMaster.stderr") }, new Path(mAppMaster.getLogPathToHDFS())); } catch (IOException e) { LOG.log(Level.INFO, "Failed to upload logs of husky master to hdfs", e); } } } }
From source file:edu.clemson.cs.nestbed.server.management.instrumentation.ProgramCompileManagerImpl.java
private void loadProgramSymbols(Program program, String tosPlatform) throws IOException { ProcessBuilder processBuilder = new ProcessBuilder(GET_SYMBOLS, program.getSourcePath() + "/build/" + tosPlatform + "/main.exe"); processBuilder.redirectErrorStream(true); Process process = processBuilder.start(); BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream())); for (String line = in.readLine(); line != null; line = in.readLine()) { try {/*from w w w . java 2 s . c o m*/ log.debug("Program symbol line: " + line); String[] tokens = line.split("\\s"); int address = Integer.parseInt(tokens[0], 16); int size = Integer.parseInt(tokens[1], 16); String module = tokens[2].substring(0, tokens[2].indexOf('.')); String symbol = tokens[2].substring(tokens[2].indexOf('.') + 1); log.debug("Address = " + address + "size = " + size + "module = " + module + "symbol = " + symbol); ProgramSymbolManagerImpl.getInstance().createProgramSymbol(program.getID(), module, symbol, address, size); } catch (StringIndexOutOfBoundsException ex) { log.error(ex); } } }
From source file:android.databinding.compilationTest.BaseCompilationTest.java
protected CompilationResult runGradle(String... params) throws IOException, InterruptedException { setExecutable();//from w ww . j a va 2 s.c om File pathToExecutable = new File(testFolder, "gradlew"); List<String> args = new ArrayList<>(); args.add(pathToExecutable.getAbsolutePath()); args.add("-P" + PRINT_ENCODED_ERRORS_PROPERTY + "=true"); args.add("--project-cache-dir"); args.add(new File("../.caches/", name.getMethodName()).getAbsolutePath()); Collections.addAll(args, params); ProcessBuilder builder = new ProcessBuilder(args); builder.environment().putAll(System.getenv()); String javaHome = System.getProperty("java.home"); if (StringUtils.isNotBlank(javaHome)) { builder.environment().put("JAVA_HOME", javaHome); } builder.directory(testFolder); Process process = builder.start(); String output = IOUtils.toString(process.getInputStream()); String error = IOUtils.toString(process.getErrorStream()); int result = process.waitFor(); return new CompilationResult(result, output, error); }
From source file:facs.utils.Billing.java
/** * creates temporary tex file and executes pdflatex in order to create the final pdf file WARNING: * Be sure that you have set all parameters before executing that method. Otherwise you will get a * apache velocity error./*from w w w. j av a 2s .co m*/ * * @return * @throws IOException * @throws InterruptedException */ public File createPdf() throws IOException, InterruptedException { if (!tempTexFile.exists()) { tempTexFile.createNewFile(); } FileWriter fw = new FileWriter(tempTexFile.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); template.merge(context, bw); bw.close(); List<String> cmd = new ArrayList<String>( Arrays.asList(pdflatexPath, "-interaction=nonstopmode", tempTexFile.getName())); String basename = FilenameUtils.getBaseName(tempTexFile.getName()); String fileNamme = basename + ".pdf"; File resultFile = Paths.get(tempTexFile.getParent(), fileNamme).toFile(); // Runtime rt = Runtime.getRuntime(); // Process p = rt.exec(cmd); ProcessBuilder pb = new ProcessBuilder(cmd); pb.directory(tempTexFile.getParentFile()); System.out.println("Basename: " + basename + " fileNamme: " + fileNamme); Process p = pb.start(); int exitValue = p.waitFor(); if (exitValue != 0 && !resultFile.exists()) { StringBuffer sb = new StringBuffer(); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = ""; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } System.out.println(sb.toString()); // TODO There is for sure a better exception to say that pdflatex failed? throw new FileNotFoundException("result file " + resultFile.getAbsolutePath() + "does not exist."); } else { return resultFile; } }
From source file:com.diversityarrays.kdxplore.trialdesign.JobRunningTask.java
@Override public Either<String, AlgorithmRunResult> generateResult(Closure<Void> arg0) throws Exception { AlgorithmRunResult result = new AlgorithmRunResult(algorithmName, algorithmFolder); ProcessBuilder pb = new ProcessBuilder(command); File tempAlgorithmOutputFile = new File(algorithmFolder, "stdout.txt"); File tempAlgorithmErrorFile = new File(algorithmFolder, "stderr.txt"); //pb.redirectErrorStream(true); tempAlgorithmErrorFile.createNewFile(); tempAlgorithmOutputFile.createNewFile(); pb.redirectOutput(tempAlgorithmOutputFile); pb.redirectError(tempAlgorithmErrorFile); Process process = pb.start(); while (!process.waitFor(1000, TimeUnit.MILLISECONDS)) { if (backgroundRunner.isCancelRequested()) { process.destroy();/*w w w . j a v a2 s .co m*/ throw new CancellationException(); } } int exitCode = process.exitValue(); if (exitCode != 0) { String errtxt = Algorithms.readContent("Error Output: (code=" + exitCode + ")", new FileInputStream(tempAlgorithmErrorFile)); return Either.left(errtxt); } if (!kdxploreOutputFile.exists()) { return Either.left("Missing output file: " + kdxploreOutputFile.getPath()); } result.addTrialEntries(kdxploreOutputFile, userTrialEntries); return Either.right(result); }
From source file:edu.umn.msi.tropix.common.execution.process.impl.ProcessFactoryImpl.java
public Process createProcess(final ProcessConfiguration processConfiguration) { final List<String> command = new LinkedList<String>(); final String application = processConfiguration.getApplication(); Preconditions.checkNotNull(application, "Attempted to create process with null application."); command.add(application);//from www. ja v a 2s . com final List<String> arguments = processConfiguration.getArguments(); if (arguments != null) { command.addAll(processConfiguration.getArguments()); } LOG.trace("Creating process builder with commands " + Joiner.on(" ").join(command) + " in directory " + processConfiguration.getDirectory()); final ProcessBuilder processBuilder = new ProcessBuilder(command); if (processConfiguration.getEnvironment() != null) { for (final Entry<String, String> entry : processConfiguration.getEnvironment().entrySet()) { processBuilder.environment().put(entry.getKey(), entry.getValue()); } } processBuilder.directory(processConfiguration.getDirectory()); java.lang.Process baseProcess = null; try { baseProcess = processBuilder.start(); } catch (final IOException e) { throw new IllegalStateException( "Failed to start process corresponding to process configuration " + processConfiguration, e); } final ProcessImpl process = new ProcessImpl(); process.setBaseProcess(baseProcess); return process; }
From source file:io.hops.hopsworks.api.jupyter.JupyterService.java
@GET @Path("/convertIPythonNotebook/{path: .+}") @AllowedProjectRoles({ AllowedProjectRoles.DATA_OWNER, AllowedProjectRoles.DATA_SCIENTIST }) public Response convertIPythonNotebook(@PathParam("path") String path, @Context SecurityContext sc) throws ServiceException { String hdfsUsername = getHdfsUser(sc); String hdfsFilename = "/Projects/" + this.project.getName() + "/" + path; String prog = settings.getHopsworksDomainDir() + "/bin/convert-ipython-notebook.sh"; String[] command = { prog, hdfsFilename, hdfsUsername }; LOGGER.log(Level.INFO, Arrays.toString(command)); ProcessBuilder pb = new ProcessBuilder(command); try {//from w w w . j a va2s.c o m Process process = pb.start(); BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = br.readLine()) != null) { // do nothing } int errCode = process.waitFor(); if (errCode != 0) { throw new ServiceException(RESTCodes.ServiceErrorCode.IPYTHON_CONVERT_ERROR, Level.SEVERE, "error code: " + errCode); } } catch (IOException | InterruptedException ex) { throw new ServiceException(RESTCodes.ServiceErrorCode.IPYTHON_CONVERT_ERROR, Level.SEVERE, null, ex.getMessage(), ex); } return noCacheResponse.getNoCacheResponseBuilder(Response.Status.OK).build(); }
From source file:com.appcel.core.encoder.executor.FfmpegEncoderExecutor.java
public void execute(MediaRecord record, File directory) throws EncoderException { LOGGER.info(" ffmpeg ? video ... Ffmpeg ===>>> " + args); final ProcessBuilder pb = new ProcessBuilder().directory(directory); pb.redirectErrorStream(true);// www .jav a2s . c o m if (null != directory) { LOGGER.info("ffmpeg ??==========>>>" + directory.toString()); } pb.command(args); try { final Process process = pb.start(); inputStream = process.getInputStream(); MediaInputStreamParser.parseMediaRecord(inputStream, record); outputStream = process.getOutputStream(); errorStream = process.getErrorStream(); // ???????. // BufferedInputStream in = new BufferedInputStream(inputStream); // BufferedReader inBr = new BufferedReader(new InputStreamReader(in)); // String lineStr; // while ((lineStr = inBr.readLine()) != null) // LOGGER.info("process.getInputStream() ===>>> " + lineStr); int waitfor = process.waitFor(); if (waitfor != 0) { //p.exitValue()==0?1?? if (process.exitValue() == 1) { LOGGER.info("===>>> ffmpeg ? Failed!"); throw new EncoderException("ffmpeg ? Failed!"); } else { LOGGER.info("==========>>> ffmpeg ??."); } } else { LOGGER.info("==========>>> ffmpeg ??."); } } catch (IOException e) { LOGGER.error("==========>>> ffmpeg ? Message: " + e.getMessage()); LOGGER.error("==========>>> ffmpeg ? Cause: " + e.getCause()); e.printStackTrace(); } catch (InterruptedException e) { LOGGER.error("==========>>> ffmpeg ? Message: " + e.getMessage()); LOGGER.error("==========>>> ffmpeg ? Cause: " + e.getCause()); e.printStackTrace(); Thread.currentThread().interrupt(); } finally { destroy(); } }
From source file:com.sms.server.service.parser.MetadataParser.java
public MediaElement parse(MediaElement mediaElement) { try {/*from ww w. j a v a 2s.c om*/ // Use transcoder to parse file metadata File parser = transcodeService.getTranscoder(); String[] command = new String[] { parser.getAbsolutePath(), "-i", mediaElement.getPath() }; ProcessBuilder processBuilder = new ProcessBuilder(command).redirectErrorStream(true); Process process = processBuilder.start(); String[] metadata = readInputStream(process.getInputStream()); // Get Media Type Byte mediaType = mediaElement.getType(); // Begin Parsing for (String line : metadata) { Matcher matcher; if (mediaType == MediaElementType.AUDIO || mediaType == MediaElementType.VIDEO) { // // Duration // matcher = DURATION.matcher(line); if (matcher.find()) { int hours = Integer.parseInt(matcher.group(1)); int minutes = Integer.parseInt(matcher.group(2)); int seconds = Integer.parseInt(matcher.group(3)); mediaElement.setDuration(hours * 3600 + minutes * 60 + seconds); } // // Bitrate // matcher = BITRATE.matcher(line); if (matcher.find()) { mediaElement.setBitrate(Integer.parseInt(matcher.group(1))); } // // Audio Stream // matcher = AUDIO_STREAM.matcher(line); if (matcher.find()) { // Language // Always set audio language for video elements if (matcher.group(1) == null && mediaType == MediaElementType.VIDEO) { mediaElement.setAudioLanguage( addToCommaSeparatedList(mediaElement.getAudioLanguage(), "und")); } // Set audio language if present if (matcher.group(1) != null) { mediaElement.setAudioLanguage(addToCommaSeparatedList(mediaElement.getAudioLanguage(), String.valueOf(matcher.group(2)))); } // Codec mediaElement.setAudioCodec(addToCommaSeparatedList(mediaElement.getAudioCodec(), String.valueOf(matcher.group(3)))); //Sample Rate mediaElement.setAudioSampleRate(addToCommaSeparatedList(mediaElement.getAudioSampleRate(), String.valueOf(matcher.group(4)))); //Configuration mediaElement.setAudioConfiguration(addToCommaSeparatedList( mediaElement.getAudioConfiguration(), String.valueOf(matcher.group(5)))); } } if (mediaType == MediaElementType.AUDIO) { // // Title // matcher = TITLE.matcher(line); if (matcher.find()) { mediaElement.setTitle(String.valueOf(matcher.group(1))); } // // Artist // matcher = ARTIST.matcher(line); if (matcher.find()) { mediaElement.setArtist(String.valueOf(matcher.group(2))); } // // Album Artist // matcher = ALBUMARTIST.matcher(line); if (matcher.find()) { mediaElement.setAlbumArtist(String.valueOf(matcher.group(2))); } // // Album // matcher = ALBUM.matcher(line); if (matcher.find()) { mediaElement.setAlbum(String.valueOf(matcher.group(1))); } // // Comment // matcher = COMMENT.matcher(line); if (matcher.find()) { mediaElement.setDescription(String.valueOf(matcher.group(1))); } // // Date // matcher = YEAR.matcher(line); if (matcher.find()) { mediaElement.setYear(Short.parseShort(matcher.group(2))); } // // Disc Number // matcher = DISCNUMBER.matcher(line); if (matcher.find()) { mediaElement.setDiscNumber(Byte.parseByte(matcher.group(2))); } // // Disc Subtitle // matcher = DISCSUBTITLE.matcher(line); if (matcher.find()) { mediaElement.setDiscSubtitle(String.valueOf(matcher.group(1))); } // // Track Number // matcher = TRACK.matcher(line); if (matcher.find()) { mediaElement.setTrackNumber(Short.parseShort(matcher.group(1))); } // // Genre // matcher = GENRE.matcher(line); if (matcher.find()) { mediaElement.setGenre(String.valueOf(matcher.group(1))); } } if (mediaType == MediaElementType.VIDEO) { // // Video Stream // matcher = VIDEO_STREAM.matcher(line); // Only pull metadata for the first video stream (embedded images are also detected as video...) if (matcher.find() && mediaElement.getVideoCodec() == null) { // Codec mediaElement.setVideoCodec(String.valueOf(matcher.group(1))); // Dimensions short width = Short.parseShort(matcher.group(2)); short height = Short.parseShort(matcher.group(3)); if (width > 0 && height > 0) { mediaElement.setVideoWidth(width); mediaElement.setVideoHeight(height); } } // // Subtitle Stream // matcher = SUBTITLE_STREAM.matcher(line); if (matcher.find()) { // Language if (matcher.group(1) == null) { mediaElement.setSubtitleLanguage( addToCommaSeparatedList(mediaElement.getSubtitleLanguage(), "und")); } else { mediaElement.setSubtitleLanguage(addToCommaSeparatedList( mediaElement.getSubtitleLanguage(), String.valueOf(matcher.group(2)))); } // Format mediaElement.setSubtitleFormat(addToCommaSeparatedList(mediaElement.getSubtitleFormat(), String.valueOf(matcher.group(3)))); //Forced if (matcher.group(4) == null) { mediaElement.setSubtitleForced( addToCommaSeparatedList(mediaElement.getSubtitleForced(), "false")); } else { mediaElement.setSubtitleForced( addToCommaSeparatedList(mediaElement.getSubtitleForced(), "true")); } } } } } catch (IOException x) { LogService.getInstance().addLogEntry(LogService.Level.ERROR, CLASS_NAME, "Unable to parse metadata for file " + mediaElement.getPath(), x); } return mediaElement; }