org.apache.commons.exec.CommandLine Java Examples
The following examples show how to use
org.apache.commons.exec.CommandLine.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SimpleTestServer.java From p4ic4idea with Apache License 2.0 | 7 votes |
public int getVersion() throws Exception { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); CommandLine cmdLine = new CommandLine(p4d); cmdLine.addArgument("-V"); DefaultExecutor executor = new DefaultExecutor(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); executor.setStreamHandler(streamHandler); executor.execute(cmdLine); int version = 0; for (String line : outputStream.toString().split("\\n")) { if (line.startsWith("Rev. P4D")) { Pattern p = Pattern.compile("\\d{4}\\.\\d{1}"); Matcher m = p.matcher(line); while (m.find()) { String found = m.group(); found = found.replace(".", ""); // strip "." version = Integer.parseInt(found); } } } logger.info("P4D Version: " + version); return version; }
Example #2
Source File: LocalLbAdapter.java From Baragon with Apache License 2.0 | 6 votes |
private int executeWithTimeout(CommandLine command, int timeout) throws LbAdapterExecuteException, IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(new PumpStreamHandler(baos)); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); // Start async and do our own time limiting instead of using a watchdog to avoid https://issues.apache.org/jira/browse/EXEC-62 try { long start = System.currentTimeMillis(); executor.execute(command, resultHandler); while (System.currentTimeMillis() - start < timeout && !resultHandler.hasResult()) { Thread.sleep(50); } if (resultHandler.hasResult()) { if (resultHandler.getException() != null) { throw resultHandler.getException(); } return resultHandler.getExitValue(); } else { CompletableFuture.runAsync(() -> executor.getWatchdog().destroyProcess(), destroyProcessExecutor); throw new LbAdapterExecuteException(baos.toString(Charsets.UTF_8.name()), command.toString()); } } catch (ExecuteException|InterruptedException e) { throw new LbAdapterExecuteException(baos.toString(Charsets.UTF_8.name()), e, command.toString()); } }
Example #3
Source File: JavaFXRunMojoTestCase.java From javafx-maven-plugin with Apache License 2.0 | 6 votes |
private String getCommandLineAsString(CommandLine commandline) { // for the sake of the test comparisons, cut out the eventual // cmd /c *.bat conversion String result = commandline.getExecutable(); boolean isCmd = false; if (OS.isFamilyWindows() && result.equals("cmd")) { result = ""; isCmd = true; } String[] arguments = commandline.getArguments(); for (int i = 0; i < arguments.length; i++) { String arg = arguments[i]; if (isCmd && i == 0 && "/c".equals(arg)) { continue; } if (isCmd && i == 1 && arg.endsWith(".bat")) { arg = arg.substring(0, arg.length() - ".bat".length()); } result += (result.length() == 0 ? "" : " ") + arg; } return result; }
Example #4
Source File: JavaFXJLinkMojo.java From javafx-maven-plugin with Apache License 2.0 | 6 votes |
private boolean isJLinkVersion13orHigher(String jlinkExePath) { CommandLine versionCommandLine = new CommandLine(jlinkExePath) .addArgument("--version"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int resultCode = -1; try { resultCode = executeCommandLine(new DefaultExecutor(), versionCommandLine, null, baos, System.err); } catch (IOException e) { if (getLog().isDebugEnabled()) { getLog().error("Error getting JLink version", e); } } if (resultCode != 0) { getLog().error("Unable to get JLink version"); getLog().error("Result of " + versionCommandLine + " execution is: '" + resultCode + "'"); return false; } String versionStr = new String(baos.toByteArray()); return JLINK_VERSION_PATTERN.matcher(versionStr).lookingAt(); }
Example #5
Source File: ScriptUtil.java From open-capacity-platform with Apache License 2.0 | 6 votes |
/** * 日志文件输出方式 * * 优点:支持将目标数据实时输出到指定日志文件中去 * 缺点: * 标准输出和错误输出优先级固定,可能和脚本中顺序不一致 * Java无法实时获取 * * @param command * @param scriptFile * @param logFile * @param params * @return * @throws IOException */ public static int execToFile(String command, String scriptFile, String logFile, String... params) throws IOException { // 标准输出:print (null if watchdog timeout) // 错误输出:logging + 异常 (still exists if watchdog timeout) // 标准输入 try (FileOutputStream fileOutputStream = new FileOutputStream(logFile, true)) { PumpStreamHandler streamHandler = new PumpStreamHandler(fileOutputStream, fileOutputStream, null); // command CommandLine commandline = new CommandLine(command); commandline.addArgument(scriptFile); if (params!=null && params.length>0) { commandline.addArguments(params); } // exec DefaultExecutor exec = new DefaultExecutor(); exec.setExitValues(null); exec.setStreamHandler(streamHandler); int exitValue = exec.execute(commandline); // exit code: 0=success, 1=error return exitValue; } }
Example #6
Source File: DropwizardContractTest.java From moneta with Apache License 2.0 | 6 votes |
@BeforeClass public static void setUpBeforeClass() throws Exception { System.out.println("Java Temp Dir: " +System.getProperty("java.io.tmpdir")); executor = new DefaultExecutor(); resultHandler = new DefaultExecuteResultHandler(); String javaHome = System.getProperty("java.home"); String userDir = System.getProperty("user.dir"); executor.setStreamHandler(new PumpStreamHandler(System.out)); watchdog = new ExecuteWatchdog(10000); executor.setWatchdog(watchdog); executor.execute(new CommandLine(javaHome + SystemUtils.FILE_SEPARATOR + "bin"+ SystemUtils.FILE_SEPARATOR+"java.exe").addArgument("-version")); executor.execute(new CommandLine(javaHome + SystemUtils.FILE_SEPARATOR + "bin"+ SystemUtils.FILE_SEPARATOR+"java.exe") .addArgument("-jar") .addArgument(userDir + "/../moneta-dropwizard/target/moneta-dropwizard-" + ContractTestSuite.getProjectVersion() + ".jar") .addArgument("server") .addArgument("src/main/resources/dropwizard/moneta-dropwizard.yaml"), resultHandler); Thread.sleep(3000); System.out.println("Test sequence starting...."); }
Example #7
Source File: SpringBootContractTest.java From moneta with Apache License 2.0 | 6 votes |
public void run() { try { executor = new DaemonExecutor(); resultHandler = new DefaultExecuteResultHandler(); String javaHome = System.getProperty("java.home"); String userDir = System.getProperty("user.dir"); executor.setStreamHandler(new PumpStreamHandler(System.out)); watchdog = new ExecuteWatchdog(15000); executor.setWatchdog(watchdog); executor.execute(new CommandLine(javaHome + SystemUtils.FILE_SEPARATOR + "bin"+ SystemUtils.FILE_SEPARATOR+"java.exe").addArgument("-version")); executor.execute(new CommandLine(javaHome + SystemUtils.FILE_SEPARATOR + "bin"+ SystemUtils.FILE_SEPARATOR+"java.exe") .addArgument("-jar") .addArgument(userDir + "/../moneta-springboot/target/moneta-springboot-" + ContractTestSuite.getProjectVersion() + ".jar")); } catch (Exception e) { e.printStackTrace(); } }
Example #8
Source File: JobMonitorTest.java From genie with Apache License 2.0 | 6 votes |
/** * Make sure that a process whose std out file has grown too large will attempt to be killed. * * @throws IOException on error */ @Test void canKillProcessOnTooLargeStdOut() throws IOException { Assumptions.assumeTrue(SystemUtils.IS_OS_UNIX); Mockito .when(this.executor.execute(Mockito.any(CommandLine.class))) .thenReturn(0) .thenReturn(0) .thenReturn(0); Mockito.when(this.stdOut.exists()).thenReturn(true); Mockito.when(this.stdOut.length()) .thenReturn(MAX_STD_OUT_LENGTH - 1) .thenReturn(MAX_STD_OUT_LENGTH) .thenReturn(MAX_STD_OUT_LENGTH + 1); Mockito.when(this.stdErr.exists()).thenReturn(false); for (int i = 0; i < 3; i++) { this.monitor.run(); } Mockito.verify(this.successfulCheckRate, Mockito.times(2)).increment(); Mockito.verify(this.stdOutTooLarge, Mockito.times(1)).increment(); Mockito.verify(this.genieEventBus, Mockito.times(1)).publishSynchronousEvent(Mockito.any(KillJobEvent.class)); }
Example #9
Source File: GradleRunner.java From app-runner with MIT License | 6 votes |
private ExecuteWatchdog runJar(LineConsumer buildLogHandler, LineConsumer consoleLogHandler, Map<String, String> envVarsForApp, Waiter startupWaiter) { Path libsPath = Paths.get(projectRoot.getPath(), "build", "libs"); File libsFolder = libsPath.toFile(); // To simplify implementation, now I assume only 1 uberjar named "artifact-version-all.jar" under libs folder // As we clean the project every time, I can't foresee any possibility that will mix up other uberjars. File[] files = libsFolder.listFiles(); if(files == null) { throw new ProjectCannotStartException(libsFolder.getPath() + " doesn't exist"); } Optional<File> jar = Stream.of(files).filter((f) -> f.getName().contains("all")).findFirst(); if (!jar.isPresent() || !jar.get().isFile()) { throw new ProjectCannotStartException("Could not find the jar file at " + jar.get().getPath()); } CommandLine command = javaHomeProvider.commandLine(envVarsForApp) .addArgument("-Djava.io.tmpdir=" + envVarsForApp.get("TEMP")) .addArgument("-jar") .addArgument(fullPath(jar.get())); return ProcessStarter.startDaemon(buildLogHandler, consoleLogHandler, envVarsForApp, command, projectRoot, startupWaiter); }
Example #10
Source File: CommandRunnerTest.java From graphviz-java with Apache License 2.0 | 6 votes |
@Test void testRunEchoHelloWorld() throws IOException, InterruptedException { final CommandLine expected = System.getProperty("os.name").contains("Windows") ? CommandLine.parse("cmd /C echo hello world") : CommandLine.parse("/bin/sh -c").addArgument("echo hello world", false); final CommandLineExecutor cmdExecMock = Mockito.mock(CommandLineExecutor.class); final CommandRunner cmdRunner = new CommandBuilder() .withShellWrapper(true) .withCommandExecutor(cmdExecMock) .build(); cmdRunner.exec(CommandLine.parse("echo hello world"), null, 5000); verify(cmdExecMock).execute(runEchoCaptor.capture(), (File) isNull(), eq(5000)); assertEquals(expected.toString(), runEchoCaptor.getValue().toString()); }
Example #11
Source File: JobKillServiceV3Test.java From genie with Apache License 2.0 | 6 votes |
/** * Make sure that if the job status is one that is already finished there is no attempt made to kill it. * * @throws GenieException on any error * @throws GenieCheckedException on any error * @throws IOException on error */ @Test public void wontKillJobIfAlreadyFinished() throws GenieException, GenieCheckedException, IOException { Mockito .when(this.persistenceService.getJobStatus(ID)) .thenReturn(JobStatus.SUCCEEDED) .thenReturn(JobStatus.FAILED) .thenReturn(JobStatus.INVALID) .thenReturn(JobStatus.KILLED); // Run through the four cases this.service.killJob(ID, KILL_REASON); this.service.killJob(ID, KILL_REASON); this.service.killJob(ID, KILL_REASON); this.service.killJob(ID, KILL_REASON); Mockito.verify(this.persistenceService, Mockito.never()).getJobExecution(ID); Mockito.verify(this.executor, Mockito.never()).execute(Mockito.any(CommandLine.class)); }
Example #12
Source File: SimpleTestServer.java From p4ic4idea with Apache License 2.0 | 6 votes |
public int getVersion() throws Exception { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); CommandLine cmdLine = new CommandLine(p4d); cmdLine.addArgument("-V"); DefaultExecutor executor = new DefaultExecutor(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); executor.setStreamHandler(streamHandler); executor.execute(cmdLine); int version = 0; for (String line : outputStream.toString().split("\\n")) { if (line.startsWith("Rev. P4D")) { Pattern p = Pattern.compile("\\d{4}\\.\\d{1}"); Matcher m = p.matcher(line); while (m.find()) { String found = m.group(); found = found.replace(".", ""); // strip "." version = Integer.parseInt(found); } } } logger.info("P4D Version: " + version); return version; }
Example #13
Source File: JobKillServiceV3Test.java From genie with Apache License 2.0 | 6 votes |
/** * Make sure we can kill a job. * * @throws GenieException on any error * @throws GenieCheckedException on any error * @throws IOException On error in execute */ @Test public void canKillJob() throws GenieException, GenieCheckedException, IOException { final JobExecution jobExecution = Mockito.mock(JobExecution.class); Mockito.when(jobExecution.getExitCode()).thenReturn(Optional.empty()); Mockito.when(jobExecution.getHostName()).thenReturn(HOSTNAME); Mockito.when(jobExecution.getProcessId()).thenReturn(Optional.of(PID)); Mockito.when(this.persistenceService.getJobStatus(ID)).thenReturn(JobStatus.RUNNING); Mockito.when(this.persistenceService.getJobExecution(ID)).thenReturn(jobExecution); Mockito.when(this.executor.execute(Mockito.any(CommandLine.class))).thenReturn(0, 0); Mockito.when( this.processCheckerFactory.get(Mockito.eq(PID), Mockito.any(Instant.class)) ).thenReturn(processChecker); this.service.killJob(ID, KILL_REASON); Mockito.verify(this.executor, Mockito.times(1)).execute(Mockito.any(CommandLine.class)); Mockito.verify(this.processChecker, Mockito.times(1)).checkProcess(); }
Example #14
Source File: StatusCheckerTimer.java From oxTrust with MIT License | 6 votes |
@SuppressWarnings("deprecation") private String getFacterVersion() { ByteArrayOutputStream bos = new ByteArrayOutputStream(4096); try { CommandLine commandLine = new CommandLine(OxTrustConstants.PROGRAM_FACTER); commandLine.addArgument("--version"); ProcessHelper.executeProgram(commandLine, false, 0, bos); return new String(bos.toByteArray(), "UTF-8"); } catch (UnsupportedEncodingException ex) { log.error("Failed to parse program {} output", OxTrustConstants.PROGRAM_FACTER, ex); return null; } finally { IOUtils.closeQuietly(bos); } }
Example #15
Source File: __platform-name__Loader.java From ldbc_graphalytics with Apache License 2.0 | 6 votes |
public int unload(String loadedInputPath) throws Exception { String unloaderDir = platformConfig.getUnloaderPath(); commandLine = new CommandLine(Paths.get(unloaderDir).toFile()); commandLine.addArgument("--graph-name"); commandLine.addArgument(formattedGraph.getName()); commandLine.addArgument("--output-path"); commandLine.addArgument(loadedInputPath); String commandString = StringUtils.toString(commandLine.toStrings(), " "); LOG.info(String.format("Execute graph unloader with command-line: [%s]", commandString)); Executor executor = new DefaultExecutor(); executor.setStreamHandler(new PumpStreamHandler(System.out, System.err)); executor.setExitValue(0); return executor.execute(commandLine); }
Example #16
Source File: NetworkUtils.java From logstash with Apache License 2.0 | 6 votes |
public String getDockerHostIpAddress(Map<String, String> environment) { String ipAddress = LOCALHOST; // Default of localhost String dockerMachineName = getDockerMachineName(environment); if (!dockerMachineName.isEmpty()) { LOG.debug("Docker machine name = " + dockerMachineName); CommandLine commandline = CommandLine.parse(DOCKER_MACHINE_IP); commandline.addArgument(dockerMachineName); LOG.debug("Running exec: " + commandline.toString()); try { ipAddress = StringUtils.strip(runCommand(commandline)); } catch (IOException e) { LOG.error("Unable to run exec command to find ip address.", e); } } else { ipAddress = getDocker0AdapterIPAddress(); } LOG.debug("Returned IP address: " + ipAddress); return ipAddress; }
Example #17
Source File: CommandBuilderHelper.java From poor-man-transcoder with GNU General Public License v2.0 | 6 votes |
protected String prepareSegmentDirectory(CommandLine cmdLine, ITranscoderResource output, TokenReplacer tokenReplacer, String masterWorkingDirectory) throws IOException { // create sub directory for hls output String HLS_SAMPLE_PLAYBACK_TEMPLATE = "hls-index-sample.html"; String OUTPUT_HLS_PLAYBACK_TEMPLATE = "index.html"; tokenReplacer.setTokenValue(TokenReplacer.TOKEN.HLS_SAMPLE_PLAYBACK_TEMPLATE, HLS_SAMPLE_PLAYBACK_TEMPLATE); String outName = output.getMediaName(); String outNameWithOutExt = FilenameUtils.removeExtension(outName); File sub = new File(masterWorkingDirectory + File.separator + outNameWithOutExt); if(!sub.exists()) sub.mkdir(); File indexTemplateSample = new File(Globals.getEnv(Globals.Vars.TEMPLATE_DIRECTORY) + File.separator + HLS_SAMPLE_PLAYBACK_TEMPLATE); File indexTemplate = new File(sub.getAbsolutePath() + File.separator + OUTPUT_HLS_PLAYBACK_TEMPLATE); if(indexTemplateSample.exists()) FileUtils.copyFile(indexTemplateSample, indexTemplate); logger.info("Copying html template for hls playback into " + sub.getAbsolutePath()); String relative = new File(masterWorkingDirectory).toURI().relativize(new File(sub.getAbsolutePath()).toURI()).getPath(); logger.info("Relative path of segment directory " + relative); return relative; }
Example #18
Source File: SystemTest.java From app-runner with MIT License | 5 votes |
private static void buildAndStartUberJar(List<String> goals) throws Exception { mavenRunner = new MavenRunner(new File("."), new HomeProvider() { public InvocationRequest mungeMavenInvocationRequest(InvocationRequest request) { return HomeProvider.default_java_home.mungeMavenInvocationRequest(request); } public CommandLine commandLine(Map<String, String> envVarsForApp) { return HomeProvider.default_java_home.commandLine(envVarsForApp).addArgument("-Dlogback.configurationFile=src/test/resources/logback-test.xml"); } }, goals); Map<String, String> env = new HashMap<String, String>(System.getenv()) {{ put(Config.SERVER_HTTPS_PORT, String.valueOf(httpsPort)); put("apprunner.keystore.path", fullPath(new File("local/test.keystore"))); put("apprunner.keystore.password", "password"); put("apprunner.keymanager.password", "password"); put(Config.DATA_DIR, fullPath(dataDir)); }}; LineConsumer logHandler = line -> System.out.print("Uber jar output > " + line); try (Waiter startupWaiter = new Waiter("AppRunner uber jar", httpClient -> { try { JSONObject sysInfo = new JSONObject(client.GET(appRunnerUrl + "/api/v1/system").getContentAsString()); return sysInfo.getBoolean("appRunnerStarted"); } catch (Exception e) { return false; } }, 2, TimeUnit.MINUTES)) { mavenRunner.start(logHandler, logHandler, env, startupWaiter); } }
Example #19
Source File: ExecMojoTest.java From exec-maven-plugin with Apache License 2.0 | 5 votes |
protected int executeCommandLine( Executor exec, CommandLine commandLine, Map enviro, OutputStream out, OutputStream err ) throws IOException, ExecuteException { commandLines.add( commandLine ); if ( failureMsg != null ) { throw new ExecuteException( failureMsg, executeResult ); } return executeResult; }
Example #20
Source File: ProcessStarterTest.java From app-runner with MIT License | 5 votes |
@Test public void canTellTheVersionOfStuff() throws Exception { Pair<Boolean, String> result = ProcessStarter.run(new CommandLine(javaExecutableName()).addArgument("-version")); assertThat(result.getLeft(), equalTo(true)); assertThat(result.getRight(), anyOf(containsString("java"), containsString("jdk"))); assertThat(result.getRight(), not(containsString("-version"))); }
Example #21
Source File: ProcessExecutor.java From frontend-maven-plugin with Apache License 2.0 | 5 votes |
private CommandLine createCommandLine(List<String> command) { CommandLine commmandLine = new CommandLine(command.get(0)); for (int i = 1;i < command.size();i++) { String argument = command.get(i); commmandLine.addArgument(argument, false); } return commmandLine; }
Example #22
Source File: NodeRunner.java From app-runner with MIT License | 5 votes |
public void start(LineConsumer buildLogHandler, LineConsumer consoleLogHandler, Map<String, String> envVarsForApp, Waiter startupWaiter) throws ProjectCannotStartException { runNPM(buildLogHandler, envVarsForApp, "install"); runNPM(buildLogHandler, envVarsForApp, "test"); CommandLine command = new CommandLine(nodeExec) .addArgument("server.js") .addArgument("--app-name=" + envVarsForApp.get("APP_NAME")); watchDog = ProcessStarter.startDaemon(buildLogHandler, consoleLogHandler, envVarsForApp, command, projectRoot, startupWaiter); }
Example #23
Source File: UNIXUtilsTest.java From genie with Apache License 2.0 | 5 votes |
/** * Test the change ownership method for success. * * @throws IOException If there is any problem. */ @Test public void testChangeOwnershipOfDirectoryMethodSuccess() throws IOException { final String user = "user"; final String dir = "dir"; final ArgumentCaptor<CommandLine> argumentCaptor = ArgumentCaptor.forClass(CommandLine.class); final List<String> command = Arrays.asList("sudo", "chown", "-R", user, dir); UNIXUtils.changeOwnershipOfDirectory(dir, user, executor); Mockito.verify(this.executor).execute(argumentCaptor.capture()); Assert.assertArrayEquals(command.toArray(), argumentCaptor.getValue().toStrings()); }
Example #24
Source File: ExecMojoTest.java From exec-maven-plugin with Apache License 2.0 | 5 votes |
private String getCommandLineAsString( CommandLine commandline ) { // for the sake of the test comparisons, cut out the eventual // cmd /c *.bat conversion String result = commandline.getExecutable(); boolean isCmd = false; if ( OS.isFamilyWindows() && result.equals( "cmd" ) ) { result = ""; isCmd = true; } String[] arguments = commandline.getArguments(); for ( int i = 0; i < arguments.length; i++ ) { String arg = arguments[i]; if ( isCmd && i == 0 && "/c".equals( arg ) ) { continue; } if ( isCmd && i == 1 && arg.endsWith( ".bat" ) ) { arg = arg.substring( 0, arg.length() - ".bat".length() ); } result += ( result.length() == 0 ? "" : " " ) + arg; } return result; }
Example #25
Source File: ReportGenerate.java From allure1 with Apache License 2.0 | 5 votes |
/** * Create a {@link CommandLine} to run bundle with needed arguments. */ private CommandLine createCommandLine() throws IOException { return new CommandLine(getJavaExecutablePath()) .addArguments(getBundleJavaOptsArgument()) .addArgument(getLoggerConfigurationArgument()) .addArgument("-jar") .addArgument(getExecutableJar()) .addArguments(results.toArray(new String[results.size()]), false) .addArgument(getReportDirectoryPath().toString(), false); }
Example #26
Source File: MavenRunner.java From app-runner with MIT License | 5 votes |
public void start(LineConsumer buildLogHandler, LineConsumer consoleLogHandler, Map<String, String> envVarsForApp, Waiter startupWaiter) throws ProjectCannotStartException { File pomFile = new File(projectRoot, "pom.xml"); if (goals.isEmpty()) { log.info("No goals. Skipping maven build"); } else { InvocationRequest request = new DefaultInvocationRequest() .setBatchMode(true) .setPomFile(pomFile) .setOutputHandler(buildLogHandler::consumeLine) .setErrorHandler(buildLogHandler::consumeLine) .setGoals(goals) .setBaseDirectory(projectRoot); log.info("Building maven project at " + fullPath(projectRoot)); runRequest(request, javaHomeProvider); log.info("Build successful. Going to start app."); } Model model = loadPomModel(pomFile); String jarName = model.getArtifactId() + "-" + model.getVersion() + ".jar"; File jar = new File(new File(projectRoot, "target"), jarName); if (!jar.isFile()) { throw new ProjectCannotStartException("Could not find the jar file at " + fullPath(jar)); } CommandLine command = javaHomeProvider.commandLine(envVarsForApp) .addArgument("-Djava.io.tmpdir=" + envVarsForApp.get("TEMP")) .addArgument("-jar") .addArgument("target" + File.separator + jarName); watchDog = ProcessStarter.startDaemon(buildLogHandler, consoleLogHandler, envVarsForApp, command, projectRoot, startupWaiter); }
Example #27
Source File: Config.java From app-runner with MIT License | 5 votes |
public CommandLineProvider sbtJavaCommandProvider() { return raw.containsKey(SBT_JAVA_CMD) ? (Map<String, String> env) -> new CommandLine(getFile(SBT_JAVA_CMD)) : javaHomeProvider(); }
Example #28
Source File: FileCopyTOCPayloadHandler.java From s3-bucket-loader with Apache License 2.0 | 5 votes |
private CmdResult exec(int maxAttempts, String desc, CommandLine cmd, String retryExistancePathToCheck) { String cmdStr = null; CmdResult result = null; try { cmdStr = cmd.toString(); File retryExistanceCheckFile = new File(retryExistancePathToCheck); int attempts = 0; while((attempts < maxAttempts) && (result == null || result.getExitCode() > 0 || !retryExistanceCheckFile.exists())) { attempts++; logger.debug("exec() attempt#: "+attempts+ " executing "+desc+": " + cmdStr); result = executor.execute(cmd,maxAttempts); // if fail, let it breathe if (result.getExitCode() > 0) { Thread.currentThread().sleep(getRetriesSleepMS()); } } } catch(Exception e) { String msg = "exec() "+desc+" unexpected exception: " +cmdStr + " " + e.getMessage(); logger.error(msg,e); result = new CmdResult(5555, null, msg); } return result; }
Example #29
Source File: __platform-name__Job.java From ldbc_graphalytics with Apache License 2.0 | 5 votes |
/** * Executes the platform job with the pre-defined parameters. * * @return the exit code * @throws IOException if the platform failed to run */ public int execute() throws Exception { String executableDir = platformConfig.getExecutablePath(); commandLine = new CommandLine(Paths.get(executableDir).toFile()); // List of benchmark parameters. String jobId = getJobId(); String logDir = getLogPath(); // List of dataset parameters. String inputPath = getInputPath(); String outputPath = getOutputPath(); // List of platform parameters. int numMachines = platformConfig.getNumMachines(); int numThreads = platformConfig.getNumThreads(); String homeDir = platformConfig.getHomePath(); appendBenchmarkParameters(jobId, logDir); appendAlgorithmParameters(); appendDatasetParameters(inputPath, outputPath); appendPlatformConfigurations(homeDir, numMachines, numThreads); String commandString = StringUtils.toString(commandLine.toStrings(), " "); LOG.info(String.format("Execute benchmark job with command-line: [%s]", commandString)); Executor executor = new DefaultExecutor(); executor.setStreamHandler(new PumpStreamHandler(System.out, System.err)); executor.setExitValue(0); return executor.execute(commandLine); }
Example #30
Source File: GoRunner.java From app-runner with MIT License | 5 votes |
private void rungo(LineConsumer buildLogHandler, Map<String, String> envVarsForApp, String... arguments) { CommandLine command = goCmd.commandLine(envVarsForApp); for (String argument : arguments) command.addArgument(argument); buildLogHandler.consumeLine("Running go " + StringUtils.join(arguments, " ") + " with " + command); ProcessStarter.run(buildLogHandler, envVarsForApp, command, projectRoot, TimeUnit.MINUTES.toMillis(20)); }