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:com.mirth.connect.connectors.tcp.TcpReceiver.java

private boolean checkSocket(Socket socket) throws IOException {
    return !connectorProperties.isKeepConnectionOpen() || socket.isClosed()
            || (socket instanceof StateAwareSocketInterface
                    && ((StateAwareSocketInterface) socket).remoteSideHasClosed());
}

From source file:org.rifidi.emulator.io.comm.ip.tcpserver.TCPServerCommunicationIncomingConnectionHandler.java

/**
 * The main logic of this monitor, which creates a new server socket bound
 * to the current local IP / port combination and listens for clients to
 * connect until explictly unbound./* ww w .ja  v  a 2  s  .co  m*/
 * 
 * @see java.lang.Runnable#run()
 */
public void run() {
    logger.debug("Attempting to create TCPServer...");

    /* Create the ServerSocket and check to see 
     * if the server socket was made successfully */

    hasNoError = bindServerSocket();

    if (hasNoError) {
        logger.debug("No error creating server, proceeding.");

        /* A string which will be used multiple times in log statements. */
        String serverString = "[" + curServerSocket.getInetAddress().getHostAddress() + ":"
                + curServerSocket.getLocalPort() + "]";

        /* Keep running while the server socket is open. */
        while (!curServerSocket.isClosed() && hasNoError) {

            /* Try to accept a connection */
            Socket curClientSocket = null;
            try {
                logger.debug(serverString + " - Waiting for client...");
                curClientSocket = curServerSocket.accept();
                curClientSocket.setKeepAlive(true);
                //TODO Maybe we should do a disconnect 
            } catch (IOException e) {
                logger.debug(serverString + " - Server accept interrupted.");
                // Retry, because no Socket was created
                continue;
            }
            /* set the new Socket */
            this.hostCommunication.setClientSocket(curClientSocket);

            /* Check to see if a client successfully connected */
            if (curClientSocket != null) {
                final String connectionMessage = serverString + " - Client connected ("
                        + curClientSocket.getInetAddress().getHostAddress() + ":" + curClientSocket.getPort()
                        + ")";

                /* Log the connection */
                logger.info(connectionMessage);

                /* Call connect on the current communication. */
                this.hostCommunication.connect();

                /* Wait until the client socket is disconnected */
                synchronized (curClientSocket) {
                    while (!curClientSocket.isClosed() && curClientSocket.isConnected()) {
                        try {
                            /* Close the ServerSocket so that he couldn't accept 
                             * more than one connections a time (SYN/SYN ACK - Problem)
                             */
                            curServerSocket.close();
                            /* wait until the client connection is closed */
                            curClientSocket.wait();
                            /* bind the ServerSocket again, so that 
                             * new Connections can be made
                             */
                            PowerState powerState = this.hostCommunication.getPowerState();
                            logger.debug("Comm power state is " + powerState);
                            if (powerState != TCPServerOffCommunicationPowerState.getInstance()) {
                                hasNoError = bindServerSocket();
                            }
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (InterruptedException e) {
                            logger.debug("Interrupted Exception happened.");
                        }
                    }

                    /* Done waiting */

                }

            }

        } /* while (!serverSocket.isClosed())... */

        /* Server socket closed */

    } else {
        /* Log the error message. */
        logger.error(errorMessage);
        /* Force a shutdown of the component. */
        this.hostCommunication.turnOff();
    }
    /* All done running. */
}

From source file:runtime.starter.MPJRun.java

private Integer[] getNextAvialablePorts(String machineName) {

    Integer[] ports = new Integer[2];

    Socket portClient = null;
    try {/*from   ww w.  j  a va2  s .  c o m*/
        portClient = new Socket(machineName, portManagerPort);
        OutputStream outToServer = portClient.getOutputStream();
        DataOutputStream out = new DataOutputStream(outToServer);
        out.writeInt(1);
        out.flush();
        DataInputStream din = new DataInputStream(portClient.getInputStream());
        ports[0] = din.readInt();
        ports[1] = din.readInt();
        out.writeInt(2);
        out.flush();

    } catch (IOException e) {
        System.out.println("Cannot connect to the daemon " + "at machine <" + machineName + "> and port <"
                + portManagerPort + ">." + "Please make sure that the machine is reachable "
                + "and portmanager is running");
    } finally {
        try {
            if (!portClient.isClosed())
                portClient.close();
        } catch (IOException e) {

            e.printStackTrace();
        }
    }
    return ports;
}

From source file:com.cws.esolutions.core.utils.NetworkUtils.java

/**
 * Creates an telnet connection to a target host and port number. Silently
 * succeeds if no issues are encountered, if so, exceptions are logged and
 * re-thrown back to the requestor./*from w  ww  .  j  a  v  a  2  s. c om*/
 *
 * If an exception is thrown during the <code>socket.close()</code> operation,
 * it is logged but NOT re-thrown. It's not re-thrown because it does not indicate
 * a connection failure (indeed, it means the connection succeeded) but it is
 * logged because continued failures to close the socket could result in target
 * system instability.
 * 
 * @param hostName - The target host to make the connection to
 * @param portNumber - The port number to attempt the connection on
 * @param timeout - The timeout for the connection
 * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing
 */
public static final synchronized void executeTelnetRequest(final String hostName, final int portNumber,
        final int timeout) throws UtilityException {
    final String methodName = NetworkUtils.CNAME
            + "#executeTelnetRequest(final String hostName, final int portNumber, final int timeout) throws UtilityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug(hostName);
        DEBUGGER.debug("portNumber: {}", portNumber);
        DEBUGGER.debug("timeout: {}", timeout);
    }

    Socket socket = null;

    try {
        synchronized (new Object()) {
            if (InetAddress.getByName(hostName) == null) {
                throw new UnknownHostException("No host was found in DNS for the given name: " + hostName);
            }

            InetSocketAddress socketAddress = new InetSocketAddress(hostName, portNumber);

            socket = new Socket();
            socket.setSoTimeout((int) TimeUnit.SECONDS.toMillis(timeout));
            socket.setSoLinger(false, 0);
            socket.setKeepAlive(false);
            socket.connect(socketAddress, (int) TimeUnit.SECONDS.toMillis(timeout));

            if (!(socket.isConnected())) {
                throw new ConnectException("Failed to connect to host " + hostName + " on port " + portNumber);
            }

            PrintWriter pWriter = new PrintWriter(socket.getOutputStream(), true);

            pWriter.println(NetworkUtils.TERMINATE_TELNET + NetworkUtils.CRLF);

            pWriter.flush();
            pWriter.close();
        }
    } catch (ConnectException cx) {
        throw new UtilityException(cx.getMessage(), cx);
    } catch (UnknownHostException ux) {
        throw new UtilityException(ux.getMessage(), ux);
    } catch (SocketException sx) {
        throw new UtilityException(sx.getMessage(), sx);
    } catch (IOException iox) {
        throw new UtilityException(iox.getMessage(), iox);
    } finally {
        try {
            if ((socket != null) && (!(socket.isClosed()))) {
                socket.close();
            }
        } catch (IOException iox) {
            // log it - this could cause problems later on
            ERROR_RECORDER.error(iox.getMessage(), iox);
        }
    }
}

