List of usage examples for org.apache.commons.exec DefaultExecutor setWatchdog
public void setWatchdog(final ExecuteWatchdog watchDog)
From source file:com.jaeksoft.searchlib.ocr.OcrManager.java
private final int run(CommandLine cmdLine, int secTimeOut, Integer expectedExitValue, StringBuilder returnedText) throws IOException, SearchLibException { DefaultExecutor executor = new DefaultExecutor(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try {/* w ww .j av a 2 s. co m*/ Logging.info("LOG OCR: " + cmdLine); PumpStreamHandler streamHandler = new PumpStreamHandler(baos); executor.setStreamHandler(streamHandler); if (expectedExitValue != null) executor.setExitValue(expectedExitValue); ExecuteWatchdog watchdog = new ExecuteWatchdog(secTimeOut * 1000); executor.setWatchdog(watchdog); int ev = executor.execute(cmdLine); if (expectedExitValue != null) if (ev != expectedExitValue) throw new SearchLibException("Bad exit value (" + ev + ") "); if (returnedText != null) returnedText.append(baos.toString("UTF-8")); return ev; } finally { if (baos != null) IOUtils.closeQuietly(baos); } }
From source file:com.k42b3.sacmis.Sacmis.java
private void executeCommand() { out.setText(""); try {//from w w w .j a v a 2s . c om // save file saveFile(); CommandLine commandLine = CommandLine.parse(this.path + " " + this.args.getText()); // set timeout ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout); // create executor DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(this.exitCode); this.baos = new ByteArrayOutputStream(); this.baosErr = new ByteArrayOutputStream(); if (this.writerStdIn) { this.bais = new ByteArrayInputStream(in.getText().getBytes()); executor.setStreamHandler(new PumpStreamHandler(this.baos, this.baosErr, this.bais)); } else { executor.setStreamHandler(new PumpStreamHandler(this.baos, this.baosErr)); } executor.setWatchdog(watchdog); executor.execute(commandLine, new ExecuteResultHandler() { public void onProcessComplete(int e) { out.setText(baos.toString()); } public void onProcessFailed(ExecuteException e) { out.setText(baosErr.toString()); } }); } catch (Exception e) { out.setText(e.getMessage()); } }
From source file:com.jredrain.startup.AgentProcessor.java
@Override public Response execute(final Request request) throws TException { if (!this.password.equalsIgnoreCase(request.getPassword())) { return errorPasswordResponse(request); }/* w w w . ja v a2 s . c o m*/ String command = request.getParams().get("command") + EXITCODE_SCRIPT; String pid = request.getParams().get("pid"); //?? Long timeout = CommonUtils.toLong(request.getParams().get("timeout"), 0L); boolean timeoutFlag = timeout > 0; logger.info("[redrain]:execute:{},pid:{}", command, pid); File shellFile = CommandUtils.createShellFile(command, pid); Integer exitValue; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final Response response = Response.response(request); final ExecuteWatchdog watchdog = new ExecuteWatchdog(Integer.MAX_VALUE); final Timer timer = new Timer(); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); try { CommandLine commandLine = CommandLine.parse("/bin/bash +x " + shellFile.getAbsolutePath()); final DefaultExecutor executor = new DefaultExecutor(); ExecuteStreamHandler stream = new PumpStreamHandler(outputStream, outputStream); executor.setStreamHandler(stream); response.setStartTime(new Date().getTime()); //?0,shell executor.setExitValue(0); if (timeoutFlag) { //... executor.setWatchdog(watchdog); // timer.schedule(new TimerTask() { @Override public void run() { //,kill... if (watchdog.isWatching()) { /** * watchdogdestroyProcesskill... * watchdog.destroyProcess(); */ timer.cancel(); watchdog.stop(); //call kill... request.setAction(Action.KILL); try { kill(request); response.setExitCode(RedRain.StatusCode.TIME_OUT.getValue()); } catch (TException e) { e.printStackTrace(); } } } }, timeout * 60 * 1000); // resultHandler = new DefaultExecuteResultHandler() { @Override public void onProcessComplete(int exitValue) { super.onProcessComplete(exitValue); timer.cancel(); } @Override public void onProcessFailed(ExecuteException e) { super.onProcessFailed(e); timer.cancel(); } }; } executor.execute(commandLine, resultHandler); resultHandler.waitFor(); } catch (Exception e) { if (e instanceof ExecuteException) { exitValue = ((ExecuteException) e).getExitValue(); } else { exitValue = RedRain.StatusCode.ERROR_EXEC.getValue(); } if (RedRain.StatusCode.KILL.getValue().equals(exitValue)) { if (timeoutFlag) { timer.cancel(); watchdog.stop(); } logger.info("[redrain]:job has be killed!at pid :{}", request.getParams().get("pid")); } else { logger.info("[redrain]:job execute error:{}", e.getCause().getMessage()); } } finally { exitValue = resultHandler.getExitValue(); if (CommonUtils.notEmpty(outputStream.toByteArray())) { try { outputStream.flush(); String text = outputStream.toString(); if (notEmpty(text)) { try { text = text.replaceAll(String.format(REPLACE_REX, shellFile.getAbsolutePath()), ""); response.setMessage(text.substring(0, text.lastIndexOf(EXITCODE_KEY))); exitValue = Integer.parseInt(text .substring(text.lastIndexOf(EXITCODE_KEY) + EXITCODE_KEY.length() + 1).trim()); } catch (IndexOutOfBoundsException e) { response.setMessage(text); } } outputStream.close(); } catch (Exception e) { logger.error("[redrain]:error:{}", e); } } if (RedRain.StatusCode.TIME_OUT.getValue() == response.getExitCode()) { response.setSuccess(false).end(); } else { response.setExitCode(exitValue) .setSuccess(response.getExitCode() == RedRain.StatusCode.SUCCESS_EXIT.getValue()).end(); } if (shellFile != null) { shellFile.delete();// } } logger.info("[redrain]:execute result:{}", response.toString()); watchdog.stop(); return response; }
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 w w w .ja va2 s . co m 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:io.selendroid.android.impl.AbstractDevice.java
private void startLogging() { logoutput = new ByteArrayOutputStream(); DefaultExecutor exec = new DefaultExecutor(); exec.setStreamHandler(new PumpStreamHandler(logoutput)); CommandLine command = adbCommand("logcat", "ResourceType:S", "dalvikvm:S", "Trace:S", "SurfaceFlinger:S", "StrictMode:S", "ExchangeService:S", "SVGAndroid:S", "skia:S", "LoaderManager:S", "ActivityThread:S", "-v", "time"); log.info("starting logcat:"); log.fine(command.toString());/*from w ww . j av a 2 s.c o m*/ try { exec.execute(command, new DefaultExecuteResultHandler()); logcatWatchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT); exec.setWatchdog(logcatWatchdog); } catch (IOException e) { e.printStackTrace(); } }
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 w w . j a va2 s.c om*/ 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:io.selendroid.standalone.android.impl.AbstractDevice.java
private void startLogging() { logoutput = new ByteArrayOutputStream(); DefaultExecutor exec = new DefaultExecutor(); exec.setStreamHandler(new PumpStreamHandler(logoutput)); CommandLine command = adbCommand("logcat", "ResourceType:S", "dalvikvm:S", "Trace:S", "SurfaceFlinger:S", "StrictMode:S", "ExchangeService:S", "SVGAndroid:S", "skia:S", "LoaderManager:S", "ActivityThread:S", "-v", "time"); log.info("starting logcat:"); log.fine(command.toString());/*from w ww.j a v a2 s . c om*/ try { exec.execute(command, new DefaultExecuteResultHandler()); logcatWatchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT); exec.setWatchdog(logcatWatchdog); } catch (IOException e) { log.log(Level.SEVERE, e.getMessage(), e); } }
From source file:fr.fastconnect.factory.tibco.bw.maven.AbstractBWMojo.java
/** * This calls a TIBCO binary./*from w w w . j av a 2 s.c o m*/ * * @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 www.ja v a 2 s . c o 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.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 a2 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; }