Example usage for java.net Socket connect

List of usage examples for java.net Socket connect

Introduction

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

Prototype

public void connect(SocketAddress endpoint, int timeout) throws IOException 

Source Link

Document

Connects this socket to the server with a specified timeout value.

Usage

From source file:hudson.gridmaven.gridlayer.PluginImpl.java

/**
 * Compute the host name that Hadoop nodes can be used to talk to Name node.
 *
 * <p>//w ww.ja  v  a 2s.c o  m
 * We prefer to use {@link Hudson#getRootUrl()}, except we have to watch out for a possibility
 * that it points to a front end (like apache, router with port-forwarding, etc.), and if that is the case,
 * use some heuristics to find out a usable host name.
 *
 * TODO: move this to {@code Hudson.toComputer().getHostName()}. 
 */
String getMasterHostName() throws IOException, InterruptedException {
    // check if rootURL is reliable
    Hudson h = Hudson.getInstance();
    String rootUrl = h.getRootUrl();
    if (rootUrl == null) {
        // the only option is to auto-detect.
        String real = h.toComputer().getHostName();
        LOGGER.fine("Hudson root URL isn't configured. Using " + real + " instead");
        return real;
    }

    // according to Hudson's setting, this is the host name that we can use to connect to master,
    // at least for HTTP. See if we can connect to the arbitrary port in this way.
    final String hostName = new URL(rootUrl).getHost();
    final ServerSocket ss = new ServerSocket(0);

    Thread t = new Thread() {
        @Override
        public void run() {
            try {
                ss.accept();
            } catch (IOException e) {
                // shouldn't happen
                LOGGER.log(Level.INFO, "Failed to accept", e);
            } finally {
                try {
                    ss.close();
                } catch (IOException e) {
                    // ignore
                }
            }
        }
    };
    t.start();

    try {
        Socket s = new Socket();
        s.connect(new InetSocketAddress(hostName, ss.getLocalPort()), 1000);
        s.close();

        // yep, it worked
        return hostName;
    } catch (IOException e) {
        // no it didn't
        String real = h.toComputer().getHostName();
        LOGGER.fine("Hudson root URL " + rootUrl + " looks like a front end. Using " + real + " instead");
        return real;
    }
}

From source file:eu.europa.ec.markt.dss.validation.https.SimpleProtocolSocketFactory.java

@Override
public Socket createSocket(final String host, final int port, final InetAddress localAddress,
        final int localPort, final HttpConnectionParams params)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null");
    }/*from   w  w w.j  av a 2  s . c o  m*/
    int timeout = params.getConnectionTimeout();
    SocketFactory socketfactory = getSSLContext().getSocketFactory();
    if (timeout == 0) {
        return socketfactory.createSocket(host, port, localAddress, localPort);
    } else {
        Socket socket = socketfactory.createSocket();
        SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
        SocketAddress remoteaddr = new InetSocketAddress(host, port);
        socket.bind(localaddr);
        socket.connect(remoteaddr, timeout);
        return socket;
    }
}

From source file:io.fabric8.kubernetes.api.KubernetesHelper.java

public static boolean isServiceSsl(String host, int port, boolean trustAllCerts) {
    try {//  www.  j av a 2  s .  c  o  m
        SSLSocketFactory sslsocketfactory = null;
        if (trustAllCerts) {
            sslsocketfactory = KubernetesFactory.TrustEverythingSSLTrustManager.getTrustingSSLSocketFactory();
        } else {
            sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
        }

        Socket socket = sslsocketfactory.createSocket();

        // Connect, with an explicit timeout value
        socket.connect(new InetSocketAddress(host, port), 1 * 1000);
        try {

            InputStream in = socket.getInputStream();
            OutputStream out = socket.getOutputStream();

            // Write a test byte to get a reaction :)
            out.write(1);

            while (in.available() > 0) {
                System.out.print(in.read());
            }

            return true;
        } finally {
            socket.close();
        }
    } catch (SSLHandshakeException e) {
        LOG.error(
                "SSL handshake failed - this probably means that you need to trust the kubernetes root SSL certificate or set the environment variable "
                        + KubernetesFactory.KUBERNETES_TRUST_ALL_CERIFICATES,
                e);
    } catch (SSLProtocolException e) {
        LOG.error("SSL protocol error", e);
    } catch (SSLKeyException e) {
        LOG.error("Bad SSL key", e);
    } catch (SSLPeerUnverifiedException e) {
        LOG.error("Could not verify server", e);
    } catch (SSLException e) {
        LOG.debug("Address does not appear to be SSL-enabled - falling back to http", e);
    } catch (IOException e) {
        LOG.debug("Failed to validate service", e);
    }
    return false;
}

From source file:org.paxle.crawler.http.impl.AllSSLProtocolSocketFactory.java

/**
 * @see ProtocolSocketFactory#createSocket(String, int, InetAddress, int, HttpConnectionParams)
 *///from w  w  w. jav a  2s. c o m
