Example usage for java.net Socket isClosed

List of usage examples for java.net Socket isClosed

Introduction

In this page you can find the example usage for java.net Socket isClosed.

Prototype

public boolean isClosed() 

Source Link

Document

Returns the closed state of the socket.

Usage

From source file:NanoHTTPD.java

/**
 * Start the server./*from w  ww  .j  av  a 2s.c o  m*/
 *
 * @throws IOException if the socket is in use.
 */
public void start() throws IOException {
    myServerSocket = new ServerSocket();
    myServerSocket
            .bind((hostname != null) ? new InetSocketAddress(hostname, myPort) : new InetSocketAddress(myPort));

    myThread = new Thread(new Runnable() {
        @Override
        public void run() {
            do {
                try {
                    final Socket finalAccept = myServerSocket.accept();
                    registerConnection(finalAccept);
                    finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT);
                    final InputStream inputStream = finalAccept.getInputStream();
                    asyncRunner.exec(new Runnable() {
                        @Override
                        public void run() {
                            OutputStream outputStream = null;
                            try {
                                outputStream = finalAccept.getOutputStream();
                                TempFileManager tempFileManager = tempFileManagerFactory.create();
                                HTTPSession session = new HTTPSession(tempFileManager, inputStream,
                                        outputStream, finalAccept.getInetAddress());
                                while (!finalAccept.isClosed()) {
                                    session.execute();
                                }
                            } catch (Exception e) {
                                // When the socket is closed by the client, we throw our own SocketException
                                // to break the  "keep alive" loop above.
                                if (!(e instanceof SocketException
                                        && "NanoHttpd Shutdown".equals(e.getMessage()))) {
                                    e.printStackTrace();
                                }
                            } finally {
                                safeClose(outputStream);
                                safeClose(inputStream);
                                safeClose(finalAccept);
                                unRegisterConnection(finalAccept);
                            }
                        }
                    });
                } catch (IOException e) {
                }
            } while (!myServerSocket.isClosed());
        }
    });
    myThread.setDaemon(true);
    myThread.setName("NanoHttpd Main Listener");
    myThread.start();
}

From source file:edu.vt.middleware.gator.server.SocketServer.java

/** {@inheritDoc}. */
public void run() {
    while (serverSocket != null && serverSocket.isBound()) {
        logger.info("Waiting to accept a new client.");

        Socket socket = null;
        InetAddress inetAddress = null;
        try {// w  w  w . j  a  v  a2s.c  o m
            socket = serverSocket.accept();
            inetAddress = socket.getInetAddress();

            // Validate newly-connected client
            if (eventHandlerMap.keySet().size() >= maxClients) {
                throw new UnauthorizedClientException(inetAddress, "Maximum number of clients exceeded.");
            }
            final ProjectConfig project = getProject(inetAddress);
            if (project == null) {
                throw new UnauthorizedClientException(inetAddress, "Client not registered with any projects.");
            }

            // Explicitly enable TCP keep alives to try to help reclaim resources
            // from dead clients
            socket.setKeepAlive(true);

            logger.info("Accepted connection from client " + inetAddress);
            logger.info("Configuring logger repository for " + inetAddress);
            final LoggingEngine engine = getLoggingEngine(project);
            if (engine != null) {
                engine.register(inetAddress, project);
                logger.info("Successfully configured " + engine);
                final LoggingEventHandler handler = new LoggingEventHandler(socket, engine, eventExecutor);
                handler.getSocketCloseListeners().add(this);
                eventHandlerMap.put(inetAddress, handler);
                handlerExecutor.execute(handler);
            } else {
                logger.warn(String.format("Logging engine not found for %s.  Closing socket for %s.", project,
                        inetAddress));
                socket.close();
            }
        } catch (UnauthorizedClientException e) {
            logger.warn(String.format("Unauthorized client %s rejected for reason: " + e.getMessage(),
                    e.getClient()));
            if (socket != null && !socket.isClosed()) {
                logger.info("Closing socket for rejected host.");
                try {
                    socket.close();
                } catch (IOException ioex) {
                    logger.error("Error closing client socket.", ioex);
                }
            }
        } catch (SocketException e) {
            // Check whether this is caused by a stop() invocation:
            // calling stop() closes server socket, which throws SocketException
            // from blocking accept() call
            if (serverSocket == null) {
                logger.info("Ignoring SocketException caused by stop() invocation.");
            } else {
                logger.error(e);
            }
        } catch (Exception e) {
            logger.error(e);
        }
    }
}

From source file:org.openqa.jetty.http.handler.ProxyHandler.java

