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.databridge.agent.endpoint.binary.BinarySecureClientPoolFactory.java

@Override
public boolean validateClient(Object client) {
    Socket socket = (Socket) client;
    return socket.isConnected();
}

From source file:org.jmxtrans.embedded.util.pool.SocketOutputStreamPoolFactory.java

/**
 * Defensive approach: we test all the "<code>Socket.isXXX()</code>" flags.
 *//*from  ww  w.j a v a 2 s. co m*/
@Override
public boolean validateObject(HostAndPort hostAndPort, PooledObject<SocketOutputStream> socketOutputStreamRef) {
    Socket socket = socketOutputStreamRef.getObject().getSocket();
    return socket.isConnected() && socket.isBound() && !socket.isClosed() && !socket.isInputShutdown()
            && !socket.isOutputShutdown();
}

From source file:org.apache.jmeter.visualizers.backend.graphite.SocketOutputStreamPoolFactory.java

/**
 *///from  w w w .ja va2 s.c  o  m
@Override
public boolean validateObject(SocketConnectionInfos hostAndPort,
        PooledObject<SocketOutputStream> socketOutputStream) {
    Socket socket = socketOutputStream.getObject().getSocket();
    return socket.isConnected() && socket.isBound() && !socket.isClosed() && !socket.isInputShutdown()
            && !socket.isOutputShutdown();
}

From source file:org.jmxtrans.embedded.util.pool.SocketWriterPoolFactory.java

/**
 * Defensive approach: we test all the "<code>Socket.isXXX()</code>" flags.
 *//*from   w w w. j  ava2  s . co m*/
@Override
public boolean validateObject(HostAndPort hostAndPort, PooledObject<SocketWriter> socketWriterRef) {
    Socket socket = socketWriterRef.getObject().getSocket();
    return socket.isConnected() && socket.isBound() && !socket.isClosed() && !socket.isInputShutdown()
            && !socket.isOutputShutdown();
}

From source file:com.tasktop.c2c.server.web.proxy.ajp.AjpPoolableConnectionFactory.java

@Override
public boolean validateObject(Object key, Object obj) {
    Socket socket = (Socket) obj;
    return socket.isConnected();
}

From source file:org.transdroid.util.IgnoreTlsSniSocketFactory.java

@Override
public boolean isSecure(Socket s) throws IllegalArgumentException {
    return s instanceof SSLSocket && s.isConnected();
}

From source file:org.pentaho.di.trans.steps.mailvalidator.MailValidation.java

/**
 * Validate an email address This code is from : http://www.rgagnon.com/javadetails/java-0452.html
 *
 * @param email// www  .  java 2  s . c  om
 *          address
 * @param sender
 *          email address
 * @param default SMTP Server
 * @param timeout
 *          for socket connection
 * @param deepCheck
 *          (if we want to perform a SMTP check
 * @return true or false
 */