public Socket createSocket(String host, int port, InetAddress localAddress, int localPort,
        HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
    if (params == null)
        throw new NullPointerException("The connection-params must not be null");

    int timeout = params.getConnectionTimeout();
    if (timeout == 0) {
        return this.socketFactory.createSocket(host, port, localAddress, localPort);
    } else {
        Socket socket = this.socketFactory.createSocket();
        SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
        SocketAddress remoteaddr = new InetSocketAddress(host, port);
        socket.bind(localaddr);
        socket.connect(remoteaddr, timeout);
        return socket;
    }
}

From source file:ee.ria.xroad.proxy.clientproxy.FastestConnectionSelectingSSLSocketFactory.java

private SocketInfo connect(URI address, HttpContext context, int timeout) throws IOException {
    Socket socket = super.createSocket(context);
    try {//from   ww w.  j  a  v a2  s.  c  o m
        socket.connect(toAddress(address), timeout);
        return new SocketInfo(address, socket);
    } catch (IOException | UnresolvedAddressException e) {
        log.error("Could not connect to '{}'", address, e);

        IOUtils.closeQuietly(socket);
        return null;
    }
}

From source file:com.linkedin.d2.discovery.stores.glu.TrustingSocketFactory.java

public Socket createSocket(final String host, final int port, final InetAddress localAddress,
        final int localPort, final HttpConnectionParams params)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null");
    }//from w  w  w. ja va2 s .c o m
    int timeout = params.getConnectionTimeout();
    SocketFactory socketfactory = getSSLContext().getSocketFactory();
    if (timeout == 0) {
        return socketfactory.createSocket(host, port, localAddress, localPort);
    } else {
        Socket socket = socketfactory.createSocket();
        SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
        SocketAddress remoteaddr = new InetSocketAddress(host, port);
        socket.bind(localaddr);
        socket.connect(remoteaddr, timeout);
        return socket;
    }
}

From source file:org.opensaml.ws.soap.client.http.TLSProtocolSocketFactory.java

/** {@inheritDoc} */
public Socket createSocket(String host, int port, InetAddress localHost, int localPort,
        HttpConnectionParams connParams) throws IOException {
    if (connParams == null) {
        throw new IllegalArgumentException("Parameters may not be null");
    }//from  w  w w.  j a  v  a2  s. com
    int timeout = connParams.getConnectionTimeout();
    SocketFactory socketfactory = sslContext.getSocketFactory();
    if (timeout == 0) {
        return socketfactory.createSocket(host, port, localHost, localPort);
    } else {
        Socket socket = socketfactory.createSocket();
        SocketAddress localaddr = new InetSocketAddress(localHost, localPort);
        SocketAddress remoteaddr = new InetSocketAddress(host, port);
        socket.bind(localaddr);
        socket.connect(remoteaddr, timeout);
        return socket;
    }
}

From source file:org.hyperic.hq.plugin.netservices.NetServicesCollector.java

protected void connect(Socket socket) throws IOException {
    InetSocketAddress saddr = getSocketAddress();
    try {//from   w w  w  .j a  va2  s .  c  o m
        socket.connect(saddr, getTimeoutMillis());
        socket.setSoTimeout(getTimeoutMillis());
        setMessage("OK");
    } catch (IOException e) {
        setMessage("connect " + saddr, e);
        throw e;
    }
}

From source file:org.apache.ambari.servicemonitor.probes.PortProbe.java

/**
 * Try to connect to the (host,port); a failure to connect within
 * the specified timeout is a failure/*from   ww w .java2 s . c  o m*/
 * @param livePing is the ping live: true for live; false for boot time
 * @return the outcome
 */
@Override
public ProbeStatus ping(boolean livePing) {
    ProbeStatus status = new ProbeStatus();
    InetSocketAddress sockAddr = new InetSocketAddress(host, port);
    Socket socket = new Socket();
    try {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Connecting to " + sockAddr.toString() + " connection-timeout="
                    + MonitorUtils.millisToHumanTime(timeout));
        }
        socket.connect(sockAddr, timeout);
        status.succeed(this);
    } catch (IOException e) {
        String error = "Probe " + sockAddr + " failed: " + e;
        LOG.debug(error, e);
        status.fail(this, new IOException(error, e));
    } finally {
        IOUtils.closeSocket(socket);
    }
    return status;

}

From source file:com.jivesoftware.os.jive.utils.http.client.CustomSecureProtocolSocketFactory.java

@Override
public Socket createSocket(String host, int port, InetAddress localAddress, int localPort,
        HttpConnectionParams params) throws IOException {

    Socket socket = sslSocketFactory.createSocket();

    if (localAddress != null && port > 0) {
        socket.bind(new InetSocketAddress(localAddress, localPort));
    }/*from  w w w. j a  v  a2s .  c  o m*/

    int timeout = params.getSoTimeout();
    if (timeout > 0) {
        socket.setSoTimeout(timeout);
    }

    socket.connect(new InetSocketAddress(host, port), params.getConnectionTimeout());

    return socket;
}