protected HttpTunnel newHttpTunnel(HttpRequest request, HttpResponse response, InetAddress iaddr, int port,
        int timeoutMS) throws IOException {
    try {//  w ww.j a va2  s.com
        Socket socket = null;
        InputStream in = null;

        String chained_proxy_host = System.getProperty("http.proxyHost");
        if (chained_proxy_host == null) {
            socket = new Socket(iaddr, port);
            socket.setSoTimeout(timeoutMS);
            socket.setTcpNoDelay(true);
        } else {
            int chained_proxy_port = Integer.getInteger("http.proxyPort", 8888).intValue();

            Socket chain_socket = new Socket(chained_proxy_host, chained_proxy_port);
            chain_socket.setSoTimeout(timeoutMS);
            chain_socket.setTcpNoDelay(true);
            if (log.isDebugEnabled())
                log.debug("chain proxy socket=" + chain_socket);

            LineInput line_in = new LineInput(chain_socket.getInputStream());
            byte[] connect = request.toString().getBytes(org.openqa.jetty.util.StringUtil.__ISO_8859_1);
            chain_socket.getOutputStream().write(connect);

            String chain_response_line = line_in.readLine();
            HttpFields chain_response = new HttpFields();
            chain_response.read(line_in);

            // decode response
            int space0 = chain_response_line.indexOf(' ');
            if (space0 > 0 && space0 + 1 < chain_response_line.length()) {
                int space1 = chain_response_line.indexOf(' ', space0 + 1);

                if (space1 > space0) {
                    int code = Integer.parseInt(chain_response_line.substring(space0 + 1, space1));

                    if (code >= 200 && code < 300) {
                        socket = chain_socket;
                        in = line_in;
                    } else {
                        Enumeration iter = chain_response.getFieldNames();
                        while (iter.hasMoreElements()) {
                            String name = (String) iter.nextElement();
                            if (!_DontProxyHeaders.containsKey(name)) {
                                Enumeration values = chain_response.getValues(name);
                                while (values.hasMoreElements()) {
                                    String value = (String) values.nextElement();
                                    response.setField(name, value);
                                }
                            }
                        }
                        response.sendError(code);
                        if (!chain_socket.isClosed())
                            chain_socket.close();
                    }
                }
            }
        }

        if (socket == null)
            return null;
        HttpTunnel tunnel = new HttpTunnel(socket, in, null);
        return tunnel;
    } catch (IOException e) {
        log.debug(e);
        response.sendError(HttpResponse.__400_Bad_Request);
        return null;
    }
}

From source file:org.browsermob.proxy.jetty.http.handler.ProxyHandler.java

protected HttpTunnel newHttpTunnel(HttpRequest request, HttpResponse response, InetAddress iaddr, int port,
        int timeoutMS) throws IOException {
    try {/* w w  w . j  a  v a2 s . co m*/
        Socket socket = null;
        InputStream in = null;

        String chained_proxy_host = System.getProperty("http.proxyHost");
        if (chained_proxy_host == null) {
            socket = new Socket(iaddr, port);
            socket.setSoTimeout(timeoutMS);
            socket.setTcpNoDelay(true);
        } else {
            int chained_proxy_port = Integer.getInteger("http.proxyPort", 8888).intValue();

            Socket chain_socket = new Socket(chained_proxy_host, chained_proxy_port);
            chain_socket.setSoTimeout(timeoutMS);
            chain_socket.setTcpNoDelay(true);
            if (log.isDebugEnabled())
                log.debug("chain proxy socket=" + chain_socket);

            LineInput line_in = new LineInput(chain_socket.getInputStream());
            byte[] connect = request.toString()
                    .getBytes(org.browsermob.proxy.jetty.util.StringUtil.__ISO_8859_1);
            chain_socket.getOutputStream().write(connect);

            String chain_response_line = line_in.readLine();
            HttpFields chain_response = new HttpFields();
            chain_response.read(line_in);

            // decode response
            int space0 = chain_response_line.indexOf(' ');
            if (space0 > 0 && space0 + 1 < chain_response_line.length()) {
                int space1 = chain_response_line.indexOf(' ', space0 + 1);

                if (space1 > space0) {
                    int code = Integer.parseInt(chain_response_line.substring(space0 + 1, space1));

                    if (code >= 200 && code < 300) {
                        socket = chain_socket;
                        in = line_in;
                    } else {
                        Enumeration iter = chain_response.getFieldNames();
                        while (iter.hasMoreElements()) {
                            String name = (String) iter.nextElement();
                            if (!_DontProxyHeaders.containsKey(name)) {
                                Enumeration values = chain_response.getValues(name);
                                while (values.hasMoreElements()) {
                                    String value = (String) values.nextElement();
                                    response.setField(name, value);
                                }
                            }
                        }
                        response.sendError(code);
                        if (!chain_socket.isClosed())
                            chain_socket.close();
                    }
                }
            }
        }

        if (socket == null)
            return null;
        HttpTunnel tunnel = new HttpTunnel(socket, in, null);
        return tunnel;
    } catch (IOException e) {
        log.debug(e);
        response.sendError(HttpResponse.__400_Bad_Request);
        return null;
    }
}