From source file:com.mirth.connect.connectors.tcp.TcpDispatcher.java

@Override
public Response send(ConnectorProperties connectorProperties, ConnectorMessage message) {
    TcpDispatcherProperties tcpDispatcherProperties = (TcpDispatcherProperties) connectorProperties;
    Status responseStatus = Status.QUEUED;
    String responseData = null;// w  w w .ja v  a 2  s  .  co m
    String responseStatusMessage = null;
    String responseError = null;
    boolean validateResponse = false;

    long dispatcherId = getDispatcherId();

    String socketKey = dispatcherId + tcpDispatcherProperties.getRemoteAddress()
            + tcpDispatcherProperties.getRemotePort();
    if (tcpDispatcherProperties.isOverrideLocalBinding()) {
        socketKey += tcpDispatcherProperties.getLocalAddress() + tcpDispatcherProperties.getLocalPort();
    }

    Socket socket = null;
    Thread timeoutThread = null;

    try {
        // Do some validation first to avoid unnecessarily creating sockets
        if (StringUtils.isBlank(tcpDispatcherProperties.getRemoteAddress())) {
            throw new Exception("Remote address is blank.");
        } else if (NumberUtils.toInt(tcpDispatcherProperties.getRemotePort()) <= 0) {
            throw new Exception("Remote port is invalid.");
        }

        socket = connectedSockets.get(socketKey);
        timeoutThread = timeoutThreads.get(socketKey);

        // If keep connection open is true, then interrupt the thread so it won't close the socket
        if (tcpDispatcherProperties.isKeepConnectionOpen() && timeoutThread != null) {
            disposeThreadQuietly(socketKey);
        }

        // Initialize a new socket if our current one is invalid, the remote side has closed, or keep connection open is false
        if (!tcpDispatcherProperties.isKeepConnectionOpen() || socket == null || socket.isClosed()
                || (tcpDispatcherProperties.isCheckRemoteHost() && socket instanceof StateAwareSocketInterface
                        && ((StateAwareSocketInterface) socket).remoteSideHasClosed())) {
            closeSocketQuietly(socketKey);

            logger.debug("Creating new socket (" + connectorProperties.getName() + " \"" + getDestinationName()
                    + "\" on channel " + getChannelId() + ").");
            String info = "Trying to connect on " + tcpDispatcherProperties.getRemoteAddress() + ":"
                    + tcpDispatcherProperties.getRemotePort() + "...";
            eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                    getDestinationName(), ConnectionStatusEventType.CONNECTING, info));

            if (tcpDispatcherProperties.isOverrideLocalBinding()) {
                socket = SocketUtil.createSocket(configuration, tcpDispatcherProperties.getLocalAddress(),
                        NumberUtils.toInt(tcpDispatcherProperties.getLocalPort()));
            } else {
                socket = SocketUtil.createSocket(configuration);
            }

            ThreadUtils.checkInterruptedStatus();
            connectedSockets.put(socketKey, socket);

            SocketUtil.connectSocket(socket, tcpDispatcherProperties.getRemoteAddress(),
                    NumberUtils.toInt(tcpDispatcherProperties.getRemotePort()), responseTimeout);

            socket.setReuseAddress(true);
            socket.setReceiveBufferSize(bufferSize);
            socket.setSendBufferSize(bufferSize);
            socket.setSoTimeout(responseTimeout);
            socket.setKeepAlive(tcpDispatcherProperties.isKeepConnectionOpen());

            eventController.dispatchEvent(new ConnectorCountEvent(getChannelId(), getMetaDataId(),
                    getDestinationName(), ConnectionStatusEventType.CONNECTED,
                    SocketUtil.getLocalAddress(socket) + " -> " + SocketUtil.getInetAddress(socket), true));
        }

        ThreadUtils.checkInterruptedStatus();

        // Send the message
        eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                getDestinationName(), ConnectionStatusEventType.SENDING,
                SocketUtil.getLocalAddress(socket) + " -> " + SocketUtil.getInetAddress(socket)));
        BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream(), bufferSize);
        BatchStreamReader batchStreamReader = new DefaultBatchStreamReader(socket.getInputStream());
        StreamHandler streamHandler = transmissionModeProvider.getStreamHandler(socket.getInputStream(), bos,
                batchStreamReader, tcpDispatcherProperties.getTransmissionModeProperties());
        streamHandler.write(getTemplateBytes(tcpDispatcherProperties, message));
        bos.flush();

        if (!tcpDispatcherProperties.isIgnoreResponse()) {
            ThreadUtils.checkInterruptedStatus();

            // Attempt to get the response from the remote endpoint
            try {
                String info = "Waiting for response from " + SocketUtil.getInetAddress(socket) + " (Timeout: "
                        + tcpDispatcherProperties.getResponseTimeout() + " ms)... ";
                eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                        getDestinationName(), ConnectionStatusEventType.WAITING_FOR_RESPONSE, info));
                byte[] responseBytes = streamHandler.read();
                if (responseBytes != null) {
                    responseData = new String(responseBytes,
                            CharsetUtils.getEncoding(tcpDispatcherProperties.getCharsetEncoding()));
                    responseStatusMessage = "Message successfully sent.";
                } else {
                    responseStatusMessage = "Message successfully sent, but no response received.";
                }

                streamHandler.commit(true);
                responseStatus = Status.SENT;

                // We only want to validate the response if we were able to retrieve it successfully
                validateResponse = tcpDispatcherProperties.getDestinationConnectorProperties()
                        .isValidateResponse();
            } catch (IOException e) {
                // An exception occurred while retrieving the response
                if (e instanceof SocketTimeoutException
                        || e.getCause() != null && e.getCause() instanceof SocketTimeoutException) {
                    responseStatusMessage = "Timeout waiting for response";

                    if (!tcpDispatcherProperties.isQueueOnResponseTimeout()) {
                        responseStatus = Status.ERROR;
                    }
                } else {
                    responseStatusMessage = "Error receiving response";
                }

                responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(),
                        responseStatusMessage + ": " + e.getMessage(), e);
                logger.warn(responseStatusMessage + " (" + connectorProperties.getName() + " \""
                        + getDestinationName() + "\" on channel " + getChannelId() + ").", e);
                eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(),
                        message.getMessageId(), ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(),
                        connectorProperties.getName(), responseStatusMessage + ".", e));
                eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                        getDestinationName(), ConnectionStatusEventType.FAILURE,
                        responseStatusMessage + " from " + SocketUtil.getInetAddress(socket)));

                closeSocketQuietly(socketKey);
            }
        } else {
            try {
                // MIRTH-2980: Since we're ignoring responses, flush out the socket's input stream so it doesn't continually grow
                socket.getInputStream().skip(socket.getInputStream().available());
            } catch (IOException e) {
                logger.warn("Error flushing socket input stream.", e);
            }

            // We're ignoring the response, so always return a successful response
            responseStatus = Status.SENT;
            responseStatusMessage = "Message successfully sent.";
        }

        if (tcpDispatcherProperties.isKeepConnectionOpen() && (getCurrentState() == DeployedState.STARTED
                || getCurrentState() == DeployedState.STARTING)) {
            if (sendTimeout > 0) {
                // Close the connection after the send timeout has been reached
                startThread(socketKey);
            }
        } else {
            // If keep connection open is false, then close the socket right now
            closeSocketQuietly(socketKey);
        }
    } catch (Throwable t) {
        disposeThreadQuietly(socketKey);
        closeSocketQuietly(socketKey);

        String monitorMessage = "Error sending message (" + SocketUtil.getLocalAddress(socket) + " -> "
                + SocketUtil.getInetAddress(socket) + "): " + t.getMessage();
        eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                getDestinationName(), ConnectionStatusEventType.FAILURE, monitorMessage));

        // If an exception occurred then close the socket, even if keep connection open is true
        responseStatusMessage = t.getClass().getSimpleName() + ": " + t.getMessage();
        responseError = ErrorMessageBuilder.buildErrorMessage(connectorProperties.getName(), t.getMessage(), t);

        String logMessage = "Error sending message via TCP (" + connectorProperties.getName() + " \""
                + getDestinationName() + "\" on channel " + getChannelId() + ").";

        if (t instanceof InterruptedException) {
            Thread.currentThread().interrupt();
        } else if (t instanceof ConnectException
                || t.getCause() != null && t.getCause() instanceof ConnectException) {
            if (isQueueEnabled()) {
                logger.warn(logMessage, t);
            } else {
                logger.error(logMessage, t);
            }
        } else {
            logger.debug(logMessage, t);
        }

        eventController.dispatchEvent(new ErrorEvent(getChannelId(), getMetaDataId(), message.getMessageId(),
                ErrorEventType.DESTINATION_CONNECTOR, getDestinationName(), connectorProperties.getName(),
                "Error sending message via TCP.", t));
    } finally {
        eventController.dispatchEvent(new ConnectorCountEvent(getChannelId(), getMetaDataId(),
                getDestinationName(), ConnectionStatusEventType.IDLE,
                SocketUtil.getLocalAddress(socket) + " -> " + SocketUtil.getInetAddress(socket),
                (Boolean) null));
    }

    return new Response(responseStatus, responseData, responseStatusMessage, responseError, validateResponse);
}