public static MailValidationResult isAddressValid(LogChannelInterface log, String address, String senderAddress,
        String defaultSMTPServer, int timeout, boolean deepCheck) {

    MailValidationResult result = new MailValidationResult();

    if (!isRegExValid(address)) {
        result.setErrorMessage(BaseMessages.getString(PKG, "MailValidator.MalformedAddress", address));
        return result;
    }

    // Find the separator for the domain name
    int pos = address.indexOf('@');

    // If the address does not contain an '@', it's not valid
    if (pos == -1) {
        return result;
    }

    if (!deepCheck) {
        result.setValide(true);
        return result;
    }

    // Isolate the domain/machine name and get a list of mail exchangers
    String domain = address.substring(++pos);

    // Maybe user want to switch to a default SMTP server?
    // In that case, we will ignore the domain
    // extracted from email address

    ArrayList<String> mxList = new ArrayList<String>();
    if (Const.isEmpty(defaultSMTPServer)) {
        try {
            mxList = getMX(domain);

            // Just because we can send mail to the domain, doesn't mean that the
            // address is valid, but if we can't, it's a sure sign that it isn't
            if (mxList == null || mxList.size() == 0) {
                result.setErrorMessage(BaseMessages.getString(PKG, "MailValidator.NoMachinesInDomain", domain));
                return result;
            }
        } catch (Exception ex) {
            result.setErrorMessage(
                    BaseMessages.getString(PKG, "MailValidator.ErrorGettingMachinesInDomain", ex.getMessage()));
            return result;
        }
    } else {
        mxList.add(defaultSMTPServer);
    }

    if (log.isDebug()) {
        log.logDebug(BaseMessages.getString(PKG, "MailValidator.ExchangersFound", "" + mxList.size()));
    }

    // Now, do the SMTP validation, try each mail exchanger until we get
    // a positive acceptance. It *MAY* be possible for one MX to allow
    // a message [store and forwarder for example] and another [like
    // the actual mail server] to reject it. This is why we REALLY ought
    // to take the preference into account.
    for (int mx = 0; mx < mxList.size(); mx++) {
        boolean valid = false;
        BufferedReader rdr = null;
        BufferedWriter wtr = null;
        Socket skt = null;
        try {
            String exhanger = mxList.get(mx);
            if (log.isDebug()) {
                log.logDebug(className(),
                        BaseMessages.getString(PKG, "MailValidator.TryingExchanger", exhanger));
            }

            int res;

            skt = new Socket(exhanger, 25);
            // set timeout (milliseconds)
            if (timeout > 0) {
                skt.setSoTimeout(timeout);
            }

            if (log.isDebug()) {
                log.logDebug(className(), BaseMessages.getString(PKG, "MailValidator.ConnectingTo", exhanger,
                        "25", skt.isConnected() + ""));
            }

            rdr = new BufferedReader(new InputStreamReader(skt.getInputStream()));
            wtr = new BufferedWriter(new OutputStreamWriter(skt.getOutputStream()));

            res = hear(rdr);
            if (res != 220) {
                throw new Exception(BaseMessages.getString(PKG, "MailValidator.InvalidHeader"));
            }

            // say HELLO it's me
            if (log.isDebug()) {
                log.logDebug(className(), BaseMessages.getString(PKG, "MailValidator.SayHello", domain));
            }
            say(wtr, "EHLO " + domain);
            res = hear(rdr);
            if (res != 250) {
                throw new Exception("Not ESMTP");
            }
            if (log.isDebug()) {
                log.logDebug(className(), BaseMessages.getString(PKG, "MailValidator.ServerReplied", "" + res));
            }

            // validate the sender address
            if (log.isDebug()) {
                log.logDebug(className(),
                        BaseMessages.getString(PKG, "MailValidator.CheckSender", senderAddress));
            }
            say(wtr, "MAIL FROM: <" + senderAddress + ">");
            res = hear(rdr);
            if (res != 250) {
                throw new Exception(BaseMessages.getString(PKG, "MailValidator.SenderRejected"));
            }
            if (log.isDebug()) {
                log.logDebug(className(),
                        BaseMessages.getString(PKG, "MailValidator.SenderAccepted", "" + res));
            }

            // Validate receiver
            if (log.isDebug()) {
                log.logDebug(className(), BaseMessages.getString(PKG, "MailValidator.CheckReceiver", address));
            }
            say(wtr, "RCPT TO: <" + address + ">");
            res = hear(rdr);

            // be polite
            say(wtr, "RSET");
            hear(rdr);
            say(wtr, "QUIT");
            hear(rdr);
            if (res != 250) {
                throw new Exception(BaseMessages.getString(PKG, "MailValidator.AddressNotValid", address));
            }

            if (log.isDebug()) {
                log.logDebug(className(),
                        BaseMessages.getString(PKG, "MailValidator.ReceiverAccepted", address, "" + res));
            }
            valid = true;

        } catch (Exception ex) {
            // Do nothing but try next host
            result.setValide(false);
            result.setErrorMessage(ex.getMessage());
        } finally {
            if (rdr != null) {
                try {
                    rdr.close();
                } catch (Exception e) {
                    // ignore this
                }
            }
            if (wtr != null) {
                try {
                    wtr.close();
                } catch (Exception e) {
                    // ignore this
                }
            }
            if (skt != null) {
                try {
                    skt.close();
                } catch (Exception e) {
                    // ignore this
                }
            }

            if (valid) {
                result.setValide(true);
                result.setErrorMessage(null);
                if (log.isDebug()) {
                    log.logDebug(className(), "=============================================");
                }
                return result;
            }
        }
    }
    if (log.isDebug()) {
        log.logDebug(className(), "=============================================");
    }

    return result;
}

From source file:com.bmwcarit.barefoot.matcher.ServerTest.java

private void sendRequest(InetAddress host, int port, JSONArray samples)
        throws InterruptedException, IOException, JSONException {
    int trials = 120;
    int timeout = 500;
    Socket client = null;

    while (client == null || !client.isConnected()) {
        try {/*from www. j  av a  2 s  .c  o  m*/
            client = new Socket(host, port);
        } catch (IOException e) {
            Thread.sleep(timeout);

            if (trials == 0) {
                client.close();
                throw new IOException(e.getMessage());
            } else {
                trials -= 1;
            }
        }
    }

    PrintWriter writer = new PrintWriter(client.getOutputStream());
    BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
    writer.println(samples.toString());
    writer.flush();

    String code = reader.readLine();
    assertEquals("SUCCESS", code);

    String response = reader.readLine();
    client.close();

    MatcherKState state = new MatcherKState(new JSONObject(response),
            new MatcherFactory(ServerControl.getServer().getMap()));

    OutputFormatter output = new GeoJSONOutputFormatter();
    PrintWriter out = new PrintWriter(ServerTest.class.getResource("").getPath() + "ServerTest-matching.json");
    out.println(output.format(null, state));
    out.close();

    assertEquals(samples.length(), state.sequence().size());
}

From source file:at.bitfire.davdroid.webdav.TlsSniSocketFactoryTest.java

public void testCreateSocket() {
    try {/*w  w w  .j  a v  a2s.  c o  m*/
        @Cleanup
        Socket socket = factory.createSocket(null);
        assertFalse(socket.isConnected());
    } catch (IOException e) {
        fail();
    }
}

From source file:voldemort.store.socket.SocketPoolableObjectFactory.java

public boolean validateObject(Object key, Object value) {
    SocketAndStreams sands = (SocketAndStreams) value;
    Socket s = sands.getSocket();
    boolean isValid = !s.isClosed() && s.isBound() && s.isConnected();
    if (!isValid && logger.isDebugEnabled())
        logger.debug("Socket connection " + sands + " is no longer valid, closing.");
    return isValid;
}