From source file:net.lightbody.bmp.proxy.jetty.http.handler.ProxyHandler.java

protected HttpTunnel newHttpTunnel(HttpRequest request, HttpResponse response, InetAddress iaddr, int port,
        int timeoutMS) throws IOException {
    try {/*from   w w  w .  j a va2s.  c o m*/
        Socket socket = null;
        InputStream in = null;

        String chained_proxy_host = System.getProperty("http.proxyHost");
        if (chained_proxy_host == null) {
            socket = new Socket(iaddr, port);
            socket.setSoTimeout(timeoutMS);
            socket.setTcpNoDelay(true);
        } else {
            int chained_proxy_port = Integer.getInteger("http.proxyPort", 8888).intValue();

            Socket chain_socket = new Socket(chained_proxy_host, chained_proxy_port);
            chain_socket.setSoTimeout(timeoutMS);
            chain_socket.setTcpNoDelay(true);
            if (log.isDebugEnabled())
                log.debug("chain proxy socket=" + chain_socket);

            LineInput line_in = new LineInput(chain_socket.getInputStream());
            byte[] connect = request.toString()
                    .getBytes(net.lightbody.bmp.proxy.jetty.util.StringUtil.__ISO_8859_1);
            chain_socket.getOutputStream().write(connect);

            String chain_response_line = line_in.readLine();
            HttpFields chain_response = new HttpFields();
            chain_response.read(line_in);

            // decode response
            int space0 = chain_response_line.indexOf(' ');
            if (space0 > 0 && space0 + 1 < chain_response_line.length()) {
                int space1 = chain_response_line.indexOf(' ', space0 + 1);

                if (space1 > space0) {
                    int code = Integer.parseInt(chain_response_line.substring(space0 + 1, space1));

                    if (code >= 200 && code < 300) {
                        socket = chain_socket;
                        in = line_in;
                    } else {
                        Enumeration iter = chain_response.getFieldNames();
                        while (iter.hasMoreElements()) {
                            String name = (String) iter.nextElement();
                            if (!_DontProxyHeaders.containsKey(name)) {
                                Enumeration values = chain_response.getValues(name);
                                while (values.hasMoreElements()) {
                                    String value = (String) values.nextElement();
                                    response.setField(name, value);
                                }
                            }
                        }
                        response.sendError(code);
                        if (!chain_socket.isClosed())
                            chain_socket.close();
                    }
                }
            }
        }

        if (socket == null)
            return null;
        HttpTunnel tunnel = new HttpTunnel(socket, in, null);
        return tunnel;
    } catch (IOException e) {
        log.debug(e);
        response.sendError(HttpResponse.__400_Bad_Request);
        return null;
    }
}

From source file:fi.iki.elonen.NanoHTTPD.java

/**
 * Start the server./*from   w w w.  j a  v  a  2 s  . c  o  m*/
 *
 * @throws IOException if the socket is in use.
 */
