Search in sources :

Example 26 with SocketFactory

use of javax.net.SocketFactory in project okhttp by square.

the class URLConnectionTest method testConnectViaSocketFactory.

public void testConnectViaSocketFactory(boolean useHttps) throws IOException {
    SocketFactory uselessSocketFactory = new SocketFactory() {

        public Socket createSocket() {
            throw new IllegalArgumentException("useless");
        }

        public Socket createSocket(InetAddress host, int port) {
            return null;
        }

        public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) {
            return null;
        }

        public Socket createSocket(String host, int port) {
            return null;
        }

        public Socket createSocket(String host, int port, InetAddress localHost, int localPort) {
            return null;
        }
    };
    if (useHttps) {
        server.useHttps(sslClient.socketFactory, false);
        urlFactory.setClient(urlFactory.client().newBuilder().sslSocketFactory(sslClient.socketFactory, sslClient.trustManager).hostnameVerifier(new RecordingHostnameVerifier()).build());
    }
    server.enqueue(new MockResponse().setStatus("HTTP/1.1 200 OK"));
    urlFactory.setClient(urlFactory.client().newBuilder().socketFactory(uselessSocketFactory).build());
    connection = urlFactory.open(server.url("/").url());
    try {
        connection.getResponseCode();
        fail();
    } catch (IllegalArgumentException expected) {
    }
    urlFactory.setClient(urlFactory.client().newBuilder().socketFactory(SocketFactory.getDefault()).build());
    connection = urlFactory.open(server.url("/").url());
    assertEquals(200, connection.getResponseCode());
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) SocketFactory(javax.net.SocketFactory) ServerSocketFactory(javax.net.ServerSocketFactory) InetAddress(java.net.InetAddress)

Example 27 with SocketFactory

use of javax.net.SocketFactory in project kdeconnect-android by KDE.

the class LanLinkProvider method udpPacketReceived.

//I've received their broadcast and should connect to their TCP socket and send my identity.
void udpPacketReceived(DatagramPacket packet) throws Exception {
    final InetAddress address = packet.getAddress();
    try {
        String message = new String(packet.getData(), StringsHelper.UTF8);
        final NetworkPackage identityPackage = NetworkPackage.unserialize(message);
        final String deviceId = identityPackage.getString("deviceId");
        if (!identityPackage.getType().equals(NetworkPackage.PACKAGE_TYPE_IDENTITY)) {
            Log.e("KDE/LanLinkProvider", "Expecting an UDP identity package");
            return;
        } else {
            String myId = DeviceHelper.getDeviceId(context);
            if (deviceId.equals(myId)) {
                //Ignore my own broadcast
                return;
            }
        }
        if (identityPackage.getInt("protocolVersion") >= MIN_VERSION_WITH_NEW_PORT_SUPPORT && identityPackage.getInt("tcpPort") < MIN_PORT) {
            Log.w("KDE/LanLinkProvider", "Ignoring a udp broadcast from legacy port because it comes from a device which knows about the new port.");
            return;
        }
        Log.i("KDE/LanLinkProvider", "Broadcast identity package received from " + identityPackage.getString("deviceName"));
        int tcpPort = identityPackage.getInt("tcpPort", MIN_PORT);
        SocketFactory socketFactory = SocketFactory.getDefault();
        Socket socket = socketFactory.createSocket(address, tcpPort);
        configureSocket(socket);
        OutputStream out = socket.getOutputStream();
        NetworkPackage myIdentity = NetworkPackage.createIdentityPackage(context);
        out.write(myIdentity.serialize().getBytes());
        out.flush();
        identityPackageReceived(identityPackage, socket, LanLink.ConnectionStarted.Remotely);
    } catch (Exception e) {
        Log.e("KDE/LanLinkProvider", "Cannot connect to " + address);
        e.printStackTrace();
        if (!reverseConnectionBlackList.contains(address)) {
            Log.w("KDE/LanLinkProvider", "Blacklisting " + address);
            reverseConnectionBlackList.add(address);
            new Timer().schedule(new TimerTask() {

                @Override
                public void run() {
                    reverseConnectionBlackList.remove(address);
                }
            }, 5 * 1000);
            // Try to cause a reverse connection
            onNetworkChange();
        }
    }
}
Also used : Timer(java.util.Timer) TimerTask(java.util.TimerTask) SocketFactory(javax.net.SocketFactory) OutputStream(java.io.OutputStream) NetworkPackage(org.kde.kdeconnect.NetworkPackage) InetAddress(java.net.InetAddress) Socket(java.net.Socket) SSLSocket(javax.net.ssl.SSLSocket) DatagramSocket(java.net.DatagramSocket) ServerSocket(java.net.ServerSocket) SocketException(java.net.SocketException) IOException(java.io.IOException)

