Example usage for org.apache.commons.exec DefaultExecutor execute

List of usage examples for org.apache.commons.exec DefaultExecutor execute

Introduction

In this page you can find the example usage for org.apache.commons.exec DefaultExecutor execute.

Prototype

public void execute(final CommandLine command, final ExecuteResultHandler handler)
        throws ExecuteException, IOException 

Source Link

Usage

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. ja va2 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:com.k42b3.sacmis.Sacmis.java

private void executeCommand() {
    out.setText("");

    try {/*from  w  ww .  j av a  2  s . com*/
        // 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:Logi.GSeries.Service.LogiGSKService.java

public void showSystemTray() {
    if ((systemTray != null) && !systemTrayVisible) {
        systemTray.setEnabled(true);/*  ww  w .j a  va2 s. c o m*/
        systemTrayVisible = true;
        return;
    }

    try {
        systemTray = SystemTray.getNative();
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
        Logger.getLogger(LogiGSKService.class.getName()).log(Level.SEVERE, null, ex);
    }

    if (systemTray != null) {
        try {
            systemTray.setImage(GSK_Icon);
        } catch (Exception e) {
            System.err.println("Problem setting system tray icon.");
        }
        systemTrayVisible = true;
        callbackOpen = new ActionListener() {
            @Override
            public void actionPerformed(final ActionEvent e) {
                final MenuItem entry = (MenuItem) e.getSource();
                try {
                    CommandLine commandLine = new CommandLine("java");
                    commandLine.addArgument("-jar");
                    String jarPath = new URI(
                            LogiGSKService.class.getProtectionDomain().getCodeSource().getLocation().getPath())
                                    .getPath();
                    commandLine.addArgument(jarPath, false);
                    DefaultExecutor executor = new DefaultExecutor();
                    executor.setExitValue(1);
                    executor.execute(commandLine, new DefaultExecuteResultHandler());
                } catch (URISyntaxException ex) {
                    Logger.getLogger(LogiGSKService.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(LogiGSKService.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        };

        callbackAbout = new ActionListener() {
            @Override
            public void actionPerformed(final ActionEvent e) {
                final MenuItem entry = (MenuItem) e.getSource();
                JOptionPane.showMessageDialog(null, "<HTML>LogiGSK V1.0</HTML>", "LogiGSK",
                        JOptionPane.INFORMATION_MESSAGE);
            }
        };

        Menu mainMenu = systemTray.getMenu();

        MenuItem openEntry = new MenuItem("Open", new ActionListener() {
            @Override
            public void actionPerformed(final ActionEvent e) {
                final MenuItem entry = (MenuItem) e.getSource();
                entry.setCallback(callbackOpen);
                try {
                    CommandLine commandLine = new CommandLine("java");
                    commandLine.addArgument("-jar");
                    String jarPath = new URI(
                            LogiGSKService.class.getProtectionDomain().getCodeSource().getLocation().getPath())
                                    .getPath();
                    commandLine.addArgument(jarPath, false);
                    DefaultExecutor executor = new DefaultExecutor();
                    executor.setExitValue(1);
                    executor.execute(commandLine, new DefaultExecuteResultHandler());
                } catch (URISyntaxException ex) {
                    Logger.getLogger(LogiGSKService.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(LogiGSKService.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
        openEntry.setShortcut('O');
        mainMenu.add(openEntry);
        mainMenu.add(new Separator());

        MenuItem aboutEntry = new MenuItem("About", new ActionListener() {
            @Override
            public void actionPerformed(final ActionEvent e) {
                final MenuItem entry = (MenuItem) e.getSource();
                JOptionPane.showMessageDialog(null, "<HTML>LogiGSK V1.0</HTML>", "LogiGSK",
                        JOptionPane.INFORMATION_MESSAGE);
                entry.setCallback(callbackAbout);
            }
        });
        openEntry.setShortcut('A');
        mainMenu.add(aboutEntry);
        /*} else {
        System.err.println("System tray is null!");
        }*/
    }
}

From source file:info.pancancer.arch3.worker.WorkerRunnable.java

@Override
public void run() {

    int max = maxRuns;

    try {//from  w w w  .j a v  a2  s . c  o  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:io.takari.maven.testing.executor.ForkedLauncher.java

public int run(String[] cliArgs, Map<String, String> envVars, File multiModuleProjectDirectory,
        File workingDirectory, File logFile) throws IOException, LauncherException {
    String javaHome;//  w  w w  .j  a  v  a 2 s  .c  o m
    if (envVars == null || envVars.get("JAVA_HOME") == null) {
        javaHome = System.getProperty("java.home");
    } else {
        javaHome = envVars.get("JAVA_HOME");
    }

    File executable = new File(javaHome, Os.isFamily(Os.FAMILY_WINDOWS) ? "bin/javaw.exe" : "bin/java");

    CommandLine cli = new CommandLine(executable);
    cli.addArgument("-classpath").addArgument(classworldsJar.getAbsolutePath());
    cli.addArgument("-Dclassworlds.conf=" + new File(mavenHome, "bin/m2.conf").getAbsolutePath());
    cli.addArgument("-Dmaven.home=" + mavenHome.getAbsolutePath());
    cli.addArgument("-Dmaven.multiModuleProjectDirectory=" + multiModuleProjectDirectory.getAbsolutePath());
    cli.addArgument("org.codehaus.plexus.classworlds.launcher.Launcher");

    cli.addArguments(args.toArray(new String[args.size()]));
    if (extensions != null && !extensions.isEmpty()) {
        cli.addArgument("-Dmaven.ext.class.path=" + toPath(extensions));
    }

    cli.addArguments(cliArgs);

    Map<String, String> env = new HashMap<>();
    if (mavenHome != null) {
        env.put("M2_HOME", mavenHome.getAbsolutePath());
    }
    if (envVars != null) {
        env.putAll(envVars);
    }
    if (envVars == null || envVars.get("JAVA_HOME") == null) {
        env.put("JAVA_HOME", System.getProperty("java.home"));
    }

    DefaultExecutor executor = new DefaultExecutor();
    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
    executor.setWorkingDirectory(workingDirectory.getAbsoluteFile());

    try (OutputStream log = new FileOutputStream(logFile)) {
        PrintStream out = new PrintStream(log);
        out.format("Maven Executor implementation: %s\n", getClass().getName());
        out.format("Maven home: %s\n", mavenHome);
        out.format("Build work directory: %s\n", workingDirectory);
        out.format("Environment: %s\n", env);
        out.format("Command line: %s\n\n", cli.toString());
        out.flush();

        PumpStreamHandler streamHandler = new PumpStreamHandler(log);
        executor.setStreamHandler(streamHandler);
        return executor.execute(cli, env); // this throws ExecuteException if process return code != 0
    } catch (ExecuteException e) {
        throw new LauncherException("Failed to run Maven: " + e.getMessage() + "\n" + cli, e);
    }
}

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());/* w ww  . j av a2s .  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: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  ww  .j a  va2 s  .  c  om
    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: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();

    /*//w ww .  jav a 2  s. c o  m
     * 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: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  w  w  w  .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)
 *//*from  w w w .j a va2s.  c o m*/
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;
}