From source file:org.y20k.transistor.helpers.MetadataHelper.java

private void createShoutcastProxyConnection() {
    closeShoutcastProxyConnection();/*from  w  w  w .ja va  2s.c o  m*/
    mProxyRunning = true;
    final StringBuffer shoutcastProxyUri = new StringBuffer();

    try {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Socket proxy = null;
                URLConnection connection = null;

                try {
                    final ServerSocket proxyServer = new ServerSocket(0, 1, InetAddress.getLocalHost());
                    shoutcastProxyUri.append("http://localhost:")
                            .append(String.valueOf(proxyServer.getLocalPort())).append("/");
                    LogHelper.v(LOG_TAG, "createProxyConnection: " + shoutcastProxyUri.toString());

                    proxy = proxyServer.accept();
                    mProxyConnection = proxy;
                    proxyServer.close();

                    connection = new URL(mStreamUri).openConnection();

                    shoutcastProxyReaderLoop(proxy, connection);

                } catch (Exception e) {
                    LogHelper.e(LOG_TAG, "Error: Unable to create proxy server. (" + e + ")");
                }

                mProxyRunning = false;

                try {
                    if (connection != null) {
                        ((HttpURLConnection) connection).disconnect();
                    }
                } catch (Exception ee) {
                    LogHelper.e(LOG_TAG, "Error: Unable to disconnect HttpURLConnection. (" + ee + ")");
                }

                try {
                    if (proxy != null && !proxy.isClosed()) {
                        proxy.close();
                    }
                } catch (Exception eee) {
                    LogHelper.e(LOG_TAG, "Error: Unable to close proxy. (" + eee + ")");
                }
            }
        }).start();

        while (shoutcastProxyUri.length() == 0) {
            try {
                Thread.sleep(10);
            } catch (Exception e) {
                LogHelper.e(LOG_TAG, "Error: Unable to Thread.sleep. (" + e + ")");
            }
        }
        mShoutcastProxy = shoutcastProxyUri.toString();

    } catch (Exception e) {
        LogHelper.e(LOG_TAG,
                "createProxyConnection: Cannot create new listening socket on localhost: " + e.toString());
        mProxyRunning = false;
        mShoutcastProxy = "";
    }
}