Example 28 with SocketFactory

use of javax.net.SocketFactory in project jdk8u_jdk by JetBrains.

the class CloseSocket method main.

public static void main(String[] args) throws Exception {
    try (Server server = new Server()) {
        new Thread(server).start();
        SocketFactory factory = SSLSocketFactory.getDefault();
        try (SSLSocket socket = (SSLSocket) factory.createSocket("localhost", server.getPort())) {
            socket.setSoTimeout(2000);
            System.out.println("Client established TCP connection");
            boolean failed = false;
            for (TestCase testCase : testCases) {
                try {
                    testCase.test(socket);
                    System.out.println("ERROR: no exception");
                    failed = true;
                } catch (IOException e) {
                    System.out.println("Failed as expected: " + e);
                }
            }
            if (failed) {
                throw new Exception("One or more tests failed");
            }
        }
    }
}
Also used : SocketFactory(javax.net.SocketFactory) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) SSLSocket(javax.net.ssl.SSLSocket) IOException(java.io.IOException) IOException(java.io.IOException)

Example 29 with SocketFactory

use of javax.net.SocketFactory in project cloudstack by apache.

the class RawHTTP method _getSocket.

private Socket _getSocket() throws IOException {
    if (useSSL) {
        SSLContext context = null;
        try {
            context = SSLUtils.getSSLContext("SunJSSE");
        } catch (NoSuchAlgorithmException e) {
            s_logger.error("Unexpected exception ", e);
        } catch (NoSuchProviderException e) {
            s_logger.error("Unexpected exception ", e);
        }
        if (context == null)
            throw new IOException("Unable to setup SSL context");
        SSLSocket ssl = null;
        try {
            context.init(null, trustAllCerts, new SecureRandom());
            SocketFactory factory = new SecureSSLSocketFactory(context);
            ssl = (SSLSocket) factory.createSocket(host, port);
            ssl.setEnabledProtocols(SSLUtils.getSupportedProtocols(ssl.getEnabledProtocols()));
        /* ssl.setSSLParameters(context.getDefaultSSLParameters()); */
        } catch (IOException e) {
            s_logger.error("IOException: " + e.getMessage(), e);
            throw e;
        } catch (KeyManagementException e) {
            s_logger.error("KeyManagementException: " + e.getMessage(), e);
        } catch (NoSuchAlgorithmException e) {
            s_logger.error("NoSuchAlgorithmException: " + e.getMessage(), e);
        }
        return ssl;
    } else {
        return new Socket(host, port);
    }
}
Also used : SocketFactory(javax.net.SocketFactory) SecureSSLSocketFactory(org.apache.cloudstack.utils.security.SecureSSLSocketFactory) SSLSocket(javax.net.ssl.SSLSocket) SecureRandom(java.security.SecureRandom) SecureSSLSocketFactory(org.apache.cloudstack.utils.security.SecureSSLSocketFactory) SSLContext(javax.net.ssl.SSLContext) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) NoSuchProviderException(java.security.NoSuchProviderException) KeyManagementException(java.security.KeyManagementException) Socket(java.net.Socket) SSLSocket(javax.net.ssl.SSLSocket)

Example 30 with SocketFactory

use of javax.net.SocketFactory in project geode by apache.

the class SocketCreator method connect.

