List of usage examples for org.apache.commons.exec DefaultExecutor setStreamHandler
public void setStreamHandler(final ExecuteStreamHandler streamHandler)
From source file:com.github.zeroxff.executor.ExtendedExecutor.java
public ExecuteResult execute() throws ExtendedExecuteException { this.clearOut(); if (this.commandLine == null) { throw new ExtendedExecuteException("CommandLine cannot be null", Executor.INVALID_EXITVALUE); }/*from ww w . j a va 2 s. com*/ if (this.commandLine.length == 0) { throw new ExtendedExecuteException("CommandLine cannot be empty", Executor.INVALID_EXITVALUE); } if (this.maxExecutiontime != ExecuteWatchdog.INFINITE_TIMEOUT && this.maxExecutiontime < 1) { throw new ExtendedExecuteException("Max execution time must not be less than 1", Executor.INVALID_EXITVALUE); } try { // load the command line as an array of strings CommandLine cmdLine = new CommandLine(this.commandLine[0]); for (int counter = 1; counter < commandLine.length; counter++) { cmdLine.addArgument(this.commandLine[counter], quoteCommandlineArgs); } // load the substitution map, if defined if (this.substitutionMap != null) { cmdLine.setSubstitutionMap(this.substitutionMap); } // load the watchdog timer, it can be set to infinite time ExecuteWatchdog watchdog = new ExecuteWatchdog(this.maxExecutiontime); ExtendedResultHandler resultHandler = new ExtendedResultHandler(watchdog); // inizialize outputstream processors. OutStreamProcessor outLinee = null; OutStreamProcessor errLinee = null; PumpStreamHandler streamHandler = null; if (outputFilter != null && outputFilter.size() > 0) { outLinee = new OutStreamProcessor(outputFilter); } else { outLinee = new OutStreamProcessor(); } if (this.enableAllLinesOut) { outLinee.enableAllLines(); } if (mergeOutStreams) { // Using Std out for the output/error stream streamHandler = new PumpStreamHandler(outLinee); } else { if (errorFilter != null && errorFilter.size() > 0) { errLinee = new OutStreamProcessor(errorFilter); } else { errLinee = new OutStreamProcessor(); } if (enableAllLinesErr) { errLinee.enableAllLines(); } // Using Std out for the output/error stream streamHandler = new PumpStreamHandler(outLinee, errLinee); } DefaultExecutor executor = new DefaultExecutor(); // set the working directory... // if the working directory doesn't exists, it can crash the // executor. if (workingDirecory != null) { executor.setWorkingDirectory(workingDirecory); } // set the accepted exit values for the command line // default is '0'. if (okExitValues != null && okExitValues.length > 0) { executor.setExitValues(okExitValues); } executor.setWatchdog(watchdog); executor.setStreamHandler(streamHandler); try { executor.execute(cmdLine, resultHandler); resultHandler.waitFor(); returnCode = resultHandler.getExitValue(); exitMode = resultHandler.getExitMode(); switch (exitMode) { case ERROR_IN_EXECUTION: this.message = resultHandler.getException().getMessage(); break; default: break; } } catch (ExecuteException e) { exitMode = ExecuteResult.EXCEPTION; exception = e; this.message = e.getMessage(); } catch (IOException e) { exitMode = ExecuteResult.EXCEPTION; exception = e; this.message = e.getMessage(); } catch (InterruptedException e) { exitMode = ExecuteResult.EXCEPTION; exception = e; this.message = e.getMessage(); } // if (outLinee != null) { outputLines = outLinee.getLines(); allOutputLines = outLinee.getAllLines(); } if (errLinee != null) { errorLines = errLinee.getLines(); allErrorLines = errLinee.getAllLines(); } this.closeStreams(outLinee, errLinee); } catch (Exception e) { throw new ExtendedExecuteException(e.getMessage(), Executor.INVALID_EXITVALUE, e); } return exitMode; }
From source file:com.tibco.tgdb.test.lib.TGServer.java
/** * <pre>//from w w w . j a va 2 s . c o m * Kill the TG server. * - taskkill on Windows. * - kill -9 on Unix. * </pre> * * @throws Exception * Kill operation fails */ public void kill() throws Exception { if (this.pid == 0) throw new TGGeneralException( "TG server does not have a PID - Probably due to a previous start-up failure"); ByteArrayOutputStream output = new ByteArrayOutputStream(); PumpStreamHandler psh = new PumpStreamHandler(output); DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(psh); CommandLine cmdLine; if (OS.isFamilyWindows()) cmdLine = CommandLine.parse("taskkill /f /pid " + this.getPid() + " /t"); else cmdLine = CommandLine.parse("kill -9 " + this.getPid() + ""); try { executor.execute(cmdLine); } catch (ExecuteException ee) { // System.out.println("TGServer with pid " + this.getPid() + " not killed :"); // System.out.println("\t- " + output.toString().trim().replace("\n","\n\t- ")); throw new ExecuteException(output.toString().trim(), 1); // re-throw with better message } System.out.println("TGServer - Server with pid " + this.getPid() + " successfully killed :"); if (!output.toString().equals("")) System.out.println("\t\t- " + output.toString().trim().replace("\n", "\n\t\t- ")); this.running = false; this.pid = 0; }
From source file:com.walmart.gatling.commons.ScriptExecutor.java
private Object runJob(Object message) { Master.Job job = (Master.Job) message; TaskEvent taskEvent = (TaskEvent) job.taskEvent; CommandLine cmdLine = new CommandLine(agentConfig.getJob().getCommand()); log.info("Verified Script worker received task: {}", message); Map<String, Object> map = new HashMap<>(); if (StringUtils.isNotEmpty(agentConfig.getJob().getMainClass())) cmdLine.addArgument(agentConfig.getJob().getCpOrJar()); map.put("path", new File(agentConfig.getJob().getJobArtifact(taskEvent.getJobName()))); cmdLine.addArgument("${path}"); if (!StringUtils.isEmpty(agentConfig.getJob().getMainClass())) { cmdLine.addArgument(agentConfig.getJob().getMainClass()); }/*ww w. ja v a 2s . c om*/ //parameters come from the task event for (Pair<String, String> pair : taskEvent.getParameters()) { cmdLine.addArgument(pair.getValue()); } cmdLine.addArgument("-rf").addArgument(agentConfig.getJob().getResultPath(job.roleId, job.jobId)); cmdLine.setSubstitutionMap(map); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValues(agentConfig.getJob().getExitValues()); ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT); executor.setWatchdog(watchdog); executor.setWorkingDirectory(new File(agentConfig.getJob().getPath())); FileOutputStream outFile = null; FileOutputStream errorFile = null; String outPath = "", errPath = ""; try { outPath = agentConfig.getJob().getOutPath(taskEvent.getJobName(), job.jobId); errPath = agentConfig.getJob().getErrorPath(taskEvent.getJobName(), job.jobId); //create the std and err files outFile = FileUtils.openOutputStream(new File(outPath)); errorFile = FileUtils.openOutputStream(new File(errPath)); PumpStreamHandler psh = new PumpStreamHandler(new ExecLogHandler(outFile), new ExecLogHandler(errorFile)); executor.setStreamHandler(psh); log.info("command: {}", cmdLine); int exitResult = executor.execute(cmdLine); //executor.getWatchdog().destroyProcess(). Worker.Result result = new Worker.Result(exitResult, agentConfig.getUrl(errPath), agentConfig.getUrl(outPath), null, job); log.info("Exit code: {}", exitResult); if (executor.isFailure(exitResult) || exitResult == 1) { log.info("Script Executor Failed, job: " + job.jobId); //getSender().tell(new Worker.WorkFailed(result), getSelf()); return new Worker.WorkFailed(result); } else { result = new Worker.Result(exitResult, agentConfig.getUrl(errPath), agentConfig.getUrl(outPath), agentConfig.getUrl(getMetricsPath(job)), job); log.info("Script Executor Completed, job: " + result); //getSender().tell(new Worker.WorkComplete(result), getSelf()); return new Worker.WorkComplete(result); } } catch (IOException e) { log.error(e.toString()); Worker.Result result = new Worker.Result(-1, agentConfig.getUrl(errPath), agentConfig.getUrl(outPath), null, job); log.info("Executor Encountered run time exception, result: " + result.toString()); //getSender().tell(new Worker.WorkFailed(result), getSelf()); return new Worker.WorkFailed(result); } finally { IOUtils.closeQuietly(outFile); IOUtils.closeQuietly(errorFile); } }
From source file:it.drwolf.ridire.session.async.Mapper.java
private StringWithEncoding createPlainTextResource(File f, CrawledResource cr, EntityManager entityManager) throws SAXException, TikaException, IOException, TransformerConfigurationException, InterruptedException {// w ww . j av a2 s.com File resourceDir = new File(FilenameUtils.getFullPath(f.getCanonicalPath().replaceAll("__\\d+", "")) + JobMapperMonitor.RESOURCESDIR); String alchemyKey = entityManager.find(Parameter.class, Parameter.ALCHEMY_KEY.getKey()).getValue(); String readabilityKey = entityManager.find(Parameter.class, Parameter.READABILITY_KEY.getKey()).getValue(); String resourceFileName = cr.getDigest() + ".gz"; File resourceFile = new File(resourceDir, resourceFileName); StringWithEncoding rawContentAndEncoding = null; String contentType = cr.getContentType(); // long t1 = System.currentTimeMillis(); if (contentType != null && contentType.contains("application/msword")) { rawContentAndEncoding = this.transformDOC2HTML(resourceFile, entityManager); } if (contentType != null && contentType.contains("application/rtf")) { rawContentAndEncoding = this.transformRTF2HTML(resourceFile, entityManager); } if (contentType != null && contentType.contains("text/plain")) { // txt -> html -> txt is for txt cleaning rawContentAndEncoding = this.transformTXT2HTML(resourceFile, entityManager); } if (contentType != null && contentType.contains("pdf")) { rawContentAndEncoding = this.transformPDF2HTML(resourceFile, entityManager); } if (contentType != null && contentType.contains("html")) { rawContentAndEncoding = this.getGuessedEncodingAndSetRawContentFromGZFile(resourceFile); } // long t2 = System.currentTimeMillis(); // System.out.println("Transformation: " + (t2 - t1)); if (rawContentAndEncoding != null) { if (rawContentAndEncoding.getEncoding() == null) { rawContentAndEncoding = new StringWithEncoding(rawContentAndEncoding.getString(), "UTF8"); } // t1 = System.currentTimeMillis(); String cleanText = this.replaceUnsupportedChars(rawContentAndEncoding.getString()); rawContentAndEncoding = new StringWithEncoding(cleanText, rawContentAndEncoding.getEncoding()); File tmpFile = File.createTempFile("ridire", null); FileUtils.writeStringToFile(tmpFile, rawContentAndEncoding.getString(), "UTF-8"); String ridireCleanerJar = entityManager .find(CommandParameter.class, CommandParameter.RIDIRE_CLEANER_EXECUTABLE_KEY).getCommandValue(); String host = entityManager.find(Parameter.class, Parameter.READABILITY_HOSTAPP.getKey()).getValue(); CommandLine commandLine = CommandLine .parse("java -Xmx128m -Djava.io.tmpdir=" + this.tempDir + " -jar " + ridireCleanerJar); commandLine.addArgument("-f"); commandLine.addArgument(tmpFile.getPath()); commandLine.addArgument("-e"); commandLine.addArgument("UTF-8"); commandLine.addArgument("-h"); commandLine.addArgument(host); commandLine.addArgument("-k"); commandLine.addArgument(alchemyKey); commandLine.addArgument("-r"); commandLine.addArgument(readabilityKey); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0); ExecuteWatchdog watchdog = new ExecuteWatchdog(Mapper.READABILITY_TIMEOUT); executor.setWatchdog(watchdog); ByteArrayOutputStream baosStdOut = new ByteArrayOutputStream(1024); ByteArrayOutputStream baosStdErr = new ByteArrayOutputStream(1024); ExecuteStreamHandler executeStreamHandler = new PumpStreamHandler(baosStdOut, baosStdErr, null); executor.setStreamHandler(executeStreamHandler); int exitValue = executor.execute(commandLine); if (exitValue == 0) { rawContentAndEncoding = new StringWithEncoding(baosStdOut.toString(), "UTF-8"); // TODO filter real errors rawContentAndEncoding.setCleaner(baosStdErr.toString().trim()); } FileUtils.deleteQuietly(tmpFile); } return rawContentAndEncoding; }
From source file:fr.fastconnect.factory.tibco.bw.maven.AbstractBWMojo.java
/** * This calls a TIBCO binary.//from w w w.ja va 2s .com * * @param binary, the TIBCO binary file to execute * @param tras, the TRA files associated with the TIBCO binary * @param arguments, command-line arguments * @param workingDir, working directory from where the binary is launched * @param errorMsg, error message to display in case of a failure * @param fork, if true the chiild process will be detached from the caller * * @throws IOException * @throws MojoExecutionException */ protected int launchTIBCOBinary(File binary, List<File> tras, ArrayList<String> arguments, File workingDir, String errorMsg, boolean fork, boolean synchronous) throws IOException, MojoExecutionException { Integer result = 0; if (tras == null) { // no value specified as Mojo parameter, we use the .tra in the same directory as the binary String traPathFileName = binary.getAbsolutePath(); traPathFileName = FilenameUtils.removeExtension(traPathFileName); traPathFileName += ".tra"; tras = new ArrayList<File>(); tras.add(new File(traPathFileName)); } HashMap<File, File> trasMap = new HashMap<File, File>(); for (File tra : tras) { // copy of ".tra" file in the working directory File tmpTRAFile = new File(directory, tra.getName()); trasMap.put(tra, tmpTRAFile); copyFile(tra, tmpTRAFile); } for (File tra : trasMap.keySet()) { if (trasMap.containsKey(tibcoDesignerTRAPath) && ((tibcoBuildEARUseDesignerTRA && tra == tibcoBuildEARTRAPath) || (tibcoBuildLibraryUseDesignerTRA && tra == tibcoBuildLibraryTRAPath))) { if (tras.size() > 1) { ReplaceRegExp replaceRegExp = new ReplaceRegExp(); replaceRegExp.setFile(trasMap.get(tra)); replaceRegExp.setMatch("tibco.include.tra (.*/designer.tra)"); replaceRegExp.setReplace( "tibco.include.tra " + trasMap.get(tibcoDesignerTRAPath).toString().replace('\\', '/')); replaceRegExp.setByLine(true); replaceRegExp.execute(); } } if (tra == tibcoBuildEARTRAPath || tra == tibcoDesignerTRAPath || tra == tibcoBWEngineTRAPath) { // FIXME: should check more properly // append user.home at the end to force the use of custom Designer5.prefs PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(trasMap.get(tra), true))); out.println(""); out.println("java.property.user.home=" + directory.getAbsolutePath().replace("\\", "/")); out.close(); } } CommandLine cmdLine = new CommandLine(binary); for (String argument : arguments) { cmdLine.addArgument(argument); } getLog().debug("launchTIBCOBinary command line : " + cmdLine.toString()); getLog().debug("working dir : " + workingDir); DefaultExecutor executor = new DefaultExecutor(); executor.setWorkingDirectory(workingDir); if (timeOut > 0) { ExecuteWatchdog watchdog = new ExecuteWatchdog(timeOut * 1000); executor.setWatchdog(watchdog); } executor.setProcessDestroyer(new ShutdownHookProcessDestroyer()); ByteArrayOutputStream stdOutAndErr = new ByteArrayOutputStream(); executor.setStreamHandler(new PumpStreamHandler(stdOutAndErr)); if (fork) { CommandLauncher commandLauncher = CommandLauncherFactory.createVMLauncher(); commandLauncher.exec(cmdLine, null, workingDir); } else { try { if (synchronous) { result = executor.execute(cmdLine); } else { executor.execute(cmdLine, new DefaultExecuteResultHandler()); } } catch (ExecuteException e) { // TODO : grer erreurs des excutables (ventuellement parser les erreurs classiques) getLog().info(cmdLine.toString()); getLog().info(stdOutAndErr.toString()); getLog().info(result.toString()); throw new MojoExecutionException(errorMsg, e); } catch (IOException e) { throw new MojoExecutionException(e.getMessage(), e); } } return result; }
From source file:com.cws.esolutions.agent.processors.impl.ServiceCheckProcessorImpl.java
public ServiceCheckResponse runSystemCheck(final ServiceCheckRequest request) throws ServiceCheckException { final String methodName = IServiceCheckProcessor.CNAME + "#runSystemCheck(final ServiceCheckRequest request) throws ServiceCheckException"; if (DEBUG) {//from ww w .j a v a 2s. co m DEBUGGER.debug(methodName); DEBUGGER.debug("ServiceCheckRequest: {}", request); } int exitCode = -1; Socket socket = null; File sourceFile = null; CommandLine command = null; BufferedWriter writer = null; ExecuteStreamHandler streamHandler = null; ByteArrayOutputStream outputStream = null; ServiceCheckResponse response = new ServiceCheckResponse(); final DefaultExecutor executor = new DefaultExecutor(); final ExecuteWatchdog watchdog = new ExecuteWatchdog(CONNECT_TIMEOUT * 1000); final DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); try { switch (request.getRequestType()) { case NETSTAT: sourceFile = scriptConfig.getScripts().get("netstat"); if (DEBUG) { DEBUGGER.debug("sourceFile: {}", sourceFile); } if (!(sourceFile.canExecute())) { throw new ServiceCheckException( "Script file either does not exist or cannot be executed. Cannot continue."); } command = CommandLine.parse(sourceFile.getAbsolutePath()); if (request.getPortNumber() != 0) { command.addArgument(String.valueOf(request.getPortNumber()), true); } if (DEBUG) { DEBUGGER.debug("CommandLine: {}", command); } outputStream = new ByteArrayOutputStream(); streamHandler = new PumpStreamHandler(outputStream); executor.setWatchdog(watchdog); executor.setStreamHandler(streamHandler); if (DEBUG) { DEBUGGER.debug("ExecuteStreamHandler: {}", streamHandler); DEBUGGER.debug("ExecuteWatchdog: {}", watchdog); DEBUGGER.debug("DefaultExecuteResultHandler: {}", resultHandler); DEBUGGER.debug("DefaultExecutor: {}", executor); } executor.execute(command, resultHandler); resultHandler.waitFor(); exitCode = resultHandler.getExitValue(); if (DEBUG) { DEBUGGER.debug("exitCode: {}", exitCode); } writer = new BufferedWriter(new FileWriter(LOGS_DIRECTORY + "/" + sourceFile.getName() + ".log")); writer.write(outputStream.toString()); writer.flush(); response.setResponseData(outputStream.toString()); if (executor.isFailure(exitCode)) { response.setRequestStatus(AgentStatus.FAILURE); } else { response.setRequestStatus(AgentStatus.SUCCESS); } break; case REMOTEDATE: response.setRequestStatus(AgentStatus.SUCCESS); response.setResponseData(System.currentTimeMillis()); break; case TELNET: response = new ServiceCheckResponse(); int targetPort = request.getPortNumber(); String targetServer = request.getTargetHost(); if (DEBUG) { DEBUGGER.debug("Target port: {}", targetPort); DEBUGGER.debug("Target server: {}", targetServer); } if (targetPort == 0) { throw new ServiceCheckException("Target port number was not assigned. Cannot action request."); } final String CRLF = "\r\n"; final String TERMINATE_TELNET = "^]"; synchronized (new Object()) { InetSocketAddress socketAddress = new InetSocketAddress(targetServer, targetPort); socket = new Socket(); socket.setSoTimeout(IServiceCheckProcessor.CONNECT_TIMEOUT); socket.setSoLinger(false, 0); socket.setKeepAlive(false); try { socket.connect(socketAddress, IServiceCheckProcessor.CONNECT_TIMEOUT); if (!(socket.isConnected())) { throw new ConnectException("Failed to connect to host " + targetServer + " on port " + request.getPortNumber()); } PrintWriter pWriter = new PrintWriter(socket.getOutputStream(), true); pWriter.println(TERMINATE_TELNET + CRLF); pWriter.flush(); pWriter.close(); response.setRequestStatus(AgentStatus.SUCCESS); response.setResponseData("Telnet connection to " + targetServer + " on port " + request.getPortNumber() + " successful."); } catch (ConnectException cx) { response.setRequestStatus(AgentStatus.FAILURE); response.setResponseData("Telnet connection to " + targetServer + " on port " + request.getPortNumber() + " failed with message: " + cx.getMessage()); } } break; case PROCESSLIST: sourceFile = scriptConfig.getScripts().get("processList"); if (DEBUG) { DEBUGGER.debug("sourceFile: {}", sourceFile); } if (!(sourceFile.canExecute())) { throw new ServiceCheckException( "Script file either does not exist or cannot be executed. Cannot continue."); } command = CommandLine.parse(sourceFile.getAbsolutePath()); if (request.getPortNumber() != 0) { command.addArgument(String.valueOf(request.getPortNumber()), true); } if (DEBUG) { DEBUGGER.debug("CommandLine: {}", command); } outputStream = new ByteArrayOutputStream(); streamHandler = new PumpStreamHandler(outputStream); executor.setWatchdog(watchdog); executor.setStreamHandler(streamHandler); if (DEBUG) { DEBUGGER.debug("ExecuteStreamHandler: {}", streamHandler); DEBUGGER.debug("ExecuteWatchdog: {}", watchdog); DEBUGGER.debug("DefaultExecuteResultHandler: {}", resultHandler); DEBUGGER.debug("DefaultExecutor: {}", executor); } executor.execute(command, resultHandler); resultHandler.waitFor(); exitCode = resultHandler.getExitValue(); if (DEBUG) { DEBUGGER.debug("exitCode: {}", exitCode); } writer = new BufferedWriter(new FileWriter(LOGS_DIRECTORY + "/" + sourceFile.getName() + ".log")); writer.write(outputStream.toString()); writer.flush(); response.setResponseData(outputStream.toString()); if (executor.isFailure(exitCode)) { response.setRequestStatus(AgentStatus.FAILURE); } else { response.setRequestStatus(AgentStatus.SUCCESS); } break; default: // unknown operation throw new ServiceCheckException("No valid operation was specified"); } } catch (UnknownHostException uhx) { ERROR_RECORDER.error(uhx.getMessage(), uhx); throw new ServiceCheckException(uhx.getMessage(), uhx); } catch (SocketException sx) { ERROR_RECORDER.error(sx.getMessage(), sx); throw new ServiceCheckException(sx.getMessage(), sx); } catch (IOException iox) { ERROR_RECORDER.error(iox.getMessage(), iox); throw new ServiceCheckException(iox.getMessage(), iox); } catch (InterruptedException ix) { ERROR_RECORDER.error(ix.getMessage(), ix); throw new ServiceCheckException(ix.getMessage(), ix); } finally { try { if (writer != null) { writer.close(); } if ((socket != null) && (!(socket.isClosed()))) { socket.close(); } } catch (IOException iox) { ERROR_RECORDER.error(iox.getMessage(), iox); } } return response; }
From source file:com.walmart.gatling.commons.ReportExecutor.java
private void runJob(Master.GenerateReport job) { TaskEvent taskEvent = job.reportJob.taskEvent; CommandLine cmdLine = new CommandLine(agentConfig.getJob().getCommand()); Map<String, Object> map = new HashMap<>(); map.put("path", new File(agentConfig.getJob().getJobArtifact(taskEvent.getJobName()))); cmdLine.addArgument("${path}"); //parameters come from the task event for (Pair<String, String> pair : taskEvent.getParameters()) { cmdLine.addArgument(pair.getValue()); }// w w w . ja v a 2 s. c om String dir = agentConfig.getJob().getLogDirectory() + "reports/" + job.reportJob.trackingId + "/"; cmdLine.addArgument(dir); cmdLine.setSubstitutionMap(map); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValues(agentConfig.getJob().getExitValues()); ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT); executor.setWatchdog(watchdog); executor.setWorkingDirectory(new File(agentConfig.getJob().getPath())); FileOutputStream outFile = null; FileOutputStream errorFile = null; try { List<String> resultFiles = new ArrayList<>(job.results.size()); //download all files adn /*int i=0; for (Worker.Result result : job.results) { String destFile = dir + i++ + ".log"; resultFiles.add(destFile); DownloadFile.downloadFile(result.metrics,destFile); }*/ AtomicInteger index = new AtomicInteger(); job.results.parallelStream().forEach(result -> { String destFile = dir + index.incrementAndGet() + ".log"; resultFiles.add(destFile); DownloadFile.downloadFile(result.metrics, destFile); }); String outPath = agentConfig.getJob().getOutPath(taskEvent.getJobName(), job.reportJob.trackingId); String errPath = agentConfig.getJob().getErrorPath(taskEvent.getJobName(), job.reportJob.trackingId); //create the std and err files outFile = FileUtils.openOutputStream(new File(outPath)); errorFile = FileUtils.openOutputStream(new File(errPath)); PumpStreamHandler psh = new PumpStreamHandler(new ExecLogHandler(outFile), new ExecLogHandler(errorFile)); executor.setStreamHandler(psh); System.out.println(cmdLine); int exitResult = executor.execute(cmdLine); ReportResult result; if (executor.isFailure(exitResult)) { result = new ReportResult(dir, job.reportJob, false); log.info("Report Executor Failed, result: " + job.toString()); } else { result = new ReportResult(job.reportJob.getHtml(), job.reportJob, true); log.info("Report Executor Completed, result: " + result.toString()); } for (String resultFile : resultFiles) { FileUtils.deleteQuietly(new File(resultFile)); } getSender().tell(result, getSelf()); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } finally { IOUtils.closeQuietly(outFile); IOUtils.closeQuietly(errorFile); } }
From source file:com.cws.esolutions.agent.processors.impl.ApplicationManagerProcessorImpl.java
/** * @see com.cws.esolutions.agent.processors.interfaces.IApplicationManagerProcessor#installApplication(com.cws.esolutions.agent.processors.dto.ApplicationManagerRequest) */// w ww. ja v a 2 s . c om public ApplicationManagerResponse installApplication(final ApplicationManagerRequest request) throws ApplicationManagerException { final String methodName = IApplicationManagerProcessor.CNAME + "#installApplication(final ApplicationManagerRequest request) throws ApplicationManagerException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("ApplicationManagerRequest: {}", request); } BufferedWriter writer = null; ApplicationManagerResponse response = new ApplicationManagerResponse(); final double version = request.getVersion(); final DefaultExecutor executor = new DefaultExecutor(); final String installerOptions = request.getInstallerOptions(); final File installPath = FileUtils.getFile(request.getInstallPath()); final ExecuteWatchdog watchdog = new ExecuteWatchdog(CONNECT_TIMEOUT * 1000); final DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); final File packageInstaller = FileUtils.getFile(request.getPackageInstaller()); if (DEBUG) { DEBUGGER.debug("double: {}", version); DEBUGGER.debug("DefaultExecutor: {}", executor); DEBUGGER.debug("String: {}", installerOptions); DEBUGGER.debug("File: {}", installPath); DEBUGGER.debug("ExecuteWatchdog: {}", watchdog); DEBUGGER.debug("DefaultExecuteResultHandler: {}", resultHandler); DEBUGGER.debug("File:{}", packageInstaller); } try { if (!(packageInstaller.canExecute())) { throw new ApplicationManagerException("Unable to execute package installer. Cannot continue."); } if (!(installPath.canWrite()) && (!(installPath.mkdirs()))) { throw new ApplicationManagerException("Unable to create installation target. Cannot continue."); } CommandLine command = CommandLine.parse(packageInstaller.getAbsolutePath()); command.addArgument(installerOptions, false); command.addArgument(request.getPackageLocation(), false); if (DEBUG) { DEBUGGER.debug("CommandLine: {}", command); } ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ExecuteStreamHandler streamHandler = new PumpStreamHandler(outputStream); streamHandler.start(); executor.setWatchdog(watchdog); executor.setStreamHandler(streamHandler); if (DEBUG) { DEBUGGER.debug("ExecuteStreamHandler: {}", streamHandler); DEBUGGER.debug("ExecuteWatchdog: {}", watchdog); DEBUGGER.debug("DefaultExecuteResultHandler: {}", resultHandler); DEBUGGER.debug("DefaultExecutor: {}", executor); } executor.execute(command, resultHandler); resultHandler.waitFor(); int exitCode = resultHandler.getExitValue(); writer = new BufferedWriter(new FileWriter(LOGS_DIRECTORY + "/" + request.getPackageName() + ".log")); writer.write(outputStream.toString()); writer.flush(); if (DEBUG) { DEBUGGER.debug("exitCode: {}", exitCode); } if (executor.isFailure(exitCode)) { throw new ApplicationManagerException("Application installation failed: Result Code: " + exitCode); } response.setResponse(outputStream.toString()); response.setRequestStatus(AgentStatus.SUCCESS); } catch (ExecuteException eex) { ERROR_RECORDER.error(eex.getMessage(), eex); throw new ApplicationManagerException(eex.getMessage(), eex); } catch (IOException iox) { ERROR_RECORDER.error(iox.getMessage(), iox); throw new ApplicationManagerException(iox.getMessage(), iox); } catch (InterruptedException ix) { ERROR_RECORDER.error(ix.getMessage(), ix); throw new ApplicationManagerException(ix.getMessage(), ix); } finally { try { writer.close(); } catch (IOException iox) { ERROR_RECORDER.error(iox.getMessage(), iox); } } return response; }
From source file:it.drwolf.ridire.session.async.Mapper.java
@SuppressWarnings("unchecked") private StringWithEncoding transformPDF2HTML(File resourceFile, EntityManager entityManager) throws IOException, InterruptedException { String workingDirName = System.getProperty("java.io.tmpdir"); String userDir = System.getProperty("user.dir"); byte[] buf = new byte[Mapper.BUFLENGTH]; int count = 0; GZIPInputStream gzis = new GZIPInputStream(new FileInputStream(resourceFile)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); while ((count = gzis.read(buf)) != -1) { baos.write(buf, 0, count);// w ww .j a v a 2 s.c o m } gzis.close(); baos.close(); byte[] byteArray = baos.toByteArray(); String uuid = UUID.randomUUID().toString(); String pdfFileName = uuid + ".pdf"; String htmlFileName = uuid + ".html"; File tmpDir = new File(workingDirName); String htmlFileNameCompletePath = workingDirName + JobMapperMonitor.FILE_SEPARATOR + htmlFileName; File fileToConvert = new File(tmpDir, pdfFileName); FileUtils.writeByteArrayToFile(fileToConvert, byteArray); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0); CommandParameter cp = entityManager.find(CommandParameter.class, CommandParameter.PDFTOHTML_EXECUTABLE_KEY); CommandLine commandLine = CommandLine.parse(cp.getCommandValue()); commandLine.addArgument("-c"); commandLine.addArgument("-i"); commandLine.addArgument(fileToConvert.getAbsolutePath()); commandLine.addArgument(htmlFileNameCompletePath); executor.setExitValue(0); executor.execute(commandLine); try { FileUtils.moveFileToDirectory( new File(userDir + JobMapperMonitor.FILE_SEPARATOR + uuid + "-outline.html"), tmpDir, false); } catch (IOException e) { } cp = entityManager.find(CommandParameter.class, CommandParameter.PDFCLEANER_EXECUTABLE_KEY); commandLine = CommandLine .parse("java -Xmx128m -jar -Djava.io.tmpdir=" + this.tempDir + " " + cp.getCommandValue()); commandLine.addArgument(htmlFileNameCompletePath); commandLine.addArgument("39"); commandLine.addArgument("6"); commandLine.addArgument("5"); executor = new DefaultExecutor(); executor.setExitValue(0); ExecuteWatchdog watchdog = new ExecuteWatchdog(Mapper.PDFCLEANER_TIMEOUT); executor.setWatchdog(watchdog); ByteArrayOutputStream baosStdOut = new ByteArrayOutputStream(1024); ExecuteStreamHandler executeStreamHandler = new PumpStreamHandler(baosStdOut, null, null); executor.setStreamHandler(executeStreamHandler); int exitValue = executor.execute(commandLine); String htmlString = null; if (exitValue == 0) { htmlString = baosStdOut.toString(); } FileUtils.deleteQuietly(new File(htmlFileNameCompletePath)); PrefixFileFilter pff = new PrefixFileFilter(uuid); for (File f : FileUtils.listFiles(tmpDir, pff, null)) { FileUtils.deleteQuietly(f); } if (htmlString != null) { htmlString = htmlString.replaceAll(" ", " "); htmlString = htmlString.replaceAll("<br.*?>", " "); CharsetDetector charsetDetector = new CharsetDetector(); charsetDetector.setText(htmlString.getBytes()); String encoding = charsetDetector.detect().getName(); return new StringWithEncoding(htmlString, encoding); } return null; }
From source file:net.sourceforge.seqware.pipeline.plugins.ITUtility.java
/** * Run an arbitrary command and check it against an expected return value * * @param line/*from w w w .j av a 2s. c o m*/ * @param expectedReturnValue * @param dir working directory, can be null if you don't want to change directories * @return * @throws IOException */ public static String runArbitraryCommand(String line, int expectedReturnValue, File dir) throws IOException { Log.info("Running " + line); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); CommandLine commandline = CommandLine.parse(line); DefaultExecutor exec = new DefaultExecutor(); if (dir != null) { exec.setWorkingDirectory(dir); } PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); exec.setStreamHandler(streamHandler); exec.setExitValue(expectedReturnValue); try { int exitValue = exec.execute(commandline); Assert.assertTrue( "exit value for full jar with no params should be " + expectedReturnValue + " was " + exitValue, exitValue == expectedReturnValue); String output = outputStream.toString(); return output; } catch (ExecuteException e) { Log.error("Execution failed with:"); Log.error(outputStream.toString()); throw e; } }