Example usage for java.net Socket isConnected

List of usage examples for java.net Socket isConnected

Introduction

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

Prototype

public boolean isConnected() 

Source Link

Document

Returns the connection state of the socket.

Usage

From source file:org.wso2.carbon.andes.internal.QpidServiceComponent.java

/**
 * check whether the tcp port has started. some times the server started thread may return
 * before MQTT server actually bind to the tcp port. in that case there are some connection
 * time out issues.//  w w w . jav a 2  s.com
 *
 * @throws ConfigurationException
 */
private void startMQTTServer() throws ConfigurationException {

    boolean isServerStarted = false;
    int port;

    if (qpidServiceImpl.getMQTTSSLOnly()) {
        port = qpidServiceImpl.getMqttSSLPort();
    } else {
        port = qpidServiceImpl.getMqttPort();
    }

    if (AndesConfigurationManager.<Boolean>readValue(AndesConfiguration.TRANSPORTS_MQTT_ENABLED)) {
        while (!isServerStarted) {
            Socket socket = null;
            try {
                InetAddress address = InetAddress.getByName(getMQTTTransportBindAddress());
                socket = new Socket(address, port);
                log.info("MQTT Host Address : " + address.getHostAddress() + " Port : " + port);
                isServerStarted = socket.isConnected();
                if (isServerStarted) {
                    log.info("Successfully connected to MQTT server on port " + port);
                }
            } catch (IOException e) {
                log.error("Wait until server starts on port " + port, e);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException ignore) {
                    // Ignore
                }
            } finally {
                try {
                    if ((socket != null) && (socket.isConnected())) {
                        socket.close();
                    }
                } catch (IOException e) {
                    log.error("Can not close the socket which is used to check the server " + "status ", e);
                }
            }
        }
    } else {
        log.warn("MQTT Transport is disabled as per configuration.");
    }
}

From source file:runtime.starter.MPJRun.java

private void clientSocketInit() throws Exception {

    for (int i = 0; i < machineList.size(); i++) {
        String daemon = (String) machineList.get(i);
        try {/*from  w w w  .j  ava  2s  . com*/

            if (DEBUG && logger.isDebugEnabled()) {
                logger.debug("Connecting to " + daemon + "@" + D_SER_PORT);
            }
            try {
                Socket sockClient = new Socket(daemon, D_SER_PORT);
                if (sockClient.isConnected())
                    peerSockets.add(sockClient);
                else {

                    throw new MPJRuntimeException(
                            "Cannot connect to the daemon " + "at machine <" + daemon + "> and port <"
                                    + D_SER_PORT + ">." + "Please make sure that the machine is reachable "
                                    + "and running the daemon in 'sane' state");

                }
            } catch (IOException e3) {

                throw new MPJRuntimeException("Cannot connect to the daemon " + "at machine <" + daemon
                        + "> and port <" + D_SER_PORT + ">." + "Please make sure that the machine is reachable "
                        + "and running the daemon in 'sane' state");
            }

        } catch (Exception ccn1) {
            System.out.println(" rest of the exceptions ");
            throw ccn1;
        }
    }

}

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  w  w  .java 2  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;
}

From source file:org.sakaiproject.antivirus.impl.ClamAVScanner.java