public void start() throws IOException {
    myServerSocket = new ServerSocket();
    myServerSocket
            .bind((hostname != null) ? new InetSocketAddress(hostname, myPort) : new InetSocketAddress(myPort));

    myThread = new Thread(new Runnable() {
        @Override
        public void run() {
            do {
                try {
                    final Socket finalAccept = myServerSocket.accept();
                    registerConnection(finalAccept);
                    finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT);
                    final InputStream inputStream = finalAccept.getInputStream();
                    if (inputStream == null) {
                        safeClose(finalAccept);
                        unRegisterConnection(finalAccept);
                    } else {
                        asyncRunner.exec(new Runnable() {
                            @Override
                            public void run() {
                                BufferedInputStream bufferedInputStream = null;
                                OutputStream outputStream = null;
                                try {
                                    bufferedInputStream = new BufferedInputStream(inputStream);
                                    outputStream = finalAccept.getOutputStream();
                                    TempFileManager tempFileManager = tempFileManagerFactory.create();
                                    HTTPSession session = new HTTPSession(tempFileManager, bufferedInputStream,
                                            outputStream, finalAccept.getInetAddress());
                                    while (!finalAccept.isClosed()) {
                                        session.execute();
                                    }
                                } catch (Exception e) {
                                    // When the socket is closed by the client, we throw our own SocketException
                                    // to break the  "keep alive" loop above.
                                    if (!(e instanceof SocketException
                                            && "NanoHttpd Shutdown".equals(e.getMessage()))) {
                                        e.printStackTrace();
                                    }
                                } finally {
                                    safeClose(bufferedInputStream);
                                    safeClose(outputStream);
                                    safeClose(finalAccept);
                                    unRegisterConnection(finalAccept);
                                }
                            }
                        });
                    }
                } catch (IOException e) {
                }
            } while (!myServerSocket.isClosed());
        }
    });
    myThread.setDaemon(true);
    myThread.setName("NanoHttpd Main Listener");
    myThread.start();
}

From source file:org.openqa.selenium.server.ProxyHandler.java

protected HttpTunnel newHttpTunnel(HttpRequest request, HttpResponse response, InetAddress iaddr, int port,
        int timeoutMS) throws IOException {
    try {/*w ww  . ja va 2s .  c om*/
        Socket socket = null;
        InputStream in = null;

        String chained_proxy_host = System.getProperty("http.proxyHost");
        if (chained_proxy_host == null) {
            socket = new Socket(iaddr, port);
            socket.setSoTimeout(timeoutMS);
            socket.setTcpNoDelay(true);
        } else {
            int chained_proxy_port = Integer.getInteger("http.proxyPort", 8888).intValue();

            Socket chain_socket = new Socket(chained_proxy_host, chained_proxy_port);
            chain_socket.setSoTimeout(timeoutMS);
            chain_socket.setTcpNoDelay(true);
            if (log.isDebugEnabled())
                log.debug("chain proxy socket=" + chain_socket);

            LineInput line_in = new LineInput(chain_socket.getInputStream());
            byte[] connect = request.toString().getBytes(org.openqa.jetty.util.StringUtil.__ISO_8859_1);
            chain_socket.getOutputStream().write(connect);

            String chain_response_line = line_in.readLine();
            HttpFields chain_response = new HttpFields();
            chain_response.read(line_in);

            // decode response
            int space0 = chain_response_line.indexOf(' ');
            if (space0 > 0 && space0 + 1 < chain_response_line.length()) {
                int space1 = chain_response_line.indexOf(' ', space0 + 1);

                if (space1 > space0) {
                    int code = Integer.parseInt(chain_response_line.substring(space0 + 1, space1));

                    if (code >= 200 && code < 300) {
                        socket = chain_socket;
                        in = line_in;
                    } else {
                        Enumeration iter = chain_response.getFieldNames();
                        while (iter.hasMoreElements()) {
                            String name = (String) iter.nextElement();
                            if (!_DontProxyHeaders.containsKey(name)) {
                                Enumeration values = chain_response.getValues(name);
                                while (values.hasMoreElements()) {
                                    String value = (String) values.nextElement();
                                    response.setField(name, value);
                                }
                            }
                        }
                        response.sendError(code);
                        if (!chain_socket.isClosed())
                            chain_socket.close();
                    }
                }
            }
        }

        if (socket == null)
            return null;
        return new HttpTunnel(socket, in, null);
    } catch (IOException e) {
        log.debug(e);
        response.sendError(HttpResponse.__400_Bad_Request);
        return null;
    }
}

From source file:com.symbian.driver.core.controller.tasks.TEFTask.java

/**
 * @param aVisitor/*from www  .  j a  va 2  s.  co m*/
 * @param aTestExecuteScript
 * @param lExecuteOnDevice
 * @param aTask
 * @return The last execption raised when running UCC.
 * @throws JStatException
 */