/**
   * Return a client socket, timing out if unable to connect and timeout > 0 (millis). The parameter
   * <i>timeout</i> is ignored if SSL is being used, as there is no timeout argument in the ssl
   * socket factory
   */
public Socket connect(InetAddress inetadd, int port, int timeout, ConnectionWatcher optionalWatcher, boolean clientSide, int socketBufferSize, boolean sslConnection) throws IOException {
    Socket socket = null;
    SocketAddress sockaddr = new InetSocketAddress(inetadd, port);
    printConfig();
    try {
        if (sslConnection) {
            if (this.sslContext == null) {
                throw new GemFireConfigException("SSL not configured correctly, Please look at previous error");
            }
            SocketFactory sf = this.sslContext.getSocketFactory();
            socket = sf.createSocket();
            // Optionally enable SO_KEEPALIVE in the OS network protocol.
            socket.setKeepAlive(ENABLE_TCP_KEEP_ALIVE);
            // (see java.net.Socket.setReceiverBufferSize javadocs for details)
            if (socketBufferSize != -1) {
                socket.setReceiveBufferSize(socketBufferSize);
            }
            if (optionalWatcher != null) {
                optionalWatcher.beforeConnect(socket);
            }
            socket.connect(sockaddr, Math.max(timeout, 0));
            configureClientSSLSocket(socket, timeout);
            return socket;
        } else {
            if (clientSide && this.clientSocketFactory != null) {
                socket = this.clientSocketFactory.createSocket(inetadd, port);
            } else {
                socket = new Socket();
                // Optionally enable SO_KEEPALIVE in the OS network protocol.
                socket.setKeepAlive(ENABLE_TCP_KEEP_ALIVE);
                // (see java.net.Socket.setReceiverBufferSize javadocs for details)
                if (socketBufferSize != -1) {
                    socket.setReceiveBufferSize(socketBufferSize);
                }
                if (optionalWatcher != null) {
                    optionalWatcher.beforeConnect(socket);
                }
                socket.connect(sockaddr, Math.max(timeout, 0));
            }
            return socket;
        }
    } finally {
        if (optionalWatcher != null) {
            optionalWatcher.afterConnect(socket);
        }
    }
}
Also used : GemFireConfigException(org.apache.geode.GemFireConfigException) InetSocketAddress(java.net.InetSocketAddress) TransportFilterSocketFactory(org.apache.geode.internal.cache.wan.TransportFilterSocketFactory) SocketFactory(javax.net.SocketFactory) ServerSocketFactory(javax.net.ServerSocketFactory) ClientSocketFactory(org.apache.geode.distributed.ClientSocketFactory) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) SSLSocket(javax.net.ssl.SSLSocket) ServerSocket(java.net.ServerSocket) TransportFilterServerSocket(org.apache.geode.internal.cache.wan.TransportFilterServerSocket) SSLServerSocket(javax.net.ssl.SSLServerSocket) Socket(java.net.Socket)

Aggregations

SocketFactory (javax.net.SocketFactory)66 Socket (java.net.Socket)25 Test (org.junit.Test)25 IOException (java.io.IOException)18 InetSocketAddress (java.net.InetSocketAddress)14 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)12 ByteArrayOutputStream (java.io.ByteArrayOutputStream)10 SSLSocket (javax.net.ssl.SSLSocket)10 OutputStream (java.io.OutputStream)9 ServerSocket (java.net.ServerSocket)9 SocketAddress (java.net.SocketAddress)6 Configuration (org.apache.hadoop.conf.Configuration)5 ServerSocketFactory (javax.net.ServerSocketFactory)4 InputStream (java.io.InputStream)3 InetAddress (java.net.InetAddress)3 UnknownHostException (java.net.UnknownHostException)3 ProtocolSocketFactory (org.apache.commons.httpclient.protocol.ProtocolSocketFactory)3 StandardSocketFactory (org.apache.hadoop.net.StandardSocketFactory)3 ByteChunk (org.apache.tomcat.util.buf.ByteChunk)3 SocketException (java.net.SocketException)2