protected void doScan(InputStream in) throws VirusScanIncompleteException, VirusFoundException {
    logger.debug("doingScan!");
    Socket socket = null;
    String virus = null;//from ww w  .j  ava 2s .  co  m
    long start = System.currentTimeMillis();
    //this could be a null or zero lenght stream
    if (in == null) {
        return;
    }

    try {
        socket = getClamdSocket();
    } catch (UnknownHostException e) {
        logger.error("could not connect to host for virus check: " + e);
        throw new VirusScanIncompleteException(SCAN_INCOMPLETE_MSG);
    }
    if (socket == null || !socket.isConnected()) {
        logger.warn("scan is inclomplete!");
        throw new VirusScanIncompleteException(SCAN_INCOMPLETE_MSG);
    }
    BufferedReader reader = null;
    PrintWriter writer = null;
    Socket streamSocket = null;
    boolean virusFound = false;
    try {

        // prepare the reader and writer for the commands
        boolean autoFlush = true;
        reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "ASCII"));
        writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),
                autoFlush);
        // write a request for a port to use for streaming out the data to scan
        writer.println("STREAM");

        // parse and get the "stream" port#
        int streamPort = getStreamPortFromAnswer(reader.readLine());

        // get the "stream" socket and the related (buffered) output stream
        streamSocket = new Socket(socket.getInetAddress(), streamPort);
        OutputStream os = streamSocket.getOutputStream();

        // stream out the message to the scanner
        int data;
        // -1 signals the end of the data stream
        while ((data = in.read()) > -1) {
            os.write(data);
        }
        os.flush();
        os.close();
        streamSocket.close();

        String logMessage = "";
        String answer = null;
        for (int i = 0; i < 100; ++i) {
            answer = reader.readLine();
            if (answer != null) {
                answer = answer.trim();

                // if a virus is found the answer will be '... FOUND'
                if (answer.substring(answer.length() - FOUND_STRING.length()).equals(FOUND_STRING)) {
                    virusFound = true;
                    logMessage = answer + " (by virus scanner)";
                    //virus = answer.substring(answer.indexOf(":" + 1));
                    virus = answer.substring(0, answer.indexOf(FOUND_STRING)).trim();
                    logger.debug(logMessage);
                } else {
                    logger.debug("no virus found: " + answer);
                }
            } else {
                break;
            }
        }
        long finish = System.currentTimeMillis();
        logger.debug("Content scanned in " + (finish - start));
    } catch (UnsupportedEncodingException e) {
        logger.error("Exception caught calling CLAMD on " + socket.getInetAddress() + ": " + e.getMessage());
        throw new VirusScanIncompleteException(SCAN_INCOMPLETE_MSG, e);
    } catch (IOException e) {
        //we expect a connection reset if we tried to send too much data to clamd
        if ("Connection reset".equals(e.getMessage())) {
            logger.warn("Clamd reset the connection maybe due to the file being too large");
            return;
        }
        logger.error("Exception caught calling CLAMD on " + socket.getInetAddress() + ": " + e.getMessage());
        throw new VirusScanIncompleteException(SCAN_INCOMPLETE_MSG, e);

    } finally {

        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
            }
        }
        if (writer != null) {
            writer.close();
        }
        if (streamSocket != null) {
            try {
                streamSocket.close();
            } catch (IOException e) {

            }
        }
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {

            }
        }

    }
    if (virusFound) {
        logger.info("Virus detected!: " + virus);
        throw new VirusFoundException(virus);
    }

}

From source file:org.pircbotx.PircBotXOutputTest.java

@BeforeMethod
public void botSetup() throws Exception {
    //Setup bot//from  ww  w  .  j  a  v a2 s  .  c o  m
    inputLatch = new CountDownLatch(1);
    bot = new PircBotX() {
        @Override
        protected InputThread createInputThread(Socket socket, BufferedReader breader) {
            return new InputThread(bot, socket, breader) {
                @Override
                public void run() {
                    //Do nothing
                }
            };
        }
    };
    bot.setListenerManager(new GenericListenerManager());
    bot.setNick("PircBotXBot");
    bot.setName("PircBotXBot");
    bot.setMessageDelay(0L);

    //Setup streams for bot
    PipedOutputStream out = new PipedOutputStream();
    //Create an input stream that we'll kill later
    in = new ByteArrayInputStream("".getBytes());
    Socket socket = mock(Socket.class);
    when(socket.isConnected()).thenReturn(true);
    when(socket.getInputStream()).thenReturn(in);
    when(socket.getOutputStream()).thenReturn(out);
    socketFactory = mock(SocketFactory.class);
    when(socketFactory.createSocket("example.com", 6667, null, 0)).thenReturn(socket);

    //Setup ability to read from bots output
    botOut = new BufferedReader(new InputStreamReader(new PipedInputStream(out)));

    //Connect the bot to the socket
    bot.connect("example.com", 6667, null, socketFactory);

    //Make sure the bot is connected
    verify(socketFactory).createSocket("example.com", 6667, null, 0);

    //Setup useful vars
    aUser = bot.getUser("aUser");
    aChannel = bot.getChannel("#aChannel");
}

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

/**
 * Tests connecting to the socket server and sending a logging event that
 * should be written to configured appenders.
 *
 * @throws  Exception  On errors./*from  w ww.j a va  2  s.  co  m*/
 */
