List of usage examples for org.apache.commons.exec DefaultExecuteResultHandler getExitValue
public int getExitValue()
From source file:info.pancancer.arch3.worker.WorkflowRunner.java
@Override public WorkflowResult call() throws IOException { PumpStreamHandler streamHandler = new PumpStreamHandler(this.outputStream, this.errorStream); WorkflowResult result = new WorkflowResult(); DefaultExecutor executor = new DefaultExecutor(); /*//from ww w . j a va2 s .c om * CommandLine cli = new CommandLine("docker"); cli.addArguments(new String[] { "run", "--rm", "-h", "master", "-t" ,"-v", * "/var/run/docker.sock:/var/run/docker.sock", "-v", job.getWorkflowPath() + ":/workflow", "-v",pathToINI + ":/ini", "-v", * "/datastore:/datastore", "-v","/home/"+this.userName+"/.ssh/gnos.pem:/home/ubuntu/.ssh/gnos.pem", * "seqware/seqware_whitestar_pancancer", "seqware", "bundle", "launch", "--dir", "/workflow", "--ini", "/ini", "--no-metadata" }); */ LOG.info("Executing command: " + this.cli.toString().replace(",", "")); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); executor.setStreamHandler(streamHandler); try { if (this.preworkDelay > 0) { LOG.info("Sleeping before executing workflow for " + this.preworkDelay + " ms."); Thread.sleep(this.preworkDelay); } executor.execute(cli, resultHandler); // Use the result handler for non-blocking call, so this way we should be able to get updates of // stdout and stderr while the command is running. resultHandler.waitFor(); result.setWorkflowStdout(outputStream.getAllLinesAsString()); result.setWorkflowStdErr(errorStream.getAllLinesAsString()); LOG.debug("Exit code: " + resultHandler.getExitValue()); result.setExitCode(resultHandler.getExitValue()); if (this.postworkDelay > 0) { LOG.info("Sleeping after executing workflow for " + this.postworkDelay + " ms."); Thread.sleep(this.postworkDelay); } } catch (ExecuteException e) { LOG.error(e.getMessage(), e); result.setWorkflowStdout(this.getStdErr()); } catch (InterruptedException | IOException e) { LOG.error(e.getMessage(), e); result.setWorkflowStdout(this.getStdErr()); } finally { this.outputStream.close(); this.errorStream.close(); } LOG.debug("Workflowrunner exiting"); return result; }
From source file:de.simu.decomap.messaging.resultprocessor.impl.helper.RulesExecutor.java
/** * Executing a predefined Rule// w w w .j a v a 2 s. c o m * @param ruleType RuleType * @param arg args for Rule * @return Success */ public boolean executePredefinedRule(byte ruleType, String arg) { logger.info("[IPTABLES] -> executing predefined command..."); // use apache's commons-exec for executing command! CommandLine cmdLine = new CommandLine(command); // get the predefined rule-parameters String[] ruleParams = Rules.getPredefindedRuleParameters(ruleType, arg); if (ruleParams != null) { // add rule-parameters to CommanLine-Object for (int i = 0; i < ruleParams.length; i++) { cmdLine.addArgument(ruleParams[i]); } // execute command DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); ExecuteWatchdog watchdog = new ExecuteWatchdog(mTimeout); Executor executor = new DefaultExecutor(); executor.setExitValue(1); executor.setWatchdog(watchdog); try { executor.execute(cmdLine, resultHandler); } catch (ExecuteException e) { logger.warn("[IPTABLES] -> error while executing predefined command: execute-exception occured!"); return false; } catch (IOException e) { logger.warn("[IPTABLES] -> error while executing predefined command: io-exception occured!"); return false; } try { // some time later the result handler callback was invoked so we // can safely request the exit value resultHandler.waitFor(); int exitCode = resultHandler.getExitValue(); logger.info("[IPTABLES] -> command " + ruleType + " executed, exit-code is: " + exitCode); switch (exitCode) { case EXIT_CODE_SUCCESS: return true; case EXIT_CODE_ERROR: return false; default: return false; } } catch (InterruptedException e) { logger.warn( "[IPTABLES] -> error while executing predefined command: interrupted-exception occured!"); return false; } } else { logger.warn("[IPTABLES] -> error while excuting predefined command: rule-parameters-list is null!"); return false; } }
From source file:de.esukom.decoit.ifmapclient.iptables.RulesExecutor.java
public boolean executePredefinedRule(byte ruleType, String[] arg) { IfMapClient.LOGGER.info("[IPTABLES] -> executing predefined command..."); // use apache's commons-exec for executing command! CommandLine cmdLine = new CommandLine(command); // get the predefined rule-parameters String[] ruleParams = Rules.getPredefindedRuleParameters(ruleType, arg); if (ruleParams != null) { // add rule-parameters to CommanLine-Object for (int i = 0; i < ruleParams.length; i++) { cmdLine.addArgument(ruleParams[i]); }//from w w w . jav a2 s.c om // execute command DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); ExecuteWatchdog watchdog = new ExecuteWatchdog(mTimeout); Executor executor = new DefaultExecutor(); executor.setExitValue(1); executor.setWatchdog(watchdog); try { executor.execute(cmdLine, resultHandler); } catch (ExecuteException e) { IfMapClient.LOGGER.warning( "[IPTABLES] -> error while executing predefined command: execute-exception occured!"); return false; } catch (IOException e) { IfMapClient.LOGGER .warning("[IPTABLES] -> error while executing predefined command: io-exception occured!"); return false; } try { // some time later the result handler callback was invoked so we // can safely request the exit value resultHandler.waitFor(); int exitCode = resultHandler.getExitValue(); IfMapClient.LOGGER.warning("[IPTABLES] -> command executed, exit-code is: " + exitCode); switch (exitCode) { case EXIT_CODE_SUCCESS: return true; case EXIT_CODE_ERROR: return false; default: return false; } } catch (InterruptedException e) { IfMapClient.LOGGER.warning( "[IPTABLES] -> error while executing predefined command: interrupted-exception occured!"); return false; } } else { IfMapClient.LOGGER.warning( "[IPTABLES] -> error while excuting predefined command: rule-parameters-list is null!"); return false; } }
From source file:at.ac.tuwien.ims.latex2mobiformulaconv.converter.html2mobi.CalibreHtmlToMobiConverter.java
@Override public File convertToMobi(File htmlFile) { logger.debug("Enter convertToMobi()..."); if (htmlFile == null) { logger.error("Document is null, aborting..."); System.exit(1);//from w w w . java 2 s . co m } CommandLine cmdLine; if (execPath != null) { // Run the configured calibre ebook-convert executable logger.info("Calibre ebook-convert will be run from: " + execPath.toString()); cmdLine = new CommandLine(execPath.toFile()); } else { // Run in system PATH environment logger.info("Calibre ebook-convert will be run within the PATH variable."); cmdLine = new CommandLine(command); } // cli command: ebook-convert input_file.html output_file.mobi --mobi-file-type=new // Run configuration cmdLine.addArgument(Paths.get(htmlFile.toURI()).toAbsolutePath().toString()); String mobiFilename = htmlFile.getName().toString().replace(".html", ".mobi").toString(); Path tempMobiFilepath = Paths.get(htmlFile.toURI()).getParent().resolve(mobiFilename); logger.debug("Mobi output file: " + tempMobiFilepath.toAbsolutePath().toString()); cmdLine.addArgument(tempMobiFilepath.toAbsolutePath().toString()); // Output will be in format "KF8" only, old format does not allow external CSS files cmdLine.addArgument("--mobi-file-type=new"); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000); Executor executor = new DefaultExecutor(); executor.setExitValue(1); executor.setWatchdog(watchdog); StringWriter writer = new StringWriter(); WriterOutputStream writerOutputStream = new WriterOutputStream(writer, Charset.forName("UTF-8")); ExecuteStreamHandler calibreStreamHandler = new PumpStreamHandler(writerOutputStream, System.err); executor.setStreamHandler(calibreStreamHandler); logger.debug("Launching calibres ebook-convert:"); logger.debug(cmdLine.toString()); try { executor.execute(cmdLine, resultHandler); } catch (IOException e) { logger.error("calibres ebook-convert failed to execute:"); logger.error(e.getMessage(), e); System.exit(-1); } try { resultHandler.waitFor(); int exitValue = resultHandler.getExitValue(); logger.debug("calibre ebook-converts execution's exit value: " + exitValue); ExecuteException executeException = resultHandler.getException(); if (executeException != null && executeException.getCause() != null) { String exceptionKlass = executeException.getCause().getClass().getCanonicalName(); String exceptionMessage = executeException.getCause().getMessage(); if (exceptionKlass.endsWith("IOException") || exceptionMessage.contains("Cannot run program \"ebook-convert\"")) { logger.error("calibres ebook-convert could not be run! Exiting..."); logger.debug(executeException); System.exit(1); } logger.debug(exceptionKlass + ": " + exceptionMessage); } } catch (InterruptedException e) { logger.error("calibre ebook-converts execution got interrupted: "); logger.error(e.getMessage(), e); } String output = ""; try { output += writer.getBuffer().toString(); writer.close(); } catch (IOException e) { logger.error("Error reading calibre ebook-converts output from buffer:"); logger.error(e.getMessage(), e); } logger.debug("Calibre ebook-convert output: \n" + output); return tempMobiFilepath.toFile(); }
From source file:info.pancancer.arch3.worker.WorkerRunnable.java
@Override public void run() { int max = maxRuns; try {//from w w w. jav a 2s . co m // the VM UUID log.info(" WORKER VM UUID provided as: '" + vmUuid + "'"); // write to // TODO: Add some sort of "local debug" mode so that developers working on their local // workstation can declare the queue if it doesn't exist. Normally, the results queue is // created by the Coordinator. resultsChannel = Utilities.setupExchange(settings, this.resultsQueueName); while (max > 0 || this.endless) { log.debug(max + " remaining jobs will be executed"); log.info(" WORKER IS PREPARING TO PULL JOB FROM QUEUE " + this.jobQueueName); if (!endless) { max--; } // jobChannel needs to be created inside the loop because it is closed inside the loop, and it is closed inside this loop to // prevent pre-fetching. Channel jobChannel = Utilities.setupQueue(settings, this.jobQueueName); if (jobChannel == null) { throw new NullPointerException("jobChannel is null for queue: " + this.jobQueueName + ". Something bad must have happened while trying to set up the queue connections. Please ensure that your configuration is correct."); } QueueingConsumer consumer = new QueueingConsumer(jobChannel); jobChannel.basicConsume(this.jobQueueName, false, consumer); QueueingConsumer.Delivery delivery = consumer.nextDelivery(); log.info(vmUuid + " received " + delivery.getEnvelope().toString()); if (delivery.getBody() != null) { String message = new String(delivery.getBody(), StandardCharsets.UTF_8); if (message.trim().length() > 0) { log.info(" [x] Received JOBS REQUEST '" + message + "' @ " + vmUuid); Job job = new Job().fromJSON(message); Status status = new Status(vmUuid, job.getUuid(), StatusState.RUNNING, Utilities.JOB_MESSAGE_TYPE, "job is starting", this.networkAddress); status.setStderr(""); status.setStdout(""); String statusJSON = status.toJSON(); log.info(" WORKER LAUNCHING JOB"); // greedy acknowledge, it will be easier to deal with lost jobs than zombie workers in hostile OpenStack // environments log.info(vmUuid + " acknowledges " + delivery.getEnvelope().toString()); jobChannel.basicAck(delivery.getEnvelope().getDeliveryTag(), false); // we need to close the channel IMMEDIATELY to complete the ACK. jobChannel.close(); // Close the connection object as well, or the main thread may not exit because of still-open-and-in-use resources. jobChannel.getConnection().close(); WorkflowResult workflowResult = new WorkflowResult(); if (testMode) { workflowResult.setWorkflowStdout("everything is awesome"); workflowResult.setExitCode(0); } else { String seqwareEngine = settings.getString(Constants.WORKER_SEQWARE_ENGINE, Constants.SEQWARE_WHITESTAR_ENGINE); String seqwareSettingsFile = settings.getString(Constants.WORKER_SEQWARE_SETTINGS_FILE); String dockerImage = settings.getString(Constants.WORKER_SEQWARE_DOCKER_IMAGE_NAME); workflowResult = launchJob(statusJSON, job, seqwareEngine, seqwareSettingsFile, dockerImage); } status = new Status(vmUuid, job.getUuid(), workflowResult.getExitCode() == 0 ? StatusState.SUCCESS : StatusState.FAILED, Utilities.JOB_MESSAGE_TYPE, "job is finished", networkAddress); status.setStderr(workflowResult.getWorkflowStdErr()); status.setStdout(workflowResult.getWorkflowStdout()); statusJSON = status.toJSON(); log.info(" WORKER FINISHING JOB"); finishJob(statusJSON); } else { log.info(NO_MESSAGE_FROM_QUEUE_MESSAGE); } // we need to close the channel *conditionally* if (jobChannel.isOpen()) { jobChannel.close(); } // Close the connection object as well, or the main thread may not exit because of still-open-and-in-use resources. if (jobChannel.getConnection().isOpen()) { jobChannel.getConnection().close(); } } else { log.info(NO_MESSAGE_FROM_QUEUE_MESSAGE); } if (endless) { log.info("attempting to reset workspace"); DefaultExecutor executor = new DefaultExecutor(); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); // attempt a cleanup CommandLine cli = new CommandLine("sudo"); List<String> args = new ArrayList<>(Arrays.asList("rm", "-rf", "/datastore/*")); cli.addArguments(args.toArray(new String[args.size()])); executor.execute(cli, resultHandler); // Use the result handler for non-blocking call, so this way we should be able to get updates of // stdout and stderr while the command is running. resultHandler.waitFor(); log.info("exit code for cleanup: " + resultHandler.getExitValue()); } } log.info(" \n\n\nWORKER FOR VM UUID HAS FINISHED!!!: '" + vmUuid + "'\n\n"); // turns out this is needed when multiple threads are reading from the same // queue otherwise you end up with multiple unacknowledged messages being undeliverable to other workers!!! if (resultsChannel != null && resultsChannel.isOpen()) { resultsChannel.close(); resultsChannel.getConnection().close(); } log.debug("result channel open: " + resultsChannel.isOpen()); log.debug("result channel connection open: " + resultsChannel.getConnection().isOpen()); } catch (Exception ex) { log.error(ex.getMessage(), ex); } }
From source file:at.ac.tuwien.ims.latex2mobiformulaconv.converter.latex2html.PandocLatexToHtmlConverter.java
@Override public Document convert(File tex, String title) { logger.debug("Start convert() with file " + tex.toPath().toAbsolutePath().toString() + ", title: " + title); CommandLine cmdLine;//from w w w . j a va 2s . c o m if (execPath != null) { // Run the configured pandoc executable logger.info("Pandoc will be run from: " + execPath.toString()); cmdLine = new CommandLine(execPath.toFile()); } else { // Run in system PATH environment logger.info("Pandoc will be run within the PATH variable."); cmdLine = new CommandLine("pandoc"); } cmdLine.addArgument("--from=latex"); cmdLine.addArgument("--to=html5"); cmdLine.addArgument("--asciimathml"); // With this option, pandoc does not render latex formulas cmdLine.addArgument("${file}"); HashMap<String, Path> map = new HashMap<String, Path>(); map.put("file", Paths.get(tex.toURI())); cmdLine.setSubstitutionMap(map); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000); // max execution time 1 minute Executor executor = new DefaultExecutor(); executor.setExitValue(1); executor.setWatchdog(watchdog); StringWriter writer = new StringWriter(); WriterOutputStream writerOutputStream = new WriterOutputStream(writer, Charset.forName("UTF-8")); ExecuteStreamHandler pandocStreamHandler = new PumpStreamHandler(writerOutputStream, System.err); executor.setStreamHandler(pandocStreamHandler); logger.debug("Launching pandoc:"); logger.debug(cmdLine.toString()); try { executor.execute(cmdLine, resultHandler); } catch (IOException e) { logger.error("Pandoc's execution failed, exiting..."); logger.error(e.getMessage(), e); System.exit(-1); } try { resultHandler.waitFor(); int exitValue = resultHandler.getExitValue(); logger.debug("Pandoc execution's exit value: " + exitValue); ExecuteException executeException = resultHandler.getException(); if (executeException != null && executeException.getCause() != null) { String exceptionKlass = executeException.getCause().getClass().getCanonicalName(); String exceptionMessage = executeException.getCause().getMessage(); if (exceptionKlass.endsWith("IOException") || exceptionMessage.contains("Cannot run program \"pandoc\"")) { logger.error("Pandoc could not be found! Exiting..."); logger.debug(executeException); System.exit(1); } logger.debug(exceptionKlass + ": " + exceptionMessage); } } catch (InterruptedException e) { logger.error("pandoc conversion thread got interrupted, exiting..."); logger.error(e.getMessage(), e); System.exit(1); } // add html document structure to output // pandoc returns no document markup (html, head, body) // therefore we have to use a template String htmlOutput = "<!DOCTYPE html>\n" + "<html>\n" + "<head>\n" + // set title "<title>" + title + "</title>\n" + // include css "<link rel=\"stylesheet\" type=\"text/css\" href=\"main.css\"></link>\n" + "</head>\n" + "<body>"; try { htmlOutput += writer.getBuffer().toString(); writer.close(); } catch (IOException e) { logger.error("Error reading html result from StringBuffer..."); logger.error(e.getMessage(), e); System.exit(1); } // Close tags in template htmlOutput += "</body>\n" + "</html>"; // output loading as JDOM Document SAXBuilder sax = new SAXBuilder(); Document document = null; try { document = sax.build(new StringReader(htmlOutput)); } catch (JDOMException e) { logger.error("JDOM Parsing error"); logger.error(e.getMessage(), e); System.exit(1); } catch (IOException e) { logger.error("Error reading from String..."); logger.error(e.getMessage(), e); System.exit(1); } return document; }
From source file:beans.ServerBootstrapperImpl.java
private void createNewMachine(ServerNode serverNode) { File cloudFolder = null;//from w w w. ja va2 s . c o m ComputeServiceContext jCloudsContext = null; try { // no existing management machine - create new server String project = serverNode.getProject(); String secretKey = serverNode.getSecretKey(); String apiKey = serverNode.getKey(); logger.info("Creating cloud folder with specific user credentials. Project: [{}], api key: [{}]", project, apiKey); jCloudsContext = CloudifyUtils.createJcloudsContext(project, apiKey, secretKey); cloudFolder = CloudifyUtils.createCloudFolder(project, apiKey, secretKey, jCloudsContext); logger.info("cloud folder is at [{}]", cloudFolder); logger.info("Creating security group for user."); CloudifyUtils.createCloudifySecurityGroup(jCloudsContext); //Command line for bootstrapping remote cloud. CommandLine cmdLine = new CommandLine(conf.server.cloudBootstrap.remoteBootstrap.getAbsoluteFile()); cmdLine.addArgument(cloudFolder.getName()); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); ProcExecutor bootstrapExecutor = executorFactory.getBootstrapExecutor(serverNode); logger.info("Executing command line: " + cmdLine); bootstrapExecutor.execute(cmdLine, ApplicationContext.get().conf().server.environment.getEnvironment(), resultHandler); logger.info("waiting for output"); resultHandler.waitFor(); logger.info("finished waiting , exit value is [{}]", resultHandler.getExitValue()); String output = Utils.getOrDefault(Utils.getCachedOutput(serverNode), ""); if (resultHandler.getException() != null) { logger.info("we have exceptions, checking for known issues"); if (output.contains("found existing management machines")) { logger.info( "found 'found existing management machines' - issuing cloudify already exists message"); throw new ServerException(Messages.get("cloudify.already.exists")); } logger.info("Command execution ended with errors: {}", output); throw new RuntimeException("Failed to bootstrap cloudify machine: " + output, resultHandler.getException()); } logger.info("finished handling errors, extracting IP"); String publicIp = Utils.extractIpFromBootstrapOutput(output); if (StringUtils.isEmpty(publicIp)) { logger.warn("No public ip address found in bootstrap output. " + output); throw new RuntimeException("Bootstrap failed. No IP address found in bootstrap output." + output, resultHandler.getException()); } logger.info("ip is [{}], saving to serverNode", publicIp); String privateKey = CloudifyUtils.getCloudPrivateKey(cloudFolder); if (StringUtils.isEmpty(privateKey)) { throw new RuntimeException("Bootstrap failed. No pem file found in cloud directory."); } logger.info("found PEM string"); logger.info("Bootstrap cloud command ended successfully"); logger.info("updating server node with new info"); serverNode.setPublicIP(publicIp); serverNode.setPrivateKey(privateKey); serverNode.save(); logger.info("server node updated and saved"); } catch (Exception e) { serverNode.errorEvent("Invalid Credentials").save(); throw new RuntimeException("Unable to bootstrap cloud", e); } finally { if (cloudFolder != null && conf.server.cloudBootstrap.removeCloudFolder) { FileUtils.deleteQuietly(cloudFolder); } if (jCloudsContext != null) { jCloudsContext.close(); } serverNode.setStopped(true); } }
From source file:at.ac.tuwien.ims.latex2mobiformulaconv.converter.html2mobi.AmazonHtmlToMobiConverter.java
@Override public File convertToMobi(File htmlFile) { logger.debug("Enter convertToMobi()..."); if (htmlFile == null) { logger.error("Document is null, aborting..."); System.exit(1);/* ww w. j a va 2s. c o m*/ } CommandLine cmdLine; if (execPath != null) { // Run the configured kindlegen executable logger.info("Kindlegen will be run from: " + execPath.toString()); cmdLine = new CommandLine(execPath.toFile()); } else { // Run in system PATH environment logger.info("Kindlegen will be run within the PATH variable."); cmdLine = new CommandLine(command); } // Run configuration cmdLine.addArgument(Paths.get(htmlFile.toURI()).toAbsolutePath().toString()); cmdLine.addArgument("-c0"); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000); Executor executor = new DefaultExecutor(); executor.setExitValue(1); executor.setWatchdog(watchdog); StringWriter stdoutWriter = new StringWriter(); StringWriter stderrWriter = new StringWriter(); WriterOutputStream writerOutputStream = new WriterOutputStream(stdoutWriter, Charset.forName("UTF-8")); WriterOutputStream writerErrorStream = new WriterOutputStream(stderrWriter, Charset.forName("UTF-8")); ExecuteStreamHandler kindlegenStreamHandler = new PumpStreamHandler(writerOutputStream, writerErrorStream); executor.setStreamHandler(kindlegenStreamHandler); logger.debug("Launching kindlegen:"); logger.debug(cmdLine.toString()); try { executor.execute(cmdLine, resultHandler); } catch (IOException e) { logger.error("Kindlegen failed to execute:"); logger.error(e.getMessage(), e); System.exit(-1); } try { resultHandler.waitFor(); int exitValue = resultHandler.getExitValue(); logger.debug("Kindlegen execution's exit value: " + exitValue); ExecuteException executeException = resultHandler.getException(); if (executeException != null && executeException.getCause() != null) { String exceptionKlass = executeException.getCause().getClass().getCanonicalName(); String exceptionMessage = executeException.getCause().getMessage(); if (exceptionKlass.endsWith("IOException") || exceptionMessage.contains("Cannot run program \"kindlegen\"")) { logger.error("Kindlegen could not be run! Exiting..."); logger.debug(executeException); System.exit(1); } logger.debug(exceptionKlass + ": " + exceptionMessage); } } catch (InterruptedException e) { logger.error("Kindlegen's execution got interrupted: "); logger.error(e.getMessage(), e); } try { String stderrOutput = stderrWriter.getBuffer().toString(); stderrWriter.close(); if (stderrOutput.isEmpty() == false) { logger.error("Kindlegen logged some errors:"); logger.error(stderrOutput); } } catch (IOException e) { logger.error("Error closing kindlegen's stderr buffer"); logger.error(e.getMessage(), e); } String output = ""; try { output += stdoutWriter.getBuffer().toString(); stdoutWriter.close(); } catch (IOException e) { logger.error("Error closing kindlegen's stdout buffer:"); logger.error(e.getMessage(), e); } logger.debug("Kindlegen output: \n" + output); String mobiFilename = htmlFile.getName().toString().replace(".html", ".mobi").toString(); logger.debug("Moving Kindlegen output file: " + mobiFilename); Path tempMobiFilepath = Paths.get(htmlFile.toURI()).getParent().resolve(mobiFilename); return tempMobiFilepath.toFile(); }
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 2 s.c om 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.j a 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; }