From source file:org.zaproxy.zap.extension.websocket.client.ServerConnectionEstablisher.java

/**
 * Create a WebSocket Client with {@link WebSocketProxy#create(String, Socket, Socket, String,
 * int, String, Map)}//from www  .j a va 2 s.  co m
 *
 * @param handshakeConfig Handshake Configuration
 * @param remoteSocket Current connection channel from ZAP to the server.
 * @param remoteReader Current {@link InputStream} of remote connection.
 */
private WebSocketProxy createChannel(HandshakeConfig handshakeConfig, Socket remoteSocket,
        InputStream remoteReader) throws WebSocketException {
    WebSocketProxy webSocketProxy = null;
    HttpMessage handshakeMessage = handshakeConfig.getHttpMessage();
    try {

        HttpRequestHeader requestHeader = handshakeMessage.getRequestHeader();
        String targetHost = requestHeader.getHostName();
        int targetPort = requestHeader.getHostPort();

        if (LOGGER.isDebugEnabled()) {
            StringBuilder logMessage = new StringBuilder(200).append("Got WebSockets channel from ")
                    .append(" to ");
            logMessage.append(targetHost).append(':').append(targetPort);
            LOGGER.debug(logMessage.toString());
        }

        // parse HTTP handshake
        Map<String, String> wsExtensions = WebSocketUtils.parseWebSocketExtensions(handshakeMessage);
        String wsProtocol = WebSocketUtils.parseWebSocketSubProtocol(handshakeMessage);
        String wsVersion = WebSocketUtils.parseWebSocketVersion(handshakeMessage);

        webSocketProxy = WebSocketProxy.create(wsVersion, null, remoteSocket, handshakeMessage.getHistoryRef(),
                targetHost, targetPort, wsProtocol, wsExtensions);

        addChannelObserversIfAny(webSocketProxy, handshakeConfig);
        addChannelSenderListenerIfAny(webSocketProxy, handshakeConfig);

        webSocketProxy.startListeners(getListenerThreadPool(), remoteReader);

    } catch (WebSocketException e) {
        try {
            remoteReader.close();
            if (remoteSocket != null && !remoteSocket.isClosed()) {
                remoteSocket.close();
            }
        } catch (IOException e1) {
            LOGGER.warn(e.getMessage(), e1);
        }
        throw e;
    }
    return webSocketProxy;
}