@Test
public void testConnectAndLog() throws Exception {
    final Socket sock = new Socket();
    try {
        final SocketAddress addr = new InetSocketAddress(InetAddress.getByName(server.getBindAddress()),
                server.getPort());
        sock.connect(addr, SOCKET_CONNECT_TIMEOUT);

        // Allow the socket server time to build the hierarchy
        // before sending a test logging event
        Thread.sleep(2000);

        Assert.assertEquals(1, server.getLoggingEventHandlers().size());
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Sending test logging event.");
        }

        final ObjectOutputStream oos = new ObjectOutputStream(sock.getOutputStream());
        oos.writeObject(new MockEvent(TEST_MESSAGE));
        oos.flush();
    } finally {
        if (sock.isConnected()) {
            sock.close();
        }
    }

    // Pause to allow time for logging events to be written
    Thread.sleep(2000);

    // Client socket close should trigger cleanup of server handler mapping
    Assert.assertEquals(0, server.getLoggingEventHandlers().size());

    // Ensure test message was written to file
    Assert.assertTrue(readTextFile(LOG_FILE).contains(TEST_MESSAGE));
}

From source file:org.psit.transwatcher.TransWatcher.java

@Override
public void run() {

    try {/* w  w w. j  av a 2s .co  m*/
        while (true) {

            String cardIP = connectAndGetCardIP();
            if (cardIP != null) {
                notifyMessage("Found SD card, IP: " + cardIP);

                // handshake successful, open permanent TCP connection
                // to listen to new images
                Socket newImageListenerSocket = null;
                try {
                    newImageListenerSocket = new Socket(cardIP, 5566);
                    newImageListenerSocket.setKeepAlive(true);
                    InputStream is = newImageListenerSocket.getInputStream();
                    byte[] c = new byte[1];
                    byte[] singleMessage = new byte[255];
                    int msgPointer = 0;

                    startConnectionKeepAliveWatchDog(newImageListenerSocket);

                    startImageDownloaderQueue(cardIP);

                    setState(State.LISTENING);

                    // loop to wait for new images
                    while (newImageListenerSocket.isConnected()) {
                        if (is.read(c) == 1) {
                            if (0x3E == c[0]) { // >
                                // start of filename
                                msgPointer = 0;
                            } else if (0x00 == c[0]) {
                                // end of filename
                                String msg = new String(Arrays.copyOfRange(singleMessage, 0, msgPointer));
                                notifyMessage("Image shot: " + msg);

                                // add to download queue
                                queue.add(msg);
                            } else {
                                // single byte. add to buffer
                                singleMessage[msgPointer++] = c[0];
                            }
                        }
                    }
                    setState(State.SEARCHING_CARD);
                } catch (IOException e) {
                    notifyMessage("Error during image notification connection!");
                } finally {
                    try {
                        newImageListenerSocket.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else {
                notifyMessage("No card found, retrying.");
            }
            Thread.sleep(2000);
        }
    } catch (InterruptedException e) {
        stopImageDownLoaderQueue();
        notifyMessage("Connection abandoned.");
    }

}

From source file:edu.vt.middleware.gator.log4j.SocketServerTest.java

/**
 * Tests connecting to the socket server and sending a logging event that
 * should be written to configured appenders.
 *
 * @throws  Exception  On errors.//from  w  w  w  .  ja  v  a  2  s  . com
 */
@Test
public void testConnectAndLog() throws Exception {
    final Socket sock = new Socket();
    try {
        final SocketAddress addr = new InetSocketAddress(InetAddress.getByName(server.getBindAddress()),
                server.getPort());
        sock.connect(addr, SOCKET_CONNECT_TIMEOUT);

        // Allow the socket server time to build the hierarchy
        // before sending a test logging event
        Thread.sleep(2000);

        Assert.assertEquals(1, server.getLoggingEventHandlers().size());
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Sending test logging event.");
        }

        final LoggingEvent event = new LoggingEvent(TEST_CATEGORY, Logger.getLogger(TEST_CATEGORY), Level.DEBUG,
                TEST_MESSAGE, null);
        final ObjectOutputStream oos = new ObjectOutputStream(sock.getOutputStream());
        oos.writeObject(event);
        oos.flush();
    } finally {
        if (sock.isConnected()) {
            sock.close();
        }
    }

    // Pause to allow time for logging events to be written
    Thread.sleep(2000);

    // Client socket close should trigger cleanup of server handler mapping
    Assert.assertEquals(0, server.getLoggingEventHandlers().size());

    for (AppenderConfig appender : testProject.getAppenders()) {
        final String logFilePath = FileHelper.pathCat(CLIENT_ROOT_DIR, testProject.getName(),
                appender.getAppenderParam("file").getValue());
        final String contents = readTextFile(logFilePath);
        Assert.assertTrue(contents.contains(TEST_MESSAGE));
    }
}

From source file:com.cyberway.issue.crawler.fetcher.HeritrixProtocolSocketFactory.java

/**
 * Attempts to get a new socket connection to the given host within the
 * given time limit./*  w w  w .jav a 2 s . c  om*/
 * <p>
 * This method employs several techniques to circumvent the limitations
 * of older JREs that do not support connect timeout. When running in
 * JRE 1.4 or above reflection is used to call
 * Socket#connect(SocketAddress endpoint, int timeout) method. When
 * executing in older JREs a controller thread is executed. The
 * controller thread attempts to create a new socket within the given
 * limit of time. If socket constructor does not return until the
 * timeout expires, the controller terminates and throws an
 * {@link ConnectTimeoutException}
 * </p>
 *
 * @param host the host name/IP
 * @param port the port on the host
 * @param localAddress the local host name/IP to bind the socket to
 * @param localPort the port on the local machine
 * @param params {@link HttpConnectionParams Http connection parameters}
 *
 * @return Socket a new socket
 *
 * @throws IOException if an I/O error occurs while creating the socket
 * @throws UnknownHostException if the IP address of the host cannot be
 * @throws IOException if an I/O error occurs while creating the socket
 * @throws UnknownHostException if the IP address of the host cannot be
 * determined
 * @throws ConnectTimeoutException if socket cannot be connected within the
 *  given time limit
 *
 * @since 3.0
 */
public Socket createSocket(final String host, final int port, final InetAddress localAddress,
        final int localPort, final HttpConnectionParams params)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    // Below code is from the DefaultSSLProtocolSocketFactory#createSocket
    // method only it has workarounds to deal with pre-1.4 JVMs.  I've
    // cut these out.
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null");
    }
    Socket socket = null;
    int timeout = params.getConnectionTimeout();
    if (timeout == 0) {
        socket = createSocket(host, port, localAddress, localPort);
    } else {
        socket = new Socket();
        ServerCache cache = (ServerCache) params.getParameter(FetchHTTP.SERVER_CACHE_KEY);
        InetAddress hostAddress = (cache != null) ? getHostAddress(cache, host) : null;
        InetSocketAddress address = (hostAddress != null) ? new InetSocketAddress(hostAddress, port)
                : new InetSocketAddress(host, port);
        socket.bind(new InetSocketAddress(localAddress, localPort));
        try {
            socket.connect(address, timeout);
        } catch (SocketTimeoutException e) {
            // Add timeout info. to the exception.
            throw new SocketTimeoutException(
                    e.getMessage() + ": timeout set at " + Integer.toString(timeout) + "ms.");
        }
        assert socket.isConnected() : "Socket not connected " + host;
    }
    return socket;
}

