@Override public void execute() throws LifecycleException { Process process = null; try { List<String> command = new ShutdownAdminServerCommand().getCommand(); ProcessBuilder builder = new ProcessBuilder(command); builder.redirectErrorStream(true); process = builder.start(); Thread consoleConsumer = new Thread(new ConsoleConsumer(process, configuration.isOutputToConsole())); consoleConsumer.setDaemon(true); consoleConsumer.start(); while (isServerRunning()) { try { Thread.sleep(500L); } catch (InterruptedException e) { logger.log(Level.INFO, "Container shutdown interrupted"); throw e; } } logger.log(Level.INFO, "Stopped WebLogic Server."); return; } catch (Exception ex) { throw new LifecycleException("Container shutdown failed.", ex); } }
private static void testDynamicNumberOfGCThreads(String gcFlag) throws Exception { // UseDynamicNumberOfGCThreads and TraceDynamicGCThreads enabled String[] baseArgs = { "-XX:+" + gcFlag, "-Xmx10M", "-XX:+UseDynamicNumberOfGCThreads", "-Xlog:gc+task=trace", GCTest.class.getName() }; // Base test with gc and +UseDynamicNumberOfGCThreads: ProcessBuilder pb_enabled = ProcessTools.createJavaProcessBuilder(baseArgs); verifyDynamicNumberOfGCThreads(new OutputAnalyzer(pb_enabled.start())); // Ensure it also works on uniprocessors or if user specifies -XX:ParallelGCThreads=1: String[] extraArgs = { "-XX:+UnlockDiagnosticVMOptions", "-XX:+ForceDynamicNumberOfGCThreads", "-XX:ParallelGCThreads=1" }; String[] finalArgs = new String[baseArgs.length + extraArgs.length]; System.arraycopy(extraArgs, 0, finalArgs, 0, extraArgs.length); System.arraycopy(baseArgs, 0, finalArgs, extraArgs.length, baseArgs.length); pb_enabled = ProcessTools.createJavaProcessBuilder(finalArgs); verifyDynamicNumberOfGCThreads(new OutputAnalyzer(pb_enabled.start())); // Turn on parallel reference processing String[] parRefProcArg = {"-XX:+ParallelRefProcEnabled", "-XX:-ShowMessageBoxOnError"}; String[] parRefArgs = new String[baseArgs.length + parRefProcArg.length]; System.arraycopy(parRefProcArg, 0, parRefArgs, 0, parRefProcArg.length); System.arraycopy(baseArgs, 0, parRefArgs, parRefProcArg.length, baseArgs.length); pb_enabled = ProcessTools.createJavaProcessBuilder(parRefArgs); verifyDynamicNumberOfGCThreads(new OutputAnalyzer(pb_enabled.start())); }
/** * @return * @throws IllegalStateException if {@code tesseract} binary invoked with {@code --list-langs} * returns a code {@code != 0} */ public List<String> getAvailableLanguages() throws IllegalStateException, IOException, InterruptedException { ProcessBuilder tesseractProcessBuilder = new ProcessBuilder(this.getBinary(), "--list-langs"); Process tesseractProcess = tesseractProcessBuilder.redirectOutput(ProcessBuilder.Redirect.PIPE).start(); int tesseractProcessReturnCode = tesseractProcess.waitFor(); String tesseractProcessStdout = IOUtils.toString(tesseractProcess.getInputStream()); String tesseractProcessStderr = IOUtils.toString(tesseractProcess.getErrorStream()); if (tesseractProcessReturnCode != 0) { throw new IllegalStateException( String.format( "The tesseract process '%s' unexpectedly returned with non-zero return code %d and output '%s' (stdout) and '%s' (stderr).", this.getBinary(), tesseractProcessReturnCode, tesseractProcessStdout, tesseractProcessStderr)); } // tesseract --list-langs prints to stderr, reported as // https://bugs.launchpad.net/ubuntu/+source/tesseract/+bug/1481015 List<String> langs = new LinkedList<>(); for (String lang : tesseractProcessStderr.split("\n")) { if (!lang.startsWith("List of available languages")) { langs.add(lang); } } Collections.sort(langs, String.CASE_INSENSITIVE_ORDER); return langs; }
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // some code String param = request.getHeader("foo"); String a1 = ""; String a2 = ""; String osName = System.getProperty("os.name"); if (osName.indexOf("Windows") != -1) { a1 = "cmd.exe"; a2 = "/c"; } else { a1 = "sh"; a2 = "-c"; } String[] args = {a1, a2, "echo", param}; ProcessBuilder pb = new ProcessBuilder(); pb.command(args); try { Process p = pb.start(); org.owasp.benchmark.helpers.Utils.printOSCommandResults(p); } catch (IOException e) { System.out.println( "Problem executing cmdi - java.lang.ProcessBuilder(java.util.List) Test Case"); throw new ServletException(e); } }
public static void mountExt4() { makeDirectory(Constants.MOUNT_PATH); try { final ProcessBuilder pb = new ProcessBuilder("mount", Constants.NBD_DEVICE, Constants.MOUNT_PATH); final StringBuilder err = new StringBuilder(); final Process startClientProcess = pb.start(); final BufferedReader stdErr = new BufferedReader( new InputStreamReader(startClientProcess.getErrorStream(), StandardCharsets.UTF_8)); final BufferedReader stdOut = new BufferedReader( new InputStreamReader(startClientProcess.getInputStream(), StandardCharsets.UTF_8)); startClientProcess.waitFor(); errorHandler(startClientProcess, stdErr, stdOut, err); } catch (final IOException e) { throw new RuntimeException(e); } catch (final InterruptedException e) { throw new RuntimeException(e); } }
/** * Change local file's permission. * * @param filePath that will change permission * @param perms the permission, e.g. "775" * @throws IOException */ public static void changeLocalFilePermission(String filePath, String perms) throws IOException { // TODO switch to java's Files.setPosixFilePermissions() if java 6 support is dropped List<String> commands = new ArrayList<String>(); commands.add("/bin/chmod"); commands.add(perms); File file = new File(filePath); commands.add(file.getAbsolutePath()); try { ProcessBuilder builder = new ProcessBuilder(commands); Process process = builder.start(); process.waitFor(); redirectIO(process); if (process.exitValue() != 0) { throw new IOException( "Can not change the file " + file.getAbsolutePath() + " 's permission to be " + perms); } } catch (InterruptedException e) { LOG.error(e.getMessage()); throw new IOException(e); } }
public Process createProcess() throws ExecutionException { if (LOG.isDebugEnabled()) { LOG.debug("Executing [" + getCommandLineString() + "]"); } List<String> commands; try { checkWorkingDirectory(); if (StringUtil.isEmptyOrSpaces(myExePath)) { throw new ExecutionException( IdeBundle.message("run.configuration.error.executable.not.specified")); } commands = CommandLineUtil.toCommandLine(myExePath, myProgramParams.getList()); } catch (ExecutionException e) { LOG.warn(e); throw e; } try { ProcessBuilder builder = new ProcessBuilder(commands); setupEnvironment(builder.environment()); builder.directory(myWorkDirectory); builder.redirectErrorStream(myRedirectErrorStream); return builder.start(); } catch (IOException e) { LOG.warn(e); throw new ProcessNotCreatedException(e.getMessage(), e, this); } }
public StreamSink createStreamSink(ServiceContext context, Flow flow) { List<String> commandList = new ArrayList<String>(); String cmd = command.evaluateString(context, flow); commandList.add(cmd); for (int i = 0; i < commandArgs.length; ++i) { String arg = commandArgs[i].evaluateString(context, flow); commandList.add(arg); } ProcessBuilder processBuilder = new ProcessBuilder(commandList); Map<String, String> environment = processBuilder.environment(); for (int i = 0; i < envVariableFactories.length; ++i) { EnvVariable envVariable = envVariableFactories[i].createEnvVariable(context, flow); environment.put(envVariable.getName(), envVariable.getValue()); } String directory = dirResolver.evaluateAsString(flow.getParameters(), flow.getRecord()); if (directory.length() > 0) { File file = new File(directory); processBuilder.directory(file); } StreamSink streamSink = new CommandSink(processBuilder, charset); return streamSink; }
/** * ====================================================================================== * TESSERACT GRAB TEXT FROM IMAGE * ====================================================================================== */ public String grabText(String image) throws Exception { findAndCropImageFromScreen(image); String imageInput = screenshotsFolder + getScreenshotsCounter() + "_" + image + "_screenshot" + getRetryCounter() + "_" + timeDifferenceStartTest + "sec" + ".png"; String[] tesseractCommand = {"tesseract", imageInput, "stdout"}; String value = ""; try { ProcessBuilder p = new ProcessBuilder(tesseractCommand); Process proc = p.start(); InputStream stdin = proc.getInputStream(); InputStreamReader isr = new InputStreamReader(stdin); BufferedReader br = new BufferedReader(isr); String line; String[] size = null; String[] splitLines; while ((line = br.readLine()) != null) { value += line; } } catch (Throwable t) { t.printStackTrace(); } return value; }
@Override public Process execute(List<String> command, boolean terminal) throws Exception { if (terminal) { File commandFile = File.createTempFile("cmd-", ""); commandFile.deleteOnExit(); String commandPath = commandFile.toString(); String commandLine = getCommandLine(command); IOUtil.writeUTF8(commandFile, commandLine); List<String> chmodCommand = new ArrayList<String>(); chmodCommand.add("chmod"); chmodCommand.add("a+x"); chmodCommand.add(commandPath); ProcessBuilder chmodProcessBuilder = new ProcessBuilder(chmodCommand); Process chmodProcess = chmodProcessBuilder.start(); chmodProcess.waitFor(); List<String> terminalCommand = new ArrayList<String>(); terminalCommand.add("open"); terminalCommand.add("-b"); terminalCommand.add("com.apple.terminal"); terminalCommand.add(commandPath); command = terminalCommand; } return super.execute(command, terminal); }
@Before public void setUp() throws Exception { FileUtils.deleteDirectory(SVN_DIR); System.out.println("setup..."); SVN_DIR.mkdirs(); ProcessBuilder builder = new ProcessBuilder(SVNADMIN_EXEC, "create", SVN_DIR.getAbsolutePath()); builder.redirectErrorStream(true); Process process = builder.start(); process.waitFor(); FileUtils.writeStringToFile( new File(SVN_DIR, "conf/svnserve.conf"), "[general]\npassword-db = passwd", null); FileUtils.writeStringToFile(new File(SVN_DIR, "conf/passwd"), "[users]\nguest = guest", null); System.out.println("setup ok."); writer = context.mock(LrdWriter.class); repositoryBean = new RepositoryBean(); repositoryBean.setUrl(SVN_URL); repositoryBean.setUserName(SVN_USER); repositoryBean.setPassword(SVN_PASS); }
@Test public void simpleExternalIntegrationTest() throws Exception { String jacocoAgentCmd = System.getProperty("jacocoAgentCmd"); File jre = new File(System.getProperty("java.home")); File bin = new File(jre, "bin"); File java = new File(bin, "java"); List<String> cmd = new ArrayList<>(); cmd.add(java.getAbsolutePath()); if (jacocoAgentCmd != null) { /** * Note: Jacoco will append (by default) execution data to an already existing execution file. */ cmd.add(jacocoAgentCmd); } cmd.add("-cp"); cmd.add(System.getProperty("java.class.path")); cmd.add(External.class.getName()); ProcessBuilder pb = new ProcessBuilder(cmd); Process process = pb.inheritIO().start(); int exitValue = process.waitFor(); System.out.println("JVM exit with " + exitValue); }
private static void checkIsAvailableAndGetVersion() { ProcessBuilder pb = new ProcessBuilder(COMMAND, "--version"); pb.redirectErrorStream(true); Process p = null; try { p = pb.start(); p.waitFor(); perconaToolkitVersion = StreamUtil.getStreamContents(p.getInputStream()); if (perconaToolkitVersion != null) { perconaToolkitVersion = perconaToolkitVersion.replaceAll("\n|\r", ""); } available = true; log.info("Using percona toolkit: " + perconaToolkitVersion); } catch (IOException e) { available = false; } catch (InterruptedException e) { available = false; } finally { if (p != null) { StreamUtil.closeQuietly(p.getErrorStream()); StreamUtil.closeQuietly(p.getInputStream()); StreamUtil.closeQuietly(p.getOutputStream()); p.destroy(); } } }
@Override public void run() { try { // File meteocalc = new // File(facade.getConstants().getMeteoOrderDir()+facade.getConstants().getMeteoOrderCommand()); String[] command = { "CMD", "/C", facade.getConstants().getImageOrderCommand(), getId().toString() }; ProcessBuilder processBuilder = new ProcessBuilder(command); processBuilder.directory(new File(facade.getConstants().getImageOrderDir())); LOG.debug("ImageOrder #" + this.getId() + " prepared for execution. Starting."); Process process = processBuilder.start(); process.waitFor(); LOG.debug("ImageOrder #" + this.getId() + " finished execution"); facade.getOrderProcessor().releaseProcessor(this); String url = facade.getConstants().getMeteoOrderDir() + "OUT_IMAGES/" + getId() + "." + facade.getConstants().getImageFormat(); if (new File(url).canRead()) { setImageURL(url); setStatus(Status.READY_FOR_PICKUP); } else { throw new Exception("Image file was not created or cannot to be read"); } } catch (Exception e) { LOG.error(e); throw new RuntimeException(e); } }
public static void main(String[] args) throws Exception { final float heapSizeMegs = Runtime.getRuntime().maxMemory() / 1024L / 1024L; if (heapSizeMegs > 511.0F) { LauncherFrame.main(args); } else { try { final String pathToJar = MCLauncher.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath(); final ArrayList<String> params = new ArrayList<String>(); params.add("javaw"); params.add("-Xmx1024m"); params.add("-Dsun.java2d.noddraw=true"); params.add("-Dsun.java2d.d3d=false"); params.add("-Dsun.java2d.opengl=false"); params.add("-Dsun.java2d.pmoffscreen=false"); params.add("-classpath"); params.add(pathToJar); params.add("com.kokakiwi.mclauncher.LauncherFrame"); final ProcessBuilder pb = new ProcessBuilder(params); final Process process = pb.start(); if (process == null) { throw new Exception("!"); } System.exit(0); } catch (final Exception e) { e.printStackTrace(); LauncherFrame.main(args); } } }
public boolean findDeviceTypeADB() throws Exception { log("trying to find device type ..."); log("------------------------------"); if (platformName.equalsIgnoreCase("iOS")) { // TO Be added } else { String adb = "adb"; String[] adbCommand = {adb, "shell", "getprop", "ro.build.characteristics"}; try { ProcessBuilder p = new ProcessBuilder(adbCommand); Process proc = p.start(); InputStream stdin = proc.getInputStream(); InputStreamReader isr = new InputStreamReader(stdin); BufferedReader br = new BufferedReader(isr); String line = null; String[] size = null; while ((line = br.readLine()) != null) { if (line.contains("tablet")) { return true; } } } catch (Throwable t) { t.printStackTrace(); } } return false; }
private static String readProcessOutput(String command, String arguments) { String result = ""; ProcessBuilder pb = new ProcessBuilder(command, arguments); pb.redirectErrorStream(true); try { Process process = pb.start(); InputStream stdout = process.getInputStream(); final BufferedReader brstdout = new BufferedReader(new InputStreamReader(stdout)); String line = null; try { StringBuilder stringBuilder = new StringBuilder(); while ((line = brstdout.readLine()) != null) { stringBuilder.append(line); } result = stringBuilder.toString(); } catch (Exception e) { } finally { IOUtils.closeQuietly(brstdout); IOUtils.closeQuietly(stdout); } } catch (Throwable e) { e.printStackTrace(); } return result; }
/** * Method description * * @return * @throws IOException */ protected Process createProcess() throws IOException { if (logger.isDebugEnabled()) { StringBuilder cmd = new StringBuilder(); for (String c : command) { cmd.append(c).append(" "); } logger.debug("start external process '{}'", cmd.toString()); } ProcessBuilder processBuilder = new ProcessBuilder(command); if (workDirectory != null) { processBuilder = processBuilder.directory(workDirectory); } Map<String, String> env = processBuilder.environment(); if (useSystemEnvironment) { env.putAll(System.getenv()); } if (environment != null) { env.putAll(environment); } return processBuilder.redirectErrorStream(true).start(); }
private void kill_pcscd() { File f = new File(ctx.getFilesDir() + "/pcscd/pcscd.pid"); FileInputStream fis = null; if (f.exists()) { try { // read pid fis = new FileInputStream(f); byte[] pid = new byte[fis.available()]; int num = fis.read(pid); if (num > 0) { // kill pcsc daemon ProcessBuilder pb = new ProcessBuilder("kill", "-9", new String(pid, "UTF-8")); pb.start(); } // cleanup files String del = ctx.getFilesDir() + "/pcscd/*"; ProcessBuilder pb = new ProcessBuilder("rm", "-r", del); pb.start(); } catch (IOException e) { logger.error("Killing the pcsc daemon or cleanup failed.", e); } finally { try { if (fis != null) { fis.close(); } } catch (IOException e) { // ignore } } } }
public void setUpSolrFile(String url) throws Exception { if (setUpIsDone) { return; } // do the setup File testDir = (Paths.get(getClass().getResource("/" + testFile).toURI()).getParent()).toFile(); ProcessBuilder pb = new ProcessBuilder("java", "-Durl=" + url + "/update", "-jar", "post.jar", testFile); pb.directory(testDir); LOGGER.log(Level.FINE, "Starting SOLR import"); final Process command = pb.start(); LOGGER.log(Level.FINE, "Started SOLR import"); String line; BufferedReader bri = new BufferedReader(new InputStreamReader(command.getInputStream())); BufferedReader bre = new BufferedReader(new InputStreamReader(command.getErrorStream())); while ((line = bri.readLine()) != null) { LOGGER.log(Level.FINE, line); } bri.close(); while ((line = bre.readLine()) != null) { LOGGER.log(Level.FINE, line); } bre.close(); int i = command.waitFor(); assertTrue(i == 0); LOGGER.log(Level.FINE, "SOLR import DONE!"); setUpIsDone = true; }
public static void main (String[] args) { System.out.println(\u00CB); try { if (!Platform.shouldSAAttach()) { System.out.println("SA attach not expected to work - test skipped."); return; } int pid = ProcessTools.getProcessId(); JDKToolLauncher jmap = JDKToolLauncher.create("jmap") .addToolArg("-F") .addToolArg("-dump:live,format=b,file=" + dumpFile) .addToolArg(Integer.toString(pid)); ProcessBuilder pb = new ProcessBuilder(jmap.getCommand()); OutputBuffer output = ProcessTools.getOutput(pb); Process p = pb.start(); int e = p.waitFor(); System.out.println("stdout:"); System.out.println(output.getStdout()); System.out.println("stderr:"); System.out.println(output.getStderr()); if (e != 0) { throw new RuntimeException("jmap returns: " + e); } if (! new File(dumpFile).exists()) { throw new RuntimeException("dump file NOT created: '" + dumpFile + "'"); } } catch (Throwable t) { t.printStackTrace(); throw new RuntimeException("Test failed with: " + t); } }
// Uses adb commands to tap at relative coordinates. To be used when appium methods fail. Only // works on Android devices. public void tapAtRelativeCoordinatesADB(double x_offset, double y_offset) throws Exception { if (platformName.equalsIgnoreCase("iOS")) { tapAtRelativeCoordinates(x_offset, y_offset); } else { Dimension size = getScreenSizeADB(); log("Size of device as seen by ADB is - width: " + size.width + " height: " + size.height); String x = String.valueOf(size.width * x_offset); String y = String.valueOf(size.height * y_offset); log("ADB: x and y: " + x + ", " + y); String[] adbCommand = {"adb", "shell", "input", "tap", x, y}; // String[] adbCommand = {"adb", "shell", "input", "touchscreen", "swipe", x, y, x, // y, "2000"}; try { ProcessBuilder p = new ProcessBuilder(adbCommand); Process proc = p.start(); InputStream stdin = proc.getInputStream(); InputStreamReader isr = new InputStreamReader(stdin); BufferedReader br = new BufferedReader(isr); String line = null; while ((line = br.readLine()) != null) System.out.print(line); proc.waitFor(); } catch (Throwable t) { t.printStackTrace(); } } }
/** * Génère une représentation graphique du processeur et de ses flux dans un fichier image. * * <p>Le logiciel externe dot de graphviz est utilisé pour construire la représentation. * * @return le nom du fichier image contenant la représentation. * @throws IOException Signals that an I/O exception has occurred. */ public String generateGraph() throws IOException { final String fileName = "graph-" + this; final PrintStream out = new PrintStream(fileName); out.println("digraph {"); out.println("\trankdir=LR;"); out.println("\tpenwidth=1;"); out.println("\tpencolor=black;"); out.println("\tbgcolor=white;"); out.println("\tmargin=0;"); out.println("\tcompound=true;pack=true;"); generateGraphRepresentation(out); out.println("}"); String windowsHack; if (System.getProperty("os.name").toLowerCase().indexOf("windows") != -1) { windowsHack = "..\\graphviz-bin\\release\\bin\\"; } else windowsHack = ""; final ProcessBuilder pb = new ProcessBuilder(windowsHack + "dot", "-Tpng", "-o" + fileName + ".png", fileName); final Process process = pb.start(); try { process.waitFor(); } catch (final InterruptedException e) { e.printStackTrace(); } final java.io.File f = new java.io.File(fileName); f.delete(); return fileName + ".png"; }
public void createMatchTable() throws IOException, InterruptedException { addReport("Matching keypoints started"); // File matchTable = new File(FileHelper.mergePath(imageDirectory, // keypointMatchTableFilename)); // // if(matchTable.exists()) { // addReport("Match table \""+keypointMatchTableFilename+"\" exists, therefore skip // matching"); // return; // } ProcessBuilder pb = new ProcessBuilder( keypointMatcherPath, FileHelper.mergePath(imageDirectory, imageListKeysFilename), FileHelper.mergePath(imageDirectory, keypointMatchTableFilename)); pb.directory(new File(imageDirectory)); Process p = pb.start(); addReport(p.getInputStream(), p.getErrorStream()); if (p.waitFor() != 0) { addReport("Matching keypoints error"); stop(); } }
/** * This method runs the ProcessBuilder and waits for it to finish. At the end it checks the return * state from the process and if it is a failure it prints the last line of the console output. * * @param builder */ private void bashProcess(ProcessBuilder builder) { Process process = null; builder.redirectErrorStream(true); try { process = builder.start(); } catch (IOException e1) { e1.printStackTrace(); } InputStream stdout = process.getInputStream(); BufferedReader stdoutBuffered = new BufferedReader(new InputStreamReader(stdout)); String line = null; String last = null; try { while ((line = stdoutBuffered.readLine()) != null) { last = line; if (isCancelled()) { process.destroy(); return; } } } catch (IOException e1) { e1.printStackTrace(); } try { if (process.waitFor() != 0) { firePropertyChange("failure", null, last); errorState = true; } } catch (InterruptedException e1) { e1.printStackTrace(); } }
protected void runPub( IContainer container, final MessageConsole console, List<String> args, boolean wait) { stringBuilder = new StringBuilder(); ProcessBuilder builder = new ProcessBuilder(); builder.directory(container.getLocation().toFile()); builder.redirectErrorStream(true); builder.command(args); final Process process; try { process = builder.start(); final Thread stdoutThread = new Thread( new Runnable() { @Override public void run() { try { copy(process.getInputStream(), console); } catch (IOException e) { // do nothing } } }); stdoutThread.start(); if (wait) { process.waitFor(); } } catch (IOException e) { String message = NLS.bind(PubMessages.RunPubJob_failed, command, e.toString()); console.println(message); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
/** 读取当前网速 */ public static long getNetSpeed() { ProcessBuilder cmd; long readBytes = 0; BufferedReader rd = null; try { String[] args = {"/system/bin/cat", "/proc/net/dev"}; cmd = new ProcessBuilder(args); Process process = cmd.start(); rd = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; // int linecount = 0; while ((line = rd.readLine()) != null) { // linecount++; if (line.contains("lan0") || line.contains("eth0")) { String[] delim = line.split(":"); if (delim.length >= 2) { readBytes = parserNumber(delim[1].trim()); break; } } } rd.close(); } catch (Exception ex) { ex.printStackTrace(); } finally { if (rd != null) { try { rd.close(); } catch (IOException e) { e.printStackTrace(); } } } return readBytes; }
@Override public CommandRunner.CommandOutput runCommandAndWaitForExit( File workingDir, List<String> arguments) throws IOException, InterruptedException { File binary = new File(arguments.get(0)); if (!binary.exists()) { logger.error("Binary {} does not exists, fix your configuration!", binary.getAbsolutePath()); return createErrorCommandOutput(); } if (!binary.canExecute()) { logger.error( "Binary {} can't be executed, fix your configuration!", binary.getAbsolutePath()); return createErrorCommandOutput(); } ProcessBuilder pb = new ProcessBuilder(arguments); pb.directory(workingDir); Process process = pb.start(); ByteArrayOutputStream stderr = new ByteArrayOutputStream(); ByteArrayOutputStream stdout = new ByteArrayOutputStream(); CommandRunnerImpl.StreamGobbler sgerr = new CommandRunnerImpl.StreamGobbler(process.getErrorStream(), stderr); CommandRunnerImpl.StreamGobbler sgout = new CommandRunnerImpl.StreamGobbler(process.getInputStream(), stdout); sgerr.start(); sgout.start(); int exitCode = process.waitFor(); sgerr.join(); sgout.join(); CommandRunner.CommandOutput result = new CommandRunner.CommandOutput(stdout.toByteArray(), stderr.toByteArray()); result.setExitCode(exitCode); return result; }
/* * Combines audio input with video input at specified time * @see javax.swing.SwingWorker#doInBackground() */ @Override protected Void doInBackground() throws Exception { // Extract the audio from the video and save it as a hidden file in MP3Files String cmd = "ffmpeg -y -i " + videoPath + " -map 0:1 ./MP3Files/.vidAudio.mp3"; ProcessBuilder builder = new ProcessBuilder("/bin/bash", "-c", cmd); Process process = builder.start(); process.waitFor(); for (int i = 1; i < 25; i++) { // Update progress bar when above process is complete Thread.sleep(40); progress.updateProgress(i); } if (time == 0) { // Create a hidden mp3 file output.mp3 that combines the video audio and selected mp3 audio at // time 0 cmd = "ffmpeg -y -i " + audioPath + " -i ./MP3Files/.vidAudio.mp3 -filter_complex amix=inputs=2 ./MP3Files/.output.mp3"; } else { // Create a hidden mp3 file output.mp3 that combines the video audio and selected mp3 audio at // specified time cmd = "ffmpeg -y -i " + audioPath + " -i ./MP3Files/.vidAudio.mp3 -filter_complex \"[0:0]adelay=" + time + "[aud1];[aud1][1:0]amix=inputs=2\" ./MP3Files/.output.mp3"; } builder = new ProcessBuilder("/bin/bash", "-c", cmd); process = builder.start(); process.waitFor(); for (int i = 1; i < 50; i++) { // Update progress bar Thread.sleep(40); progress.updateProgress(25 + i); } // Creates an output.avi file from merging existing video stream (1:0) and combined audio (0:0) cmd = "ffmpeg -i " + videoPath + " -i ./MP3Files/.output.mp3 -map 0:0 -map 1:0 -acodec copy -vcodec copy ./VideoFiles/" + name + ".avi"; builder = new ProcessBuilder("/bin/bash", "-c", cmd); process = builder.start(); process.waitFor(); for (int i = 1; i < 25; i++) { // Update progress bar Thread.sleep(40); progress.updateProgress(75 + i); } return null; }
public void startProfile(FirefoxProfile profile, File profileDir, String... commandLineFlags) throws IOException { String profileAbsPath = profileDir.getAbsolutePath(); setEnvironmentProperty("XRE_PROFILE_PATH", profileAbsPath); setEnvironmentProperty("MOZ_NO_REMOTE", "1"); setEnvironmentProperty("MOZ_CRASHREPORTER_DISABLE", "1"); // Disable Breakpad setEnvironmentProperty( "NO_EM_RESTART", "1"); // Prevent the binary from detaching from the console if (isOnLinux() && (profile.enableNativeEvents() || profile.alwaysLoadNoFocusLib())) { modifyLinkLibraryPath(profileDir); } List<String> commands = new ArrayList<String>(); commands.add(getExecutable().getPath()); commands.addAll(Arrays.asList(commandLineFlags)); ProcessBuilder builder = new ProcessBuilder(commands); builder.redirectErrorStream(true); builder.environment().putAll(getExtraEnv()); getExecutable().setLibraryPath(builder, getExtraEnv()); if (stream == null) { stream = getExecutable().getDefaultOutputStream(); } startFirefoxProcess(builder); copeWithTheStrangenessOfTheMac(builder); startOutputWatcher(); }