private boolean runUCC(List<String> aArgs, Task aTask) {
    boolean lReturn = true;
    Socket lUccSocket = null;
    DataOutputStream lSocketOut = null;
    DataInputStream lSocketIn = null;
    int lRunNumber = 0;
    int lUccPort = -1;
    String lUccAddress = null;
    IDeviceComms.ISymbianProcess lProcess = null;

    try {
        String[] lUccSplit = TDConfig.getInstance().getPreference(TDConfig.UCC_IP_ADDRESS).split(":");
        lRunNumber = TDConfig.getInstance().getPreferenceInteger(TDConfig.RUN_NUMBER);

        lUccAddress = lUccSplit[0];
        lUccPort = Integer.parseInt(lUccSplit[1]);
    } catch (ParseException lParseException) {
        LOGGER.log(Level.SEVERE, "Could not get configuration for UCC.", lParseException);
        iExceptions.put(lParseException, ESeverity.ERROR);
        lReturn = false;
    } catch (NumberFormatException lNumberFormatException) {
        LOGGER.log(Level.SEVERE, "Could not parse the port number for UCC.", lNumberFormatException);
        iExceptions.put(lNumberFormatException, ESeverity.ERROR);
        lReturn = false;
    }

    if (lUccAddress == null || lUccAddress.equals("") || lUccPort < 0) {
        iExceptions.put(
                new UnknownHostException("Please specify a valid UCC address for example 192.168.0.1:3000"),
                ESeverity.ERROR);
        return false;
    }

    // Run the test
    try {
        LOGGER.info("Running UCC with:\n\tAddress: " + lUccAddress + "\n\tUCC Port:" + lUccPort);

        lUccSocket = new Socket(lUccAddress, lUccPort);
        lSocketOut = new DataOutputStream(lUccSocket.getOutputStream());
        lSocketIn = new DataInputStream(lUccSocket.getInputStream());

        LOGGER.fine("Starting UCC while still polling");
        lProcess = iDeviceProxy.createSymbianProcess();
        if (lProcess != null) {
            // run and don't wait
            if (!lProcess.runCommand(TEST_EXECUTE, aArgs, aTask.getTimeout() * 1000, false)) {
                iExceptions.put(new Exception("Failed to run TEF for UCC."), ESeverity.ERROR);
                lReturn = false;
            }

            // Tell UCC that the test has started.
            LOGGER.fine("Writing to UCC socket: " + lRunNumber);
            lSocketOut.writeInt(lRunNumber);
            lSocketOut.flush();

            int lUCCReply = lSocketIn.readInt();
            LOGGER.fine("UCC Reply: " + lUCCReply);
        }

    } catch (UnknownHostException lUnknownHostException) {
        LOGGER.log(Level.SEVERE, "Could not find UCC host", lUnknownHostException);
        iExceptions.put(lUnknownHostException, ESeverity.ERROR);
        return false;
    } catch (IOException lIOException) {
        LOGGER.log(Level.SEVERE,
                "IO Exception during UCC testing: " + lIOException.getMessage() + (lUccSocket != null
                        ? "\nUcc Socket Connected: " + lUccSocket.isConnected() + "\nUcc Socket InputShutdown: "
                                + lUccSocket.isInputShutdown() + "\nUcc Socket OutputShutdown:"
                                + lUccSocket.isOutputShutdown() + "\nUcc Socket Bound: " + lUccSocket.isBound()
                        : "\nUcc Socket is NULL"),
                lIOException);
        iExceptions.put(lIOException, ESeverity.ERROR);
        return false;
    } finally {

        // Close UCC
        if (lSocketOut != null) {
            try {
                LOGGER.log(Level.FINE, "Closing Socket Out.");
                lUccSocket.shutdownInput();
                lUccSocket.shutdownOutput();
                lSocketOut.close();
            } catch (IOException lIOException) {
                LOGGER.log(Level.SEVERE, "Could not close UCC Out socket.", lIOException);
                iExceptions.put(lIOException, ESeverity.ERROR);
            }
        }
        if (lSocketIn != null) {
            try {
                LOGGER.log(Level.FINE, "Closing Socket In.");
                lSocketIn.close();
            } catch (IOException lIOException) {
                LOGGER.log(Level.SEVERE, "Could not close UCC In socket.", lIOException);
                iExceptions.put(lIOException, ESeverity.ERROR);
            }
        }
        if (lUccSocket != null) {
            try {
                LOGGER.log(Level.FINE, "Closing Socket UCC.");
                lUccSocket.close();
            } catch (IOException lIOException) {
                LOGGER.log(Level.SEVERE, "Could not close UCC socket.", lIOException);
                iExceptions.put(lIOException, ESeverity.ERROR);
            }
        }

        if (!lUccSocket.isClosed()) {
            LOGGER.warning("Could not close the UCC sockets properly.");
        }

        lSocketOut = null;
        lSocketIn = null;
        lUccSocket = null;

        // Poll TEF Test
        if (!lProcess.join()) {
            iExceptions.put(new Exception("Coud not join UCC-TEF Process"), ESeverity.ERROR);
            lReturn = false;
        }

    }
    return lReturn;
}

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) {//w  w 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;
}