List of usage examples for java.lang ProcessBuilder command
List command
To view the source code for java.lang ProcessBuilder command.
Click Source Link
From source file:com.paniclauncher.data.Settings.java
public void restartLauncher() { File thisFile = new File(Update.class.getProtectionDomain().getCodeSource().getLocation().getPath()); String path = null;/*from ww w . ja v a2 s . c om*/ try { path = thisFile.getCanonicalPath(); path = URLDecoder.decode(path, "UTF-8"); } catch (UnsupportedEncodingException e) { this.console.logStackTrace(e); } catch (IOException e) { this.console.logStackTrace(e); } List<String> arguments = new ArrayList<String>(); if (usingMacApp) { arguments.add("open"); arguments.add("-n"); arguments.add(baseDir.getParentFile().getParentFile().getParentFile().getAbsolutePath()); } else { String jpath = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java"; if (Utils.isWindows()) { jpath += "w"; } arguments.add(jpath); arguments.add("-jar"); arguments.add(path); } ProcessBuilder processBuilder = new ProcessBuilder(); processBuilder.command(arguments); try { processBuilder.start(); } catch (IOException e) { e.printStackTrace(); } System.exit(0); }
From source file:org.nuxeo.launcher.NuxeoLauncher.java
/** * Since 5.5/*from w w w. ja va 2 s . c o m*/ */ private boolean pack() { try { checkNoRunningServer(); configurationGenerator.setProperty(PARAM_UPDATECENTER_DISABLED, "true"); List<String> startCommand = new ArrayList<String>(); startCommand.add(getJavaExecutable().getPath()); startCommand.addAll(Arrays.asList(getJavaOptsProperty().split(" "))); startCommand.add("-cp"); String classpath = getClassPath(); classpath = addToClassPath(classpath, "bin" + File.separator + "nuxeo-launcher.jar"); classpath = getClassPath(classpath, configurationGenerator.getServerConfigurator().getServerLibDir()); classpath = getClassPath(classpath, configurationGenerator.getServerConfigurator().getNuxeoLibDir()); classpath = getClassPath(classpath, new File(configurationGenerator.getRuntimeHome(), "bundles")); startCommand.add(classpath); startCommand.addAll(getNuxeoProperties()); if (configurationGenerator.isJBoss) { startCommand.add(PACK_JBOSS_CLASS); } else if (configurationGenerator.isTomcat) { startCommand.add(PACK_TOMCAT_CLASS); } else { errorValue = EXIT_CODE_ERROR; return false; } startCommand.add(configurationGenerator.getRuntimeHome().getPath()); for (String param : params) { startCommand.add(param); } ProcessBuilder pb = new ProcessBuilder(getOSCommand(startCommand)); pb.directory(configurationGenerator.getNuxeoHome()); log.debug("Pack command: " + pb.command()); Process process = pb.start(); ArrayList<ThreadedStreamGobbler> sgArray = logProcessStreams(process, true); Thread.sleep(100); process.waitFor(); waitForProcessStreams(sgArray); } catch (IOException e) { errorValue = EXIT_CODE_ERROR; log.error("Could not start process", e); } catch (InterruptedException e) { errorValue = EXIT_CODE_ERROR; log.error("Could not start process", e); } catch (IllegalStateException e) { errorValue = EXIT_CODE_ERROR; log.error("The server must not be running while running pack command", e); } catch (ConfigurationException e) { errorValue = EXIT_CODE_ERROR; log.error(e); } return errorValue == 0; }
From source file:org.nuxeo.launcher.NuxeoLauncher.java
/** * Do not directly call this method without a call to * {@link #checkNoRunningServer()}/*from w w w.j a v a2s.co m*/ * * @see #doStart() * @throws IOException In case of issue with process. * @throws InterruptedException If any thread has interrupted the current * thread. */ protected void start(boolean logProcessOutput) throws IOException, InterruptedException { List<String> startCommand = new ArrayList<String>(); startCommand.add(getJavaExecutable().getPath()); startCommand.addAll(Arrays.asList(getJavaOptsProperty().split(" "))); startCommand.add("-cp"); startCommand.add(getClassPath()); startCommand.addAll(getNuxeoProperties()); startCommand.addAll(getServerProperties()); setServerStartCommand(startCommand); for (String param : params) { startCommand.add(param); } ProcessBuilder pb = new ProcessBuilder(getOSCommand(startCommand)); pb.directory(configurationGenerator.getNuxeoHome()); // pb = pb.redirectErrorStream(true); log.debug("Server command: " + pb.command()); nuxeoProcess = pb.start(); logProcessStreams(nuxeoProcess, logProcessOutput); Thread.sleep(1000); if (getPid() != null) { log.warn("Server started with process ID " + pid + "."); } else { log.warn("Sent server start command but could not get process ID."); } }
From source file:org.nuxeo.launcher.NuxeoLauncher.java
/** * Stops the server.//w ww . j av a 2s . c o m * * Will try to call specific class for a clean stop, retry * {@link #STOP_NB_TRY}, waiting {@link #STOP_SECONDS_BEFORE_NEXT_TRY} * between each try, then kill the process if still running. */ public void stop(boolean logProcessOutput) { long startTime = new Date().getTime(); long deltaTime; try { if (!isRunning()) { log.warn("Server is not running."); return; } if (!quiet) { System.out.print("\nStopping server..."); } int nbTry = 0; boolean retry = false; int stopMaxWait = Integer.parseInt( configurationGenerator.getUserConfig().getProperty(STOP_MAX_WAIT_PARAM, STOP_MAX_WAIT_DEFAULT)); do { List<String> stopCommand = new ArrayList<String>(); stopCommand.add(getJavaExecutable().getPath()); stopCommand.add("-cp"); stopCommand.add(getShutdownClassPath()); stopCommand.addAll(getNuxeoProperties()); stopCommand.addAll(getServerProperties()); setServerStopCommand(stopCommand); for (String param : params) { stopCommand.add(param); } ProcessBuilder pb = new ProcessBuilder(getOSCommand(stopCommand)); pb.directory(configurationGenerator.getNuxeoHome()); // pb = pb.redirectErrorStream(true); log.debug("Server command: " + pb.command()); try { Process stopProcess = pb.start(); ArrayList<ThreadedStreamGobbler> sgArray = logProcessStreams(stopProcess, logProcessOutput); stopProcess.waitFor(); waitForProcessStreams(sgArray); boolean wait = true; while (wait) { try { if (stopProcess.exitValue() == 0) { // Successful call for server stop retry = false; } else { // Failed to call for server stop retry = ++nbTry < STOP_NB_TRY; if (!quiet) { System.out.print("."); } Thread.sleep(STOP_SECONDS_BEFORE_NEXT_TRY * 1000); } wait = false; } catch (IllegalThreadStateException e) { // Stop call is still running wait = true; if (!quiet) { System.out.print("."); } Thread.sleep(1000); } } // Exit if there's no way to check for server stop if (processManager instanceof PureJavaProcessManager) { log.warn("Can't check server status on your OS."); return; } // Wait a few seconds for effective stop deltaTime = 0; do { if (!quiet) { System.out.print("."); } Thread.sleep(1000); deltaTime = (new Date().getTime() - startTime) / 1000; } while (!retry && getPid() != null && deltaTime < stopMaxWait); } catch (InterruptedException e) { log.error(e); } } while (retry); if (getPid() == null) { log.warn("Server stopped."); } else { log.info("No answer from server, try to kill process " + pid + "..."); processManager.kill(nuxeoProcess, pid); if (getPid() == null) { log.warn("Server forcibly stopped."); } } } catch (IOException e) { log.error("Could not manage process!", e); } }
From source file:com.netflix.genie.agent.execution.services.impl.LaunchJobServiceImpl.java
/** * {@inheritDoc}/*from www . j ava2 s. co m*/ */ @Override public void launchProcess(final File jobDirectory, final Map<String, String> environmentVariablesMap, final List<String> commandLine, final boolean interactive) throws JobLaunchException { if (!launched.compareAndSet(false, true)) { throw new IllegalStateException("Job already launched"); } final ProcessBuilder processBuilder = new ProcessBuilder(); // Validate job running directory if (jobDirectory == null) { throw new JobLaunchException("Job directory is null"); } else if (!jobDirectory.exists()) { throw new JobLaunchException("Job directory does not exist: " + jobDirectory); } else if (!jobDirectory.isDirectory()) { throw new JobLaunchException("Job directory is not a directory: " + jobDirectory); } else if (!jobDirectory.canWrite()) { throw new JobLaunchException("Job directory is not writable: " + jobDirectory); } final Map<String, String> currentEnvironmentVariables = processBuilder.environment(); if (environmentVariablesMap == null) { throw new JobLaunchException("Job environment variables map is null"); } // Merge job environment variables into process inherited environment environmentVariablesMap.forEach((key, value) -> { final String replacedValue = currentEnvironmentVariables.put(key, value); if (StringUtils.isBlank(replacedValue)) { log.debug("Added job environment variable: {}={}", key, value); } else if (!replacedValue.equals(value)) { log.debug("Set job environment variable: {}={} (previous value: {})", key, value, replacedValue); } }); // Validate arguments if (commandLine == null) { throw new JobLaunchException("Job command-line arguments is null"); } else if (commandLine.isEmpty()) { throw new JobLaunchException("Job command-line arguments are empty"); } // Configure arguments log.info("Job command-line: {}", Arrays.toString(commandLine.toArray())); final List<String> expandedCommandLine; try { expandedCommandLine = expandCommandLineVariables(commandLine, Collections.unmodifiableMap(currentEnvironmentVariables)); } catch (final EnvUtils.VariableSubstitutionException e) { throw new JobLaunchException("Job command-line arguments variables could not be expanded"); } if (!commandLine.equals(expandedCommandLine)) { log.info("Job command-line with variables expanded: {}", Arrays.toString(expandedCommandLine.toArray())); } processBuilder.command(expandedCommandLine); if (interactive) { processBuilder.inheritIO(); } else { processBuilder.redirectError(PathUtils.jobStdErrPath(jobDirectory).toFile()); processBuilder.redirectOutput(PathUtils.jobStdOutPath(jobDirectory).toFile()); } if (killed.get()) { log.info("Job aborted, skipping launch"); } else { log.info("Launching job"); try { processReference.set(processBuilder.start()); } catch (final IOException | SecurityException e) { throw new JobLaunchException("Failed to launch job: ", e); } log.info("Process launched (pid: {})", getPid(processReference.get())); } }
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 w w .j a v a 2 s. c om*/ // 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:org.eu.eark.textclassification.TextClassifierMapper.java
protected void map(Object key, Text value, Context context) throws IOException, InterruptedException { String c = ","; String value_string = value.toString(); int i = value_string.lastIndexOf(c); String[] values = { value_string.substring(0, i), value_string.substring(i + 1) }; //should be able to handle "," in path String idPath = values[0];/*w w w. j av a 2s. c om*/ String fileType = values[1]; Configuration conf = context.getConfiguration(); // get classifier and model from parameters String classifier = conf.get(TextClassifierJob.CLASSIFIER); String model = conf.get(TextClassifierJob.MODEL); List<String> pythonCmd = new ArrayList<>(); pythonCmd.add("python"); pythonCmd.add(classifier); pythonCmd.add(model); String result; // List<String> resultList = new ArrayList<String>(); // only needed if a list of files is provided to python (same for errorList) String category = "category"; //String category_alt = "category_alternative"; String error; // List<String> errorList = new ArrayList<String>(); ProcessBuilder pb = new ProcessBuilder(); // TODO: is an identifier needed? - adapt py script if yes (three input arguments!) - maybe on cluster, but not on earkdev // pythonCmd.add(fileID); // get input from Lily (content) and write if to the Hadoop filesystem String filename = RandomStringUtils.randomAlphanumeric(20); FileSystem fs_local = FileSystem.getLocal(conf); Path pt_local = new Path(String.format("/tmp/clfin/%s.out", filename)); InputStream contentstream = null; try { String tableName = conf.get(TextClassifierJob.TABLE_NAME); LTable table = tableName == null ? repository.getDefaultTable() : repository.getTable(tableName); RecordId id = repository.getIdGenerator().newRecordId(idPath); // get the content fields' content - a BLOB contentstream = table.getBlob(id, q("content")).getInputStream(); } catch (RecordNotFoundException e) { System.out.println("Record doesn't exist: " + idPath); } catch (InterruptedException | RepositoryException e) { throw new RuntimeException(e); } if ("application/pdf".equals(fileType)) { // special case: BLOB is a pdf - extract the text and write as plain text TikaInputStream tikainput = TikaInputStream.get(contentstream); BodyContentHandler handler = new BodyContentHandler(-1); // -1 means no char limit on parse Metadata metadata = new Metadata(); ParseContext pcontext = new ParseContext(); // parsing the document using PDF parser PDFParser pdfparser = new PDFParser(); try { pdfparser.parse(tikainput, handler, metadata, pcontext); } catch (SAXException | TikaException ex) { Logger.getLogger(TextClassifierMapper.class.getName()).log(Level.SEVERE, null, ex); } // write the content to file (metadata is omitted because not of interest) BufferedWriter br = new BufferedWriter(new OutputStreamWriter(fs_local.create(pt_local, true))); br.write(handler.toString().replace("\n", " ")); // remove all the newlines - it confuses the classifier, for whatever reason br.close(); } else { // every other file // this writes a copy of the BLOB to the local filesystem - beware of the file type, must be plain text! byte[] buff = new byte[4096]; int len = 0; OutputStream out = fs_local.create(pt_local); while ((len = contentstream.read(buff)) != -1) { out.write(buff, 0, len); } out.close(); } // add the filename to the python command pythonCmd.add(String.format("%s.out", filename)); pb.command(pythonCmd); //System.out.println(pb.command()); try { // start the process Process p = pb.start(); BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); while ((result = stdInput.readLine()) != null) { // resultList.add(result); String[] categories = result.split(","); category = String.format(categories[0] + " " + categories[1]); //category_alt = categories[1]; System.out.println(category); //System.out.println(category_alt); } BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream())); while ((error = stdError.readLine()) != null) { // errorList.add(error); System.out.println(error); throw new PythonException(error); } } catch (IOException | PythonException ex) { Logger.getLogger(TextClassifierMapper.class.getName()).log(Level.SEVERE, null, ex); } // reset the StringBuilder (length 0) and remove the last item from pythonCmd (else the pythonCmd just gets longer) pythonCmd.remove(pythonCmd.size() - 1); // pythonCmd.remove(pythonCmd.size() - 1); // only if three arguments are passed // write the results to Lily: try { String tableName = conf.get(TextClassifierJob.TABLE_NAME); LTable table = tableName == null ? repository.getDefaultTable() : repository.getTable(tableName); RecordId id = repository.getIdGenerator().newRecordId(idPath); Record record_category = table.read(id, q("textCategory")); record_category.setField(q("textCategory"), category); table.createOrUpdate(record_category); Indexer indexer = lilyClient.getIndexer(); indexer.index(table.getTableName(), record_category.getId()); } catch (RecordNotFoundException e) { System.out.println("Record doesn't exist!"); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.atlauncher.data.Settings.java
public void runUpdate(String currentPath, String temporaryUpdatePath) { List<String> arguments = new ArrayList<String>(); String path = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java"; if (Utils.isWindows()) { path += "w"; }//from ww w . j a v a 2s .co m arguments.add(path); arguments.add("-cp"); arguments.add(temporaryUpdatePath); arguments.add("com.atlauncher.Update"); arguments.add(currentPath); arguments.add(temporaryUpdatePath); ProcessBuilder processBuilder = new ProcessBuilder(); processBuilder.command(arguments); LogManager.info("Running launcher update with command " + arguments); try { processBuilder.start(); } catch (IOException e) { this.logStackTrace(e); } System.exit(0); }
From source file:com.atlauncher.data.Settings.java
public void restartLauncher() { File thisFile = new File(Update.class.getProtectionDomain().getCodeSource().getLocation().getPath()); String path = null;// w w w .jav a2s. c o m try { path = thisFile.getCanonicalPath(); path = URLDecoder.decode(path, "UTF-8"); } catch (UnsupportedEncodingException e) { logStackTrace(e); } catch (IOException e) { logStackTrace(e); } List<String> arguments = new ArrayList<String>(); if (this.isUsingMacApp()) { arguments.add("open"); arguments.add("-n"); arguments.add(baseDir.getParentFile().getParentFile().getParentFile().getAbsolutePath()); } else { String jpath = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java"; if (Utils.isWindows()) { jpath += "w"; } arguments.add(jpath); arguments.add("-jar"); arguments.add(path); } ProcessBuilder processBuilder = new ProcessBuilder(); processBuilder.command(arguments); try { processBuilder.start(); } catch (IOException e) { e.printStackTrace(); } System.exit(0); }