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:org.codehaus.enunciate.modules.gwt.GWTDeploymentModule.java
/** * Invokes GWTCompile on the apps specified in the configuration file. *///from ww w. j a v a 2 s .c o m protected void doGWTCompile() throws EnunciateException, IOException { if (this.gwtHome == null) { throw new EnunciateException( "To compile a GWT app you must specify the GWT home directory, either in configuration, by setting the GWT_HOME environment variable, or setting the 'gwt.home' system property."); } File gwtHomeDir = new File(this.gwtHome); if (!gwtHomeDir.exists()) { throw new EnunciateException("GWT home not found ('" + gwtHomeDir.getAbsolutePath() + "')."); } File gwtUserJar = new File(gwtHomeDir, "gwt-user.jar"); if (!gwtUserJar.exists()) { warn("Unable to find %s. You may be GWT compile errors.", gwtUserJar.getAbsolutePath()); } //now we have to find gwt-dev.jar. //start by assuming linux... File gwtDevJar = new File(gwtHomeDir, "gwt-dev.jar"); if (!gwtDevJar.exists()) { File linuxDevJar = new File(gwtHomeDir, "gwt-dev-linux.jar"); gwtDevJar = linuxDevJar; if (!gwtDevJar.exists()) { //linux not found. try mac... File macDevJar = new File(gwtHomeDir, "gwt-dev-mac.jar"); gwtDevJar = macDevJar; if (!gwtDevJar.exists()) { //okay, we'll try windows if we have to... File windowsDevJar = new File(gwtHomeDir, "gwt-dev-windows.jar"); gwtDevJar = windowsDevJar; if (!gwtDevJar.exists()) { throw new EnunciateException( String.format("Unable to find GWT dev jar. Looked for %s, %s, and %s.", linuxDevJar.getAbsolutePath(), macDevJar.getAbsolutePath(), windowsDevJar.getAbsolutePath())); } } } } boolean windows = false; File javaBinDir = new File(System.getProperty("java.home"), "bin"); File javaExecutable = new File(javaBinDir, "java"); if (!javaExecutable.exists()) { //append the "exe" for windows users. javaExecutable = new File(javaBinDir, "java.exe"); windows = true; } String javaCommand = javaExecutable.getAbsolutePath(); if (!javaExecutable.exists()) { warn("No java executable found in %s. We'll just hope the environment is set up to execute 'java'...", javaBinDir.getAbsolutePath()); javaCommand = "java"; } StringBuilder classpath = new StringBuilder(enunciate.getEnunciateRuntimeClasspath()); //append the client-side gwt directory. classpath.append(File.pathSeparatorChar).append(getClientSideGenerateDir().getAbsolutePath()); //append the gwt-user jar. classpath.append(File.pathSeparatorChar).append(gwtUserJar.getAbsolutePath()); //append the gwt-dev jar. classpath.append(File.pathSeparatorChar).append(gwtDevJar.getAbsolutePath()); //so here's the GWT compile command: //java [extra jvm args] -cp [classpath] [compilerClass] -gen [gwt-gen-dir] -style [style] -out [out] [moduleName] List<String> jvmargs = getGwtCompileJVMArgs(); List<String> compilerArgs = getGwtCompilerArgs(); List<String> gwtcCommand = new ArrayList<String>(jvmargs.size() + compilerArgs.size() + 11); int argIndex = 0; gwtcCommand.add(argIndex++, javaCommand); for (String arg : jvmargs) { gwtcCommand.add(argIndex++, arg); } gwtcCommand.add(argIndex++, "-cp"); int classpathArgIndex = argIndex; //app-specific arg. gwtcCommand.add(argIndex++, null); int compileClassIndex = argIndex; gwtcCommand.add(argIndex++, getGwtCompilerClass()); gwtcCommand.add(argIndex++, "-gen"); gwtcCommand.add(argIndex++, getGwtGenDir().getAbsolutePath()); gwtcCommand.add(argIndex++, "-style"); int styleArgIndex = argIndex; gwtcCommand.add(argIndex++, null); //app-specific arg. gwtcCommand.add(argIndex++, gwtVersionGreaterThan(1, 5) ? "-war" : "-out"); int outArgIndex = argIndex; gwtcCommand.add(argIndex++, null); //app-specific arg. for (String arg : compilerArgs) { gwtcCommand.add(argIndex++, arg); } int moduleNameIndex = argIndex; gwtcCommand.add(argIndex, null); //module-specific arg. for (GWTApp gwtApp : gwtApps) { String appName = gwtApp.getName(); File appSource = enunciate.resolvePath(gwtApp.getSrcDir()); String style = gwtApp.getJavascriptStyle().toString(); File appDir = getAppGenerateDir(appName); gwtcCommand.set(classpathArgIndex, classpath.toString() + File.pathSeparatorChar + appSource.getAbsolutePath()); gwtcCommand.set(styleArgIndex, style); gwtcCommand.set(outArgIndex, appDir.getAbsolutePath()); boolean upToDate = enunciate.isUpToDate(getClientSideGenerateDir(), appDir) && enunciate.isUpToDate(appSource, appDir); if (!upToDate) { for (GWTAppModule appModule : gwtApp.getModules()) { String moduleName = appModule.getName(); gwtcCommand.set(moduleNameIndex, moduleName); debug("Executing GWTCompile for module '%s'...", moduleName); if (enunciate.isDebug()) { StringBuilder command = new StringBuilder(); for (String commandPiece : gwtcCommand) { command.append(' ').append(commandPiece); } debug("Executing GWTCompile for module %s with the command: %s", moduleName, command); } ProcessBuilder processBuilder = new ProcessBuilder(gwtcCommand); processBuilder.directory(getGenerateDir()); processBuilder.redirectErrorStream(true); Process process = processBuilder.start(); BufferedReader procReader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line = procReader.readLine(); while (line != null) { line = URLDecoder.decode(line, "utf-8").replaceAll("%", "%%").trim(); //GWT URL-encodes spaces and other weird Windows characters. info(line); line = procReader.readLine(); } int procCode; try { procCode = process.waitFor(); } catch (InterruptedException e1) { throw new EnunciateException("Unexpected inturruption of the GWT compile process."); } if (procCode != 0) { throw new EnunciateException("GWT compile failed for module " + moduleName); } if (!gwtVersionGreaterThan(1, 5)) { File moduleOutputDir = appDir; String outputPath = appModule.getOutputPath(); if ((outputPath != null) && (!"".equals(outputPath.trim()))) { moduleOutputDir = new File(appDir, outputPath); } File moduleGenDir = new File(appDir, moduleName); if (!moduleOutputDir.equals(moduleGenDir)) { moduleOutputDir.mkdirs(); enunciate.copyDir(moduleGenDir, moduleOutputDir); deleteDir(moduleGenDir); } } StringBuilder shellCommand = new StringBuilder(); for (int i = 0; i < moduleNameIndex; i++) { String commandArg = gwtcCommand.get(i); if (i == compileClassIndex) { commandArg = gwtVersionGreaterThan(1, 5) ? "com.google.gwt.dev.HostedMode" : "com.google.gwt.dev.GWTShell"; } else if (commandArg.indexOf(' ') >= 0) { commandArg = '"' + commandArg + '"'; } shellCommand.append(commandArg).append(' '); } //add any extra args before the module name. shellCommand.append(windows ? "%*" : "$@").append(' '); String shellPage = getModuleId(moduleName) + ".html"; if (appModule.getShellPage() != null) { shellPage = appModule.getShellPage(); } if (!gwtVersionGreaterThan(1, 5)) { //when invoking the shell for GWT 1.4 or 1.5, it requires a URL to load. //The URL is the [moduleName]/[shellPage.html] shellCommand.append(moduleName).append('/').append(shellPage); } else { //as of 1.6, you invoke it with -startupUrl [shellPage.html] [moduleName] shellCommand.append("-startupUrl ").append(shellPage).append(' ').append(moduleName); } File scriptFile = getShellScriptFile(appName, moduleName); scriptFile.getParentFile().mkdirs(); FileWriter writer = new FileWriter(scriptFile); writer.write(shellCommand.toString()); writer.flush(); writer.close(); File shellFile = getShellScriptFile(appName, moduleName); if (shellFile.exists()) { StringBuilder scriptArtifactId = new StringBuilder(); if ((appName != null) && (appName.trim().length() > 0)) { scriptArtifactId.append(appName).append('.'); } scriptArtifactId.append(moduleName).append(".shell"); getEnunciate() .addArtifact(new FileArtifact(getName(), scriptArtifactId.toString(), shellFile)); } else { debug("No GWT shell script file exists at %s. No artifact added.", shellFile); } } } else { info("Skipping GWT compile for app %s as everything appears up-to-date...", appName); } } }
From source file:org.apache.giraph.zk.ZooKeeperManager.java
/** * If this task has been selected, online a ZooKeeper server. Otherwise, * wait until this task knows that the ZooKeeper servers have been onlined. *//*from w ww . j a va 2s.c om*/ public void onlineZooKeeperServers() { Integer taskId = zkServerPortMap.get(myHostname); if ((taskId != null) && (taskId.intValue() == taskPartition)) { File zkDirFile = new File(this.zkDir); try { if (LOG.isInfoEnabled()) { LOG.info("onlineZooKeeperServers: Trying to delete old " + "directory " + this.zkDir); } FileUtils.deleteDirectory(zkDirFile); } catch (IOException e) { LOG.warn("onlineZooKeeperServers: Failed to delete " + "directory " + this.zkDir, e); } generateZooKeeperConfigFile(new ArrayList<String>(zkServerPortMap.keySet())); ProcessBuilder processBuilder = new ProcessBuilder(); List<String> commandList = Lists.newArrayList(); String javaHome = System.getProperty("java.home"); if (javaHome == null) { throw new IllegalArgumentException("onlineZooKeeperServers: java.home is not set!"); } commandList.add(javaHome + "/bin/java"); String zkJavaOptsString = GiraphConstants.ZOOKEEPER_JAVA_OPTS.get(conf); String[] zkJavaOptsArray = zkJavaOptsString.split(" "); if (zkJavaOptsArray != null) { commandList.addAll(Arrays.asList(zkJavaOptsArray)); } commandList.add("-cp"); Path fullJarPath = new Path(conf.get(GiraphConstants.ZOOKEEPER_JAR)); commandList.add(fullJarPath.toString()); commandList.add(QuorumPeerMain.class.getName()); commandList.add(configFilePath); processBuilder.command(commandList); File execDirectory = new File(zkDir); processBuilder.directory(execDirectory); processBuilder.redirectErrorStream(true); if (LOG.isInfoEnabled()) { LOG.info("onlineZooKeeperServers: Attempting to " + "start ZooKeeper server with command " + commandList + " in directory " + execDirectory.toString()); } try { synchronized (this) { zkProcess = processBuilder.start(); zkProcessCollector = new StreamCollector(zkProcess.getInputStream()); zkProcessCollector.start(); } Runnable runnable = new Runnable() { public void run() { LOG.info("run: Shutdown hook started."); synchronized (this) { if (zkProcess != null) { LOG.warn("onlineZooKeeperServers: " + "Forced a shutdown hook kill of the " + "ZooKeeper process."); zkProcess.destroy(); int exitCode = -1; try { exitCode = zkProcess.waitFor(); } catch (InterruptedException e) { LOG.warn("run: Couldn't get exit code."); } LOG.info("onlineZooKeeperServers: ZooKeeper process exited " + "with " + exitCode + " (note that 143 " + "typically means killed)."); } } } }; Runtime.getRuntime().addShutdownHook(new Thread(runnable)); LOG.info("onlineZooKeeperServers: Shutdown hook added."); } catch (IOException e) { LOG.error("onlineZooKeeperServers: Failed to start " + "ZooKeeper process", e); throw new RuntimeException(e); } // Once the server is up and running, notify that this server is up // and running by dropping a ready stamp. int connectAttempts = 0; final int maxConnectAttempts = conf.getZookeeperConnectionAttempts(); while (connectAttempts < maxConnectAttempts) { try { if (LOG.isInfoEnabled()) { LOG.info("onlineZooKeeperServers: Connect attempt " + connectAttempts + " of " + maxConnectAttempts + " max trying to connect to " + myHostname + ":" + zkBasePort + " with poll msecs = " + pollMsecs); } InetSocketAddress zkServerAddress = new InetSocketAddress(myHostname, zkBasePort); Socket testServerSock = new Socket(); testServerSock.connect(zkServerAddress, 5000); if (LOG.isInfoEnabled()) { LOG.info("onlineZooKeeperServers: Connected to " + zkServerAddress + "!"); } break; } catch (SocketTimeoutException e) { LOG.warn("onlineZooKeeperServers: Got " + "SocketTimeoutException", e); } catch (ConnectException e) { LOG.warn("onlineZooKeeperServers: Got " + "ConnectException", e); } catch (IOException e) { LOG.warn("onlineZooKeeperServers: Got " + "IOException", e); } ++connectAttempts; try { Thread.sleep(pollMsecs); } catch (InterruptedException e) { LOG.warn("onlineZooKeeperServers: Sleep of " + pollMsecs + " interrupted - " + e.getMessage()); } } if (connectAttempts == maxConnectAttempts) { throw new IllegalStateException( "onlineZooKeeperServers: Failed to connect in " + connectAttempts + " tries!"); } Path myReadyPath = new Path(serverDirectory, myHostname + HOSTNAME_TASK_SEPARATOR + taskPartition); try { if (LOG.isInfoEnabled()) { LOG.info("onlineZooKeeperServers: Creating my filestamp " + myReadyPath); } fs.createNewFile(myReadyPath); } catch (IOException e) { LOG.error("onlineZooKeeperServers: Failed (maybe previous " + "task failed) to create filestamp " + myReadyPath, e); } } else { List<String> foundList = new ArrayList<String>(); int readyRetrievalAttempt = 0; while (true) { try { FileStatus[] fileStatusArray = fs.listStatus(serverDirectory); foundList.clear(); if ((fileStatusArray != null) && (fileStatusArray.length > 0)) { for (int i = 0; i < fileStatusArray.length; ++i) { String[] hostnameTaskArray = fileStatusArray[i].getPath().getName() .split(HOSTNAME_TASK_SEPARATOR); if (hostnameTaskArray.length != 2) { throw new RuntimeException("getZooKeeperServerList: Task 0 failed " + "to parse " + fileStatusArray[i].getPath().getName()); } foundList.add(hostnameTaskArray[0]); } if (LOG.isInfoEnabled()) { LOG.info("onlineZooKeeperServers: Got " + foundList + " " + foundList.size() + " hosts from " + fileStatusArray.length + " ready servers when " + serverCount + " required (polling period is " + pollMsecs + ") on attempt " + readyRetrievalAttempt); } if (foundList.containsAll(zkServerPortMap.keySet())) { break; } } else { if (LOG.isInfoEnabled()) { LOG.info("onlineZooKeeperSErvers: Empty " + "directory " + serverDirectory + ", waiting " + pollMsecs + " msecs."); } } Thread.sleep(pollMsecs); ++readyRetrievalAttempt; } catch (IOException e) { throw new RuntimeException(e); } catch (InterruptedException e) { LOG.warn("onlineZooKeeperServers: Strange interrupt from " + e.getMessage(), e); } } } }
From source file:net.rim.ejde.internal.packaging.PackagingManager.java
private void runRapcCommand() throws CoreException { try {/*from w ww . j a v a 2 s .c o m*/ File workDir = _bbProject.getProject().getLocation().toFile(); if (writeToFile) { File outputFile = null; String outputFileName = _bbProject.getProject().getName() + ".files"; outputFile = new File(workDir, outputFileName); _rapcCommandsHead.add("@" + outputFileName); flushToFile(outputFile); } else { _rapcCommandsHead.addAll(_rapcCommands); } String command = getStringCommand(_rapcCommandsHead); _log.trace("Execute rapc command: " + command + "; Working Directory: " + workDir.getPath()); ProcessBuilder rapcBuilder = new ProcessBuilder(_rapcCommandsHead); String javaHome = System.getenv("JAVA_HOME"); if (javaHome != null) { Map<String, String> env = rapcBuilder.environment(); String pathName = "Path"; for (String s : env.keySet()) { if (s.equalsIgnoreCase("Path")) pathName = s; } String path = env.get(pathName); path = path == null ? javaHome : (path + File.pathSeparator + javaHome); path = path + File.pathSeparator + javaHome + File.separator + "bin"; env.put(pathName, path); _log.trace("PATH=" + path); } rapcBuilder.directory(workDir); rapcBuilder.redirectErrorStream(true); long startTime = System.currentTimeMillis(); _consoleOutputStream.println( NLS.bind(Messages.PackagingManager_PACKAGING_PROJECT_MSG, _bbProject.getProject().getName())); _consoleOutputStream.println(command); Process process = rapcBuilder.start(); InputStream inStream = process.getInputStream(); InputStreamHandler inputHandler = new InputStreamHandler(_bbProject.getProject(), _consoleOutputStream, inStream); inputHandler.start(); int result = process.waitFor(); inputHandler.join(); float spendTime = ((float) (System.currentTimeMillis() - startTime)) / 1000; if (result == 0) { _consoleOutputStream.println(NLS.bind(Messages.PackagingManager_PACKAGING_SUCCEED_MSG, new String[] { _bbProject.getProject().getName(), String.valueOf(spendTime) })); } else { _consoleOutputStream.println(NLS.bind(Messages.PackagingManager_PACKAGING_FAILED_MSG, new String[] { _bbProject.getProject().getName(), String.valueOf(spendTime) })); } } catch (IOException e) { throw new CoreException(StatusFactory.createErrorStatus(e.getMessage())); } catch (InterruptedException e) { throw new CoreException(StatusFactory.createErrorStatus(e.getMessage())); } }
From source file:org.pshdl.model.simulation.codegenerator.CCodeGenerator.java
public IHDLInterpreterFactory<NativeRunner> createInterpreter(final File tempDir) { try {/*from w w w. j a v a 2 s. co m*/ final File testCFile = new File(tempDir, "test.c"); String _generateMainCode = this.generateMainCode(); Files.write(_generateMainCode, testCFile, StandardCharsets.UTF_8); final File testRunner = new File(tempDir, "runner.c"); final InputStream runnerStream = CCodeGenerator.class .getResourceAsStream("/org/pshdl/model/simulation/includes/runner.c"); final FileOutputStream fos = new FileOutputStream(testRunner); try { ByteStreams.copy(runnerStream, fos); } finally { runnerStream.close(); fos.close(); } final File executable = new File(tempDir, "testExec"); this.writeAuxiliaryContents(tempDir); String _absolutePath = tempDir.getAbsolutePath(); String _absolutePath_1 = testCFile.getAbsolutePath(); String _absolutePath_2 = testRunner.getAbsolutePath(); String _absolutePath_3 = executable.getAbsolutePath(); final ProcessBuilder builder = new ProcessBuilder(CCodeGenerator.COMPILER, "-I", _absolutePath, "-O3", _absolutePath_1, _absolutePath_2, "-o", _absolutePath_3); ProcessBuilder _directory = builder.directory(tempDir); ProcessBuilder _inheritIO = _directory.inheritIO(); final Process process = _inheritIO.start(); process.waitFor(); int _exitValue = process.exitValue(); boolean _notEquals = (_exitValue != 0); if (_notEquals) { throw new RuntimeException("Process did not terminate with 0"); } return new IHDLInterpreterFactory<NativeRunner>() { public NativeRunner newInstance() { try { String _absolutePath = executable.getAbsolutePath(); final ProcessBuilder execBuilder = new ProcessBuilder(_absolutePath); ProcessBuilder _directory = execBuilder.directory(tempDir); ProcessBuilder _redirectErrorStream = _directory.redirectErrorStream(true); final Process testExec = _redirectErrorStream.start(); InputStream _inputStream = testExec.getInputStream(); OutputStream _outputStream = testExec.getOutputStream(); String _absolutePath_1 = executable.getAbsolutePath(); return new NativeRunner(_inputStream, _outputStream, CCodeGenerator.this.em, testExec, 5, _absolutePath_1); } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } } }; } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } }
From source file:io.snappydata.hydra.cluster.SnappyTest.java
public void executeProcess(ProcessBuilder pb, File logFile) { Process p = null;// w ww . ja va 2 s .c o m try { pb.redirectErrorStream(true); pb.redirectError(ProcessBuilder.Redirect.PIPE); pb.redirectOutput(ProcessBuilder.Redirect.appendTo(logFile)); p = pb.start(); assert pb.redirectInput() == ProcessBuilder.Redirect.PIPE; assert pb.redirectOutput().file() == logFile; assert p.getInputStream().read() == -1; int rc = p.waitFor(); if (rc == 0) { Log.getLogWriter().info("Executed successfully"); } else { Log.getLogWriter().info("Failed with exit code: " + rc); } } catch (IOException e) { throw new TestException( "Exception occurred while starting the process:" + pb + "\nError Message:" + e.getMessage()); } catch (InterruptedException e) { throw new TestException("Exception occurred while waiting for the process execution:" + p + "\nError Message:" + e.getMessage()); } }
From source file:io.snappydata.hydra.cluster.SnappyTest.java
protected void recordSnappyProcessIDinNukeRun(String pName) { Process pr = null;//w w w . ja v a 2s. c o m try { String command; if (pName.equals("Master")) command = "ps ax | grep -w " + pName + " | grep -v grep | awk '{print $1}'"; else command = "jps | grep " + pName + " | awk '{print $1}'"; hd = TestConfig.getInstance().getMasterDescription().getVmDescription().getHostDescription(); ProcessBuilder pb = new ProcessBuilder("/bin/bash", "-c", command); File log = new File("."); pb.redirectErrorStream(true); String dest = log.getCanonicalPath() + File.separator + "PIDs.log"; File logFile = new File(dest); pb.redirectOutput(ProcessBuilder.Redirect.appendTo(logFile)); pr = pb.start(); pr.waitFor(); FileInputStream fis = new FileInputStream(logFile); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); String str = null; while ((str = br.readLine()) != null) { int pid = Integer.parseInt(str); try { if (pids.contains(pid)) { Log.getLogWriter().info("Pid is already recorded with Master" + pid); } else { pids.add(pid); RemoteTestModule.Master.recordPID(hd, pid); SnappyBB.getBB().getSharedMap().put("pid" + "_" + pName + "_" + str, str); } } catch (RemoteException e) { String s = "Unable to access master to record PID: " + pid; throw new HydraRuntimeException(s, e); } Log.getLogWriter().info("pid value successfully recorded with Master"); } br.close(); } catch (IOException e) { String s = "Problem while starting the process : " + pr; throw new TestException(s, e); } catch (InterruptedException e) { String s = "Exception occurred while waiting for the process execution : " + pr; throw new TestException(s, e); } }
From source file:gov.pnnl.goss.gridappsd.service.ServiceManagerImpl.java
@Override public String startServiceForSimultion(String serviceId, String runtimeOptions, Map<String, Object> simulationContext) { String instanceId = serviceId + "-" + new Date().getTime(); // get execution path ServiceInfo serviceInfo = services.get(serviceId); if (serviceInfo == null) { //TODO: publish error on status topic throw new RuntimeException("Service not found: " + serviceId); }//from w ww . java 2s . co m // are multiple allowed? if not check to see if it is already running, if it is then fail if (!serviceInfo.isMultiple_instances() && listRunningServices(serviceId).size() > 0) { throw new RuntimeException( "Service is already running and multiple instances are not allowed: " + serviceId); } File serviceDirectory = new File( getServiceConfigDirectory().getAbsolutePath() + File.separator + serviceId); ProcessBuilder processServiceBuilder = new ProcessBuilder(); Process process = null; List<String> commands = new ArrayList<String>(); Map<String, String> envVars = processServiceBuilder.environment(); //set environment variables List<EnvironmentVariable> envVarList = serviceInfo.getEnvironmentVariables(); for (EnvironmentVariable envVar : envVarList) { String value = envVar.getEnvValue(); //Right now this depends on having the simulationContext set, so don't try it if the simulation context is null if (simulationContext != null) { if (value.contains("(")) { String[] replaceValue = StringUtils.substringsBetween(envVar.getEnvValue(), "(", ")"); for (String args : replaceValue) { value = value.replace("(" + args + ")", simulationContext.get(args).toString()); } } } envVars.put(envVar.getEnvName(), value); } //add executation command commands.add(serviceInfo.getExecution_path()); //Check if static args contain any replacement values List<String> staticArgsList = serviceInfo.getStatic_args(); for (String staticArg : staticArgsList) { if (staticArg != null) { //Right now this depends on having the simulationContext set, so don't try it if the simulation context is null if (simulationContext != null) { if (staticArg.contains("(")) { String[] replaceArgs = StringUtils.substringsBetween(staticArg, "(", ")"); for (String args : replaceArgs) { staticArg = staticArg.replace("(" + args + ")", simulationContext.get(args).toString()); } } } commands.add(staticArg); } } if (runtimeOptions != null) { commands.add(runtimeOptions); } try { if (serviceInfo.getType().equals(ServiceType.PYTHON)) { commands.add(0, "python"); processServiceBuilder.command(commands); if (serviceDirectory.exists()) processServiceBuilder.directory(serviceDirectory); processServiceBuilder.redirectErrorStream(true); processServiceBuilder.redirectOutput(); logManager.log( new LogMessage(this.getClass().getSimpleName(), simulationId, new Date().getTime(), "Starting service with command " + String.join(" ", commands), LogLevel.DEBUG, ProcessStatus.RUNNING, true), GridAppsDConstants.topic_simulationLog + simulationId); process = processServiceBuilder.start(); } else if (serviceInfo.getType().equals(ServiceType.EXE)) { processServiceBuilder.command(commands); if (serviceDirectory.exists()) processServiceBuilder.directory(serviceDirectory); processServiceBuilder.redirectErrorStream(true); processServiceBuilder.redirectOutput(); logManager.log( new LogMessage(this.getClass().getSimpleName(), simulationId, new Date().getTime(), "Starting service with command " + String.join(" ", commands), LogLevel.DEBUG, ProcessStatus.RUNNING, true), GridAppsDConstants.topic_simulationLog + simulationId); process = processServiceBuilder.start(); } else if (serviceInfo.getType().equals(ServiceType.JAVA)) { commands.add(0, "java -jar"); processServiceBuilder.command(commands); if (serviceDirectory.exists()) processServiceBuilder.directory(serviceDirectory); processServiceBuilder.redirectErrorStream(true); processServiceBuilder.redirectOutput(); logManager.log( new LogMessage(this.getClass().getSimpleName(), simulationId, new Date().getTime(), "Starting service with command " + String.join(" ", commands), LogLevel.DEBUG, ProcessStatus.RUNNING, true), GridAppsDConstants.topic_simulationLog + simulationId); process = processServiceBuilder.start(); } else if (serviceInfo.getType().equals(ServiceType.WEB)) { } else { throw new RuntimeException("Type not recognized " + serviceInfo.getType()); } } catch (IOException e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); String sStackTrace = sw.toString(); // stack trace as a string System.out.println(sStackTrace); StringBuilder commandString = new StringBuilder(); for (String s : commands) { commandString.append(s); commandString.append(" "); } logManager.log( new LogMessage(this.getClass().getSimpleName(), simulationId, new Date().getTime(), "Error running command + " + commandString, LogLevel.ERROR, ProcessStatus.ERROR, true), GridAppsDConstants.topic_simulationLog + simulationId); logManager.log( new LogMessage(this.getClass().getSimpleName(), simulationId, new Date().getTime(), sStackTrace, LogLevel.ERROR, ProcessStatus.ERROR, true), GridAppsDConstants.topic_simulationLog + simulationId); } //create serviceinstance object ServiceInstance serviceInstance = new ServiceInstance(instanceId, serviceInfo, runtimeOptions, simulationId, process); serviceInstance.setService_info(serviceInfo); //add to service instances map serviceInstances.put(instanceId, serviceInstance); return instanceId; }
From source file:com.twinsoft.convertigo.engine.localbuild.BuildLocally.java
private String runCommand(File launchDir, String command, List<String> parameters, boolean mergeError) throws Throwable { if (is(OS.win32)) { // Works for cordova and npm command += ".cmd"; }//from ww w . j ava2s .com String shellFullpath = command; String paths = getLocalBuildAdditionalPath(); paths = (paths.length() > 0 ? paths + File.pathSeparator : "") + System.getenv("PATH"); String defaultPaths = null; if (is(OS.mac) || is(OS.linux)) { defaultPaths = "/usr/local/bin"; } else if (is(OS.win32)) { String programFiles = System.getenv("ProgramW6432"); if (programFiles != null && programFiles.length() > 0) { defaultPaths = programFiles + File.separator + "nodejs"; } programFiles = System.getenv("ProgramFiles"); if (programFiles != null && programFiles.length() > 0) { defaultPaths = (defaultPaths == null ? "" : defaultPaths + File.pathSeparator) + programFiles + File.separator + "nodejs"; } String appData = System.getenv("APPDATA"); if (appData != null && appData.length() > 0) { defaultPaths = (defaultPaths == null ? "" : defaultPaths + File.pathSeparator) + appData + File.separator + "npm"; } } paths += File.pathSeparator + defaultPaths; // Checks if the command is already full path if (!(new File(shellFullpath).exists())) { // Else search where the "exec" is and build the absolute path for this "exec" shellFullpath = getFullPath(paths, command); // If the "exec" is not found then it search it elsewhere if (shellFullpath == null) { shellFullpath = command; } } // Prepares the command parameters.add(0, shellFullpath); ProcessBuilder pb = new ProcessBuilder(parameters); // Set the directory from where the command will be executed pb.directory(launchDir.getCanonicalFile()); Map<String, String> pbEnv = pb.environment(); // must set "Path" for Windows 8.1 64 pbEnv.put(pbEnv.get("PATH") == null ? "Path" : "PATH", paths); // Specific to npm command if (shellFullpath.endsWith("npm") || shellFullpath.endsWith("npm.cmd")) { // Set the proxy for npm String proxyMode = EnginePropertiesManager .getProperty(EnginePropertiesManager.PropertyName.PROXY_SETTINGS_MODE); if (proxyMode.equals(ProxyMode.manual.getValue())) { String proxyAuthMethod = EnginePropertiesManager .getProperty(EnginePropertiesManager.PropertyName.PROXY_SETTINGS_METHOD); if (proxyAuthMethod.equals(ProxyMethod.anonymous.getValue()) || proxyAuthMethod.equals(ProxyMethod.basic.getValue())) { String proxyHost = EnginePropertiesManager .getProperty(EnginePropertiesManager.PropertyName.PROXY_SETTINGS_HOST); String proxyPort = EnginePropertiesManager .getProperty(EnginePropertiesManager.PropertyName.PROXY_SETTINGS_PORT); String npmProxy = proxyHost + ":" + proxyPort; if (proxyAuthMethod.equals(ProxyMethod.basic.getValue())) { String proxyUser = EnginePropertiesManager .getProperty(EnginePropertiesManager.PropertyName.PROXY_SETTINGS_USER); String proxyPassword = EnginePropertiesManager .getProperty(EnginePropertiesManager.PropertyName.PROXY_SETTINGS_PASSWORD); npmProxy = proxyUser + ":" + proxyPassword + "@" + npmProxy; } pbEnv.put("http-proxy", "http://" + npmProxy); pbEnv.put("https-proxy", "http://" + npmProxy); } } } pb.redirectErrorStream(mergeError); Engine.logEngine.info("Executing command : " + parameters); process = pb.start(); cmdOutput = ""; // Logs the output new Thread(new Runnable() { @Override public void run() { try { String line; processCanceled = false; BufferedReader bis = new BufferedReader(new InputStreamReader(process.getInputStream())); while ((line = bis.readLine()) != null) { Engine.logEngine.info(line); BuildLocally.this.cmdOutput += line; } } catch (IOException e) { Engine.logEngine.error("Error while executing command", e); } } }).start(); if (!mergeError) { // Logs the error output new Thread(new Runnable() { @Override public void run() { try { String line; processCanceled = false; BufferedReader bis = new BufferedReader(new InputStreamReader(process.getErrorStream())); while ((line = bis.readLine()) != null) { Engine.logEngine.error(line); errorLines += line; } } catch (IOException e) { Engine.logEngine.error("Error while executing command", e); } } }).start(); } int exitCode = process.waitFor(); if (exitCode != 0 && exitCode != 127) { throw new Exception( "Exit code " + exitCode + " when running the command '" + command + "' with parameters : '" + parameters + "'. The output of the command is : '" + cmdOutput + "'"); } return cmdOutput; }
From source file:io.snappydata.hydra.cluster.SnappyTest.java
/** * Task(ENDTASK) for cleaning up snappy processes, because they are not stopped by Hydra in case of Test failure. *//* w w w .ja va 2s . c o m*/ public static void HydraTask_cleanUpSnappyProcessesOnFailure() { Process pr = null; ProcessBuilder pb = null; File logFile = null, log = null, nukeRunOutput = null; try { List<String> pidList = new ArrayList(); HostDescription hd = TestConfig.getInstance().getMasterDescription().getVmDescription() .getHostDescription(); pidList = snappyTest.getPidList(); log = new File("."); String nukerun = log.getCanonicalPath() + File.separator + "snappyNukeRun.sh"; logFile = new File(nukerun); String nukeRunOutputString = log.getCanonicalPath() + File.separator + "nukeRunOutput.log"; nukeRunOutput = new File(nukeRunOutputString); FileWriter fw = new FileWriter(logFile.getAbsoluteFile(), true); BufferedWriter bw = new BufferedWriter(fw); for (String pidString : pidList) { int pid = Integer.parseInt(pidString); bw.write("/bin/kill -KILL " + pid); bw.newLine(); try { RemoteTestModule.Master.removePID(hd, pid); } catch (RemoteException e) { String s = "Failed to remove PID from nukerun script: " + pid; throw new HydraRuntimeException(s, e); } } bw.close(); fw.close(); logFile.setExecutable(true); pb = new ProcessBuilder(nukerun); pb.redirectErrorStream(true); pb.redirectOutput(ProcessBuilder.Redirect.appendTo(nukeRunOutput)); pr = pb.start(); pr.waitFor(); } catch (IOException e) { throw new TestException("IOException occurred while retriving logFile path " + log + "\nError Message:" + e.getMessage()); } catch (InterruptedException e) { String s = "Exception occurred while waiting for the process execution : " + pr; throw new TestException(s, e); } }