From source file:org.eclipse.ecf.internal.provider.filetransfer.httpclient4.ECFHttpClientSecureProtocolSocketFactory.java

public Socket connectSocket(final Socket socket, final InetSocketAddress remoteAddress,
        final InetSocketAddress localAddress, final HttpParams params)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    if (remoteAddress == null) {
        throw new IllegalArgumentException("Remote address must not be null"); //$NON-NLS-1$
    }/*from   www.  ja  v  a  2 s  .com*/
    if (params == null) {
        throw new IllegalArgumentException("HTTP parameters must not be null"); //$NON-NLS-1$
    }

    if (socket == null) {
        SSLSocket sslSocket = (SSLSocket) this.sslSocketFactory.createSocket();

        performConnection(sslSocket, remoteAddress, localAddress, params);

        return wrapSocket(sslSocket);
    } else if (socket instanceof SSLSocket) {
        performConnection(socket, remoteAddress, localAddress, params);

        return wrapSocket(socket);
    }

    // If we were given a unconnected socket, we need to connect it first
    if (!socket.isConnected()) {
        performConnection(socket, remoteAddress, localAddress, params);
    }

    Socket layeredSocket = this.sslSocketFactory.createSocket(socket, remoteAddress.getHostName(),
            remoteAddress.getPort(), true);

    return wrapSocket(layeredSocket);
}