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:com.novartis.opensource.yada.adaptor.SOAPAdaptor.java
/** * Constructs and executes a SOAP message. For {@code basic} authentication, YADA uses the * java soap api, and the {@link SOAPConnection} object stored in the query object. For * NTLM, which was never successful using the java api, YADA calls out to {@link #CURL_EXEC} * in {@link #YADA_BIN}. /* w w w. ja v a 2 s . co m*/ * @see com.novartis.opensource.yada.adaptor.Adaptor#execute(com.novartis.opensource.yada.YADAQuery) */ @Override public void execute(YADAQuery yq) throws YADAAdaptorExecutionException { String result = ""; resetCountParameter(yq); SOAPConnection connection = (SOAPConnection) yq.getConnection(); for (int row = 0; row < yq.getData().size(); row++) { yq.setResult(); YADAQueryResult yqr = yq.getResult(); String soapUrl = yq.getSoap(row); try { this.endpoint = new URL(soapUrl); MessageFactory factory = MessageFactory.newInstance(); SOAPMessage message = factory.createMessage(); byte[] authenticationToken = Base64.encodeBase64((this.soapUser + ":" + this.soapPass).getBytes()); // Assume a SOAP message was built previously MimeHeaders mimeHeaders = message.getMimeHeaders(); if ("basic".equals(this.soapAuth.toLowerCase())) { mimeHeaders.addHeader("Authorization", this.soapAuth + " " + new String(authenticationToken)); mimeHeaders.addHeader("SOAPAction", this.soapAction); mimeHeaders.addHeader("Content-Type", "text/xml"); SOAPHeader header = message.getSOAPHeader(); SOAPBody body = message.getSOAPBody(); header.detachNode(); l.debug("query:\n" + this.queryString); try { Document xml = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(new ByteArrayInputStream(this.soapData.getBytes())); //SOAPBodyElement docElement = body.addDocument(xml); Authenticator.setDefault(new YadaSoapAuthenticator(this.soapUser, this.soapPass)); SOAPMessage response = connection.call(message, this.endpoint); try (ByteArrayOutputStream responseOutputStream = new ByteArrayOutputStream()) { response.writeTo(responseOutputStream); result = responseOutputStream.toString(); } } catch (IOException e) { String msg = "Unable to process input or output stream for SOAP message with Basic Authentication. This is an I/O problem, not an authentication issue."; throw new YADAAdaptorExecutionException(msg, e); } l.debug("SOAP Body:\n" + result); } else if (AUTH_NTLM.equals(this.soapAuth.toLowerCase()) || "negotiate".equals(this.soapAuth.toLowerCase())) { ArrayList<String> args = new ArrayList<>(); args.add(Finder.getEnv(YADA_BIN) + CURL_EXEC); args.add("-X"); args.add("-s"); args.add(this.soapSource + this.soapPath); args.add("-u"); args.add(this.soapDomain + "\\" + this.soapUser); args.add("-p"); args.add(this.soapPass); args.add("-a"); args.add(this.soapAuth); args.add("-q"); args.add(this.soapData); args.add("-t"); args.add(this.soapAction); String[] cmds = args.toArray(new String[0]); l.debug("Executing soap request via script: " + Arrays.toString(cmds)); String s = null; try { ProcessBuilder pb = new ProcessBuilder(args); l.debug(pb.environment().toString()); pb.redirectErrorStream(true); Process p = pb.start(); try (BufferedReader si = new BufferedReader(new InputStreamReader(p.getInputStream()))) { while ((s = si.readLine()) != null) { l.debug(s); if (null == result) { result = ""; } result += s; } } } catch (IOException e) { String msg = "Unable to execute NTLM-authenticated SOAP call using system call to 'curl'. Make sure the curl executable is still accessible."; throw new YADAAdaptorExecutionException(msg, e); } } } catch (SOAPException e) { String msg = "There was a problem creating or executing the SOAP message, or receiving the response."; throw new YADAAdaptorExecutionException(msg, e); } catch (SAXException e) { String msg = "Unable to parse SOAP message body."; throw new YADAAdaptorExecutionException(msg, e); } catch (ParserConfigurationException e) { String msg = "There was a problem creating the xml document for the SOAP message body."; throw new YADAAdaptorExecutionException(msg, e); } catch (YADAResourceException e) { String msg = "Cannot find 'curl' executable at specified JNDI path " + YADA_BIN + CURL_EXEC; throw new YADAAdaptorExecutionException(msg, e); } catch (MalformedURLException e) { String msg = "Can't create URL from provided source and path."; throw new YADAAdaptorExecutionException(msg, e); } finally { try { ConnectionFactory.releaseResources(connection, yq.getSoap().get(0)); } catch (YADAConnectionException e) { l.error(e.getMessage()); } } yqr.addResult(row, result); } }
From source file:gui.sqlmap.SqlmapUi.java
private void startSqlmap() { String python = textfieldPython.getText(); String workingDir = textfieldWorkingdir.getText(); String sqlmap = textfieldSqlmap.getText(); // Do some basic tests File f;//from w w w . j a v a 2 s .c o m f = new File(python); if (!f.exists()) { JOptionPane.showMessageDialog(this, "Python path does not exist: " + python); return; } f = new File(workingDir); if (!f.exists()) { JOptionPane.showMessageDialog(this, "workingDir path does not exist: " + workingDir); return; } f = new File(sqlmap); if (!f.exists()) { JOptionPane.showMessageDialog(this, "sqlmap path does not exist: " + sqlmap); return; } // Write request file String requestFile = workingDir + "request.txt"; try { FileOutputStream fos = new FileOutputStream(requestFile); fos.write(httpMessage.getRequest()); fos.close(); } catch (IOException e) { JOptionPane.showMessageDialog(this, "could not write request: " + workingDir + "request.txt"); BurpCallbacks.getInstance().print("Error: " + e.getMessage()); } // Start sqlmap args = new ArrayList<String>(); args.add(python); args.add(sqlmap); args.add("-r"); args.add(requestFile); args.add("--batch"); args.add("-p"); args.add(attackParam.getName()); String sessionFile = workingDir + "sessionlog.txt"; args.add("-s"); args.add(sessionFile); args.add("--flush-session"); String traceFile = workingDir + "tracelog.txt"; args.add("-t"); args.add(traceFile); args.add("--disable-coloring"); args.add("--cleanup"); textareaCommand.setText(StringUtils.join(args, " ")); SwingWorker worker = new SwingWorker<String, Void>() { @Override public String doInBackground() { ProcessBuilder pb = new ProcessBuilder(args); //BurpCallbacks.getInstance().print(pb.command().toString()); pb.redirectErrorStream(true); Process proc; try { proc = pb.start(); InputStream is = proc.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; int exit = -1; while ((line = br.readLine()) != null) { // Outputs your process execution addLine(line); try { exit = proc.exitValue(); if (exit == 0) { // Process finished } } catch (IllegalThreadStateException t) { // The process has not yet finished. // Should we stop it? //if (processMustStop()) // processMustStop can return true // after time out, for example. //{ // proc.destroy(); //} } } } catch (IOException ex) { BurpCallbacks.getInstance().print(ex.getLocalizedMessage()); } return ""; } @Override public void done() { } }; worker.execute(); }
From source file:io.hops.hopsworks.common.dao.tensorflow.config.TensorBoardProcessMgr.java
/** * Start the TensorBoard process/*from www .j a v a2s. c om*/ * @param project * @param user * @param hdfsUser * @param hdfsLogdir * @return * @throws IOException */ @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public TensorBoardDTO startTensorBoard(Project project, Users user, HdfsUsers hdfsUser, String hdfsLogdir) throws IOException { String prog = settings.getHopsworksDomainDir() + "/bin/tensorboard.sh"; Process process = null; Integer port = 0; BigInteger pid = null; String tbBasePath = settings.getStagingDir() + Settings.TENSORBOARD_DIRS + File.separator; String projectUserUniquePath = project.getName() + "_" + hdfsUser.getName(); String tbPath = tbBasePath + DigestUtils.sha256Hex(projectUserUniquePath); String certsPath = "\"\""; File tbDir = new File(tbPath); if (tbDir.exists()) { for (File file : tbDir.listFiles()) { if (file.getName().endsWith(".pid")) { String pidContents = com.google.common.io.Files.readFirstLine(file, Charset.defaultCharset()); try { pid = BigInteger.valueOf(Long.parseLong(pidContents)); if (pid != null && ping(pid) == 0) { killTensorBoard(pid); } } catch (NumberFormatException nfe) { LOGGER.log(Level.WARNING, "Expected number in pidfile " + file.getAbsolutePath() + " got " + pidContents); } } } FileUtils.deleteDirectory(tbDir); } tbDir.mkdirs(); DistributedFileSystemOps dfso = dfsService.getDfsOps(); try { certsPath = tbBasePath + DigestUtils.sha256Hex(projectUserUniquePath + "_certs"); File certsDir = new File(certsPath); certsDir.mkdirs(); HopsUtils.materializeCertificatesForUserCustomDir(project.getName(), user.getUsername(), settings.getHdfsTmpCertDir(), dfso, certificateMaterializer, settings, certsPath); } catch (IOException ioe) { LOGGER.log(Level.SEVERE, "Failed in materializing certificates for " + hdfsUser + " in directory " + certsPath, ioe); HopsUtils.cleanupCertificatesForUserCustomDir(user.getUsername(), project.getName(), settings.getHdfsTmpCertDir(), certificateMaterializer, certsPath, settings); } finally { if (dfso != null) { dfsService.closeDfsClient(dfso); } } String anacondaEnvironmentPath = settings.getAnacondaProjectDir(project.getName()); int retries = 3; while (retries > 0) { if (retries == 0) { throw new IOException( "Failed to start TensorBoard for project=" + project.getName() + ", user=" + user.getUid()); } // use pidfile to kill any running servers port = ThreadLocalRandom.current().nextInt(40000, 59999); String[] command = new String[] { "/usr/bin/sudo", prog, "start", hdfsUser.getName(), hdfsLogdir, tbPath, port.toString(), anacondaEnvironmentPath, settings.getHadoopVersion(), certsPath, settings.getJavaHome() }; LOGGER.log(Level.INFO, Arrays.toString(command)); ProcessBuilder pb = new ProcessBuilder(command); try { // Send both stdout and stderr to the same stream pb.redirectErrorStream(true); process = pb.start(); synchronized (pb) { try { // Wait until the launcher bash script has finished process.waitFor(20l, TimeUnit.SECONDS); } catch (InterruptedException ex) { LOGGER.log(Level.SEVERE, "Woken while waiting for the TensorBoard to start: {0}", ex.getMessage()); } } int exitValue = process.exitValue(); String pidPath = tbPath + File.separator + port + ".pid"; File pidFile = new File(pidPath); // Read the pid for TensorBoard server if (pidFile.exists()) { String pidContents = com.google.common.io.Files.readFirstLine(pidFile, Charset.defaultCharset()); pid = BigInteger.valueOf(Long.parseLong(pidContents)); } if (exitValue == 0 && pid != null) { int maxWait = 10; String logFilePath = tbPath + File.separator + port + ".log"; File logFile = new File(logFilePath); while (maxWait > 0) { String logFileContents = com.google.common.io.Files.readFirstLine(logFile, Charset.defaultCharset()); // It is not possible to have a fixed wait time before showing the TB, we need to be sure it has started if (logFile.length() > 0 && (logFileContents.contains("Loaded") | logFileContents.contains("Reloader") | logFileContents.contains("event")) | maxWait == 1) { Thread.currentThread().sleep(5000); TensorBoardDTO tensorBoardDTO = new TensorBoardDTO(); String host = null; try { host = InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException ex) { Logger.getLogger(TensorBoardProcessMgr.class.getName()).log(Level.SEVERE, null, ex); } tensorBoardDTO.setEndpoint(host + ":" + port); tensorBoardDTO.setPid(pid); return tensorBoardDTO; } else { Thread.currentThread().sleep(1000); maxWait--; } } TensorBoardDTO tensorBoardDTO = new TensorBoardDTO(); tensorBoardDTO.setPid(pid); String host = null; try { host = InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException ex) { Logger.getLogger(TensorBoardProcessMgr.class.getName()).log(Level.SEVERE, null, ex); } tensorBoardDTO.setEndpoint(host + ":" + port); return tensorBoardDTO; } else { LOGGER.log(Level.SEVERE, "Failed starting TensorBoard got exitcode " + exitValue + " retrying on new port"); if (pid != null) { this.killTensorBoard(pid); } pid = null; } } catch (Exception ex) { LOGGER.log(Level.SEVERE, "Problem starting TensorBoard: {0}", ex); if (process != null) { process.destroyForcibly(); } } finally { retries--; } } //Failed to start TensorBoard, make sure there is no process running for it! (This should not be needed) if (pid != null && this.ping(pid) == 0) { this.killTensorBoard(pid); } //Certificates cleanup in case they were materialized but no TB started successfully dfso = dfsService.getDfsOps(); certsPath = tbBasePath + DigestUtils.sha256Hex(projectUserUniquePath + "_certs"); File certsDir = new File(certsPath); certsDir.mkdirs(); try { HopsUtils.cleanupCertificatesForUserCustomDir(user.getUsername(), project.getName(), settings.getHdfsTmpCertDir(), certificateMaterializer, certsPath, settings); } finally { if (dfso != null) { dfsService.closeDfsClient(dfso); } } return null; }
From source file:com.opentable.db.postgres.embedded.EmbeddedPostgres.java
private void startPostmaster() throws IOException { final StopWatch watch = new StopWatch(); watch.start();//from ww w. ja va 2 s .c om Preconditions.checkState(started.getAndSet(true) == false, "Postmaster already started"); final List<String> args = Lists.newArrayList(pgBin("pg_ctl"), "-D", dataDirectory.getPath(), "-o", Joiner.on(" ").join(createInitOptions()), "start"); final ProcessBuilder builder = new ProcessBuilder(args); builder.redirectErrorStream(true); builder.redirectError(outputRedirector); builder.redirectOutput(outputRedirector); postmaster = builder.start(); LOG.info("{} postmaster started as {} on port {}. Waiting up to {}ms for server startup to finish.", instanceId, postmaster.toString(), port, PG_STARTUP_WAIT_MS); Runtime.getRuntime().addShutdownHook(newCloserThread()); waitForServerStartup(watch); }
From source file:de.jcup.egradle.core.process.SimpleProcessExecutor.java
@Override public int execute(ProcessConfiguration wdProvider, EnvironmentProvider envProvider, ProcessContext processContext, String... commands) throws IOException { notNull(wdProvider, "'wdProvider' may not be null"); notNull(envProvider, "'envProvider' may not be null"); String wd = wdProvider.getWorkingDirectory(); /* Working directory */ File workingDirectory = null; if (StringUtils.isNotBlank(wd)) { workingDirectory = new File(wd); }/* w w w . j av a 2 s .co m*/ if (workingDirectory != null) { if (!workingDirectory.exists()) { throw new FileNotFoundException("Working directory does not exist:" + workingDirectory); } } /* Create process with dedicated environment */ ProcessBuilder pb = new ProcessBuilder(commands); Map<String, String> env = envProvider.getEnvironment(); /* init environment */ if (env != null) { Map<String, String> pbEnv = pb.environment(); for (String key : env.keySet()) { pbEnv.put(key, env.get(key)); } } /* init working directory */ pb.directory(workingDirectory); pb.redirectErrorStream(true); Date started = new Date(); Process p = startProcess(pb); ProcessTimeoutTerminator timeoutTerminator = null; if (timeOutInSeconds != ENDLESS_RUNNING) { timeoutTerminator = new ProcessTimeoutTerminator(p, outputHandler, timeOutInSeconds); timeoutTerminator.start(); } ProcessCancelTerminator cancelTerminator = new ProcessCancelTerminator(p, processContext.getCancelStateProvider()); Thread cancelCheckThread = new Thread(cancelTerminator, "process-cancel-terminator"); cancelCheckThread.start(); handleProcessStarted(envProvider, p, started, workingDirectory, commands); handleOutputStreams(p, timeoutTerminator, processContext.getCancelStateProvider()); /* wait for execution */ try { while (isAlive(p)) { waitFor(p); } } catch (InterruptedException e) { /* ignore */ } /* done */ int exitValue = p.exitValue(); handleProcessEnd(p); return exitValue; }
From source file:org.sonar.application.process.ProcessLauncherImpl.java
private ProcessBuilder create(AbstractCommand<?> javaCommand, List<String> commands) { ProcessBuilder processBuilder = processBuilderSupplier.get(); processBuilder.command(commands);//from w w w.jav a 2 s . co m processBuilder.directory(javaCommand.getWorkDir()); Map<String, String> environment = processBuilder.environment(); environment.putAll(javaCommand.getEnvVariables()); javaCommand.getSuppressedEnvVariables().forEach(environment::remove); processBuilder.redirectErrorStream(true); return processBuilder; }
From source file:jp.co.tis.gsp.tools.dba.dialect.OracleDialect.java
@Override public void exportSchema(ExportParams params) throws MojoExecutionException { BufferedReader reader = null; try {/*from w w w. java2 s. c o m*/ File dumpFile = params.getDumpFile(); String user = params.getUser(); String password = params.getPassword(); String schema = params.getSchema(); createDirectory(user, password, dumpFile.getParentFile()); ProcessBuilder pb = new ProcessBuilder("expdp", user + "/" + password, "directory=exp_dir", "dumpfile=" + dumpFile.getName(), "schemas=" + schema, "reuse_dumpfiles=y", "nologfile=y"); pb.redirectErrorStream(true); Process process = pb.start(); Charset terminalCharset = System.getProperty("os.name").toLowerCase().contains("windows") ? Charset.forName("Shift_JIS") : Charset.forName("UTF-8"); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), terminalCharset)); //??????????????? String line; while ((line = reader.readLine()) != null) { System.out.println(line); } process.waitFor(); if (process.exitValue() != 0) { throw new MojoExecutionException("oracle export error"); } process.destroy(); } catch (Exception e) { throw new MojoExecutionException("oracle export", e); } finally { IOUtils.closeQuietly(reader); } }
From source file:org.apache.flume.test.util.StagedInstall.java
public synchronized void startAgent(String name, Properties properties) throws Exception { if (process != null) { throw new Exception("A process is already running"); }/*from w w w . j av a 2 s .c o m*/ LOGGER.info("Starting process for agent: " + name + " using config: " + properties); File configFile = createConfigurationFile(name, properties); configFilePath = configFile.getCanonicalPath(); String configFileName = configFile.getName(); String logFileName = "flume-" + name + "-" + configFileName.substring(0, configFileName.indexOf('.')) + ".log"; LOGGER.info("Created configuration file: " + configFilePath); String[] cmdArgs = { launchScriptPath, "agent", "-n", name, "-f", configFilePath, "-c", confDirPath, "-D" + ENV_FLUME_LOG_DIR + "=" + logDirPath, "-D" + ENV_FLUME_ROOT_LOGGER + "=" + ENV_FLUME_ROOT_LOGGER_VALUE, "-D" + ENV_FLUME_LOG_FILE + "=" + logFileName }; StringBuilder sb = new StringBuilder(""); for (String cmdArg : cmdArgs) { sb.append(cmdArg).append(" "); } LOGGER.info("Using command: " + sb.toString()); ProcessBuilder pb = new ProcessBuilder(cmdArgs); Map<String, String> env = pb.environment(); LOGGER.debug("process environment: " + env); pb.directory(baseDir); pb.redirectErrorStream(true); process = pb.start(); consumer = new ProcessInputStreamConsumer(process.getInputStream()); consumer.start(); shutdownHook = new ProcessShutdownHook(); Runtime.getRuntime().addShutdownHook(shutdownHook); Thread.sleep(3000); // sleep for 3s to let system initialize }
From source file:service.impl.DatabaseBackupServiceImpl.java
/** * To be compatible to Windows 7 and 10 (the original function could just work on win 10), * Using the ProcessBuilder as the main class to initialize the process and generate the file. * The ProcessBuilder receives the command as the separated string (by space). * The backup file couldn't be generated without calling waitFor(). * After this function, the uploadFtp() will be called, and upload this file to remote, one day one file. * The default path of generated file is located on C:\\ * This path is defined on the properties backup.properties. * /*from ww w . j a v a 2s .co m*/ */ @Override public void backup() throws ServiceException { Process proc = null; try { ProcessBuilder procBuilder = new ProcessBuilder("cmd", "/c", mysqlBinPath + "mysqldump", "--lock-all-tables", "--flush-logs", "-h", srcHost, "-u" + srcUsername, "-p" + srcPassword, "--databases", srcDbname); procBuilder.directory(new File(bakSqlPath)); File sqlBackupFile = new File(bakSqlPath + System.getProperty("file.separator") + bakSqlFile); sqlBackupFile.delete(); sqlBackupFile.createNewFile(); procBuilder.redirectErrorStream(true); procBuilder.redirectOutput(Redirect.to(sqlBackupFile)); proc = procBuilder.start(); proc.waitFor(); } catch (Exception e) { e.printStackTrace(); throw new ServiceException(e); } finally { try { if (proc != null) { proc.destroy(); } } catch (Exception e) { e.printStackTrace(); } } }
From source file:jp.co.tis.gsp.tools.dba.dialect.OracleDialect.java
@Override public void importSchema(ImportParams params) throws MojoExecutionException { BufferedReader reader = null; try {//from ww w . j a va2 s . c o m File dumpFile = params.getDumpFile(); if (!dumpFile.exists()) throw new MojoExecutionException(dumpFile.getName() + " is not found?"); String user = params.getAdminUser(); String password = params.getAdminPassword(); String schema = params.getSchema(); createDirectory(user, password, dumpFile.getParentFile()); // Oracle????? dropAllObjects(user, password, schema); ProcessBuilder pb = new ProcessBuilder("impdp", user + "/" + password, "directory=exp_dir", "dumpfile=" + dumpFile.getName(), "schemas=" + schema, "nologfile=y", "exclude=user"); pb.redirectErrorStream(true); Process process = pb.start(); Charset terminalCharset = System.getProperty("os.name").toLowerCase().contains("windows") ? Charset.forName("Shift_JIS") : Charset.forName("UTF-8"); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), terminalCharset)); //??????????????? String line; while ((line = reader.readLine()) != null) { System.out.println(line); } process.waitFor(); if (process.exitValue() != 0) { throw new MojoExecutionException("oracle import error"); } process.destroy(); } catch (Exception e) { throw new MojoExecutionException("oracle import", e); } finally { IOUtils.closeQuietly(reader); } }