From source file:org.lockss.protocol.BlockingStreamComm.java

void processIncomingConnection(Socket sock) throws IOException {
    if (sock.isClosed()) {
        // This should no longer happen
        throw new SocketException("processIncomingConnection got closed socket");
    }//www .j ava  2s . co  m
    // Setup socket (SO_TIMEOUT, etc.) before SSL handshake
    setupOpenSocket(sock);
    log.debug2("Accepted connection from " + new IPAddr(sock.getInetAddress()));
    // SSL handshake now performed by channel
    BlockingPeerChannel chan = getSocketFactory().newPeerChannel(this, sock);
    chan.startIncoming();
}

From source file:edu.vt.middleware.gator.log4j.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  .ja  va 2s . c  om*/
            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 LoggerRepository repo = getLoggerRepository(project);
            configurator.configure(project, repo);
            logger.info("Logger repository configured successfully.");
            final LoggingEventHandler handler = new LoggingEventHandler(socket, repo, eventExecutor);
            handler.getSocketCloseListeners().add(this);
            eventHandlerMap.put(inetAddress, handler);
            handlerExecutor.execute(handler);
        } 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:com.cws.esolutions.core.utils.NetworkUtils.java

/**
 * Creates an telnet connection to a target host and port number. Silently
 * succeeds if no issues are encountered, if so, exceptions are logged and
 * re-thrown back to the requestor.//  w ww  .  j a va2  s .c o m
 *
 * If an exception is thrown during the <code>socket.close()</code> operation,
 * it is logged but NOT re-thrown. It's not re-thrown because it does not indicate
 * a connection failure (indeed, it means the connection succeeded) but it is
 * logged because continued failures to close the socket could result in target
 * system instability.
 * 
 * @param hostName - The target host to make the connection to
 * @param portNumber - The port number to attempt the connection on
 * @param timeout - How long to wait for a connection to establish or a response from the target
 * @param object - The serializable object to send to the target
 * @return <code>Object</code> as output from the request
 * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing
 */
public static final synchronized Object executeTcpRequest(final String hostName, final int portNumber,
        final int timeout, final Object object) throws UtilityException {
    final String methodName = NetworkUtils.CNAME
            + "#executeTcpRequest(final String hostName, final int portNumber, final int timeout, final Object object) throws UtilityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug(hostName);
        DEBUGGER.debug("portNumber: {}", portNumber);
        DEBUGGER.debug("timeout: {}", timeout);
        DEBUGGER.debug("object: {}", object);
    }

    Socket socket = null;
    Object resObject = null;

    try {
        synchronized (new Object()) {
            if (StringUtils.isEmpty(InetAddress.getByName(hostName).toString())) {
                throw new UnknownHostException("No host was found in DNS for the given name: " + hostName);
            }

            InetSocketAddress socketAddress = new InetSocketAddress(hostName, portNumber);

            socket = new Socket();
            socket.setSoTimeout((int) TimeUnit.SECONDS.toMillis(timeout));
            socket.setSoLinger(false, 0);
            socket.setKeepAlive(false);
            socket.connect(socketAddress, (int) TimeUnit.SECONDS.toMillis(timeout));

            if (!(socket.isConnected())) {
                throw new ConnectException("Failed to connect to host " + hostName + " on port " + portNumber);
            }

            ObjectOutputStream objectOut = new ObjectOutputStream(socket.getOutputStream());

            if (DEBUG) {
                DEBUGGER.debug("ObjectOutputStream: {}", objectOut);
            }

            objectOut.writeObject(object);

            resObject = new ObjectInputStream(socket.getInputStream()).readObject();

            if (DEBUG) {
                DEBUGGER.debug("resObject: {}", resObject);
            }

            PrintWriter pWriter = new PrintWriter(socket.getOutputStream(), true);

            pWriter.println(NetworkUtils.TERMINATE_TELNET + NetworkUtils.CRLF);

            pWriter.flush();
            pWriter.close();
        }
    } catch (ConnectException cx) {
        throw new UtilityException(cx.getMessage(), cx);
    } catch (UnknownHostException ux) {
        throw new UtilityException(ux.getMessage(), ux);
    } catch (SocketException sx) {
        throw new UtilityException(sx.getMessage(), sx);
    } catch (IOException iox) {
        throw new UtilityException(iox.getMessage(), iox);
    } catch (ClassNotFoundException cnfx) {
        throw new UtilityException(cnfx.getMessage(), cnfx);
    } finally {
        try {
            if ((socket != null) && (!(socket.isClosed()))) {
                socket.close();
            }
        } catch (IOException iox) {
            // log it - this could cause problems later on
            ERROR_RECORDER.error(iox.getMessage(), iox);
        }
    }

    return resObject;
}