Search in sources :

Example 61 with Socket

use of java.net.Socket in project camel by apache.

the class UnsharableCodecsConflictsTest method canSupplyMultipleCodecsToEndpointPipeline.

@Test
public void canSupplyMultipleCodecsToEndpointPipeline() throws Exception {
    byte[] sPort1 = new byte[8192];
    byte[] sPort2 = new byte[16383];
    Arrays.fill(sPort1, (byte) 0x38);
    Arrays.fill(sPort2, (byte) 0x39);
    byte[] bodyPort1 = (new String(LENGTH_HEADER) + new String(sPort1)).getBytes();
    byte[] bodyPort2 = (new String(LENGTH_HEADER) + new String(sPort2)).getBytes();
    MockEndpoint mock = getMockEndpoint("mock:result");
    mock.expectedBodiesReceived(new String(sPort2) + "9");
    Socket server1 = getSocket("localhost", port1);
    Socket server2 = getSocket("localhost", port2);
    try {
        sendSopBuffer(bodyPort2, server2);
        sendSopBuffer(bodyPort1, server1);
        sendSopBuffer(new String("9").getBytes(), server2);
    } catch (Exception e) {
        log.error("", e);
    } finally {
        server1.close();
        server2.close();
    }
    mock.assertIsSatisfied();
}
Also used : MockEndpoint(org.apache.camel.component.mock.MockEndpoint) Socket(java.net.Socket) IOException(java.io.IOException) Test(org.junit.Test)

Example 62 with Socket

use of java.net.Socket in project robovm by robovm.

the class DefaultClientConnectionOperator method updateSecureConnection.

// openConnection
// non-javadoc, see interface ClientConnectionOperator
public void updateSecureConnection(OperatedClientConnection conn, HttpHost target, HttpContext context, HttpParams params) throws IOException {
    if (conn == null) {
        throw new IllegalArgumentException("Connection must not be null.");
    }
    if (target == null) {
        throw new IllegalArgumentException("Target host must not be null.");
    }
    //@@@ is context allowed to be null?
    if (params == null) {
        throw new IllegalArgumentException("Parameters must not be null.");
    }
    if (!conn.isOpen()) {
        throw new IllegalArgumentException("Connection must be open.");
    }
    final Scheme schm = schemeRegistry.getScheme(target.getSchemeName());
    if (!(schm.getSocketFactory() instanceof LayeredSocketFactory)) {
        throw new IllegalArgumentException("Target scheme (" + schm.getName() + ") must have layered socket factory.");
    }
    final LayeredSocketFactory lsf = (LayeredSocketFactory) schm.getSocketFactory();
    final Socket sock;
    try {
        sock = lsf.createSocket(conn.getSocket(), target.getHostName(), schm.resolvePort(target.getPort()), true);
    } catch (ConnectException ex) {
        throw new HttpHostConnectException(target, ex);
    }
    prepareSocket(sock, context, params);
    conn.update(sock, target, lsf.isSecure(sock), params);
//@@@ error handling: close the layered socket in case of exception?
}
Also used : Scheme(org.apache.http.conn.scheme.Scheme) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) LayeredSocketFactory(org.apache.http.conn.scheme.LayeredSocketFactory) Socket(java.net.Socket) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) ConnectException(java.net.ConnectException)

Example 63 with Socket

use of java.net.Socket in project robovm by robovm.

the class DefaultClientConnectionOperator method openConnection.

// non-javadoc, see interface ClientConnectionOperator
public void openConnection(OperatedClientConnection conn, HttpHost target, InetAddress local, HttpContext context, HttpParams params) throws IOException {
    if (conn == null) {
        throw new IllegalArgumentException("Connection must not be null.");
    }
    if (target == null) {
        throw new IllegalArgumentException("Target host must not be null.");
    }
    //@@@ is context allowed to be null?
    if (params == null) {
        throw new IllegalArgumentException("Parameters must not be null.");
    }
    if (conn.isOpen()) {
        throw new IllegalArgumentException("Connection must not be open.");
    }
    final Scheme schm = schemeRegistry.getScheme(target.getSchemeName());
    final SocketFactory sf = schm.getSocketFactory();
    final SocketFactory plain_sf;
    final LayeredSocketFactory layered_sf;
    if (sf instanceof LayeredSocketFactory) {
        plain_sf = staticPlainSocketFactory;
        layered_sf = (LayeredSocketFactory) sf;
    } else {
        plain_sf = sf;
        layered_sf = null;
    }
    InetAddress[] addresses = InetAddress.getAllByName(target.getHostName());
    for (int i = 0; i < addresses.length; ++i) {
        Socket sock = plain_sf.createSocket();
        conn.opening(sock, target);
        try {
            Socket connsock = plain_sf.connectSocket(sock, addresses[i].getHostAddress(), schm.resolvePort(target.getPort()), local, 0, params);
            if (sock != connsock) {
                sock = connsock;
                conn.opening(sock, target);
            }
            /*
                 * prepareSocket is called on the just connected
                 * socket before the creation of the layered socket to
                 * ensure that desired socket options such as
                 * TCP_NODELAY, SO_RCVTIMEO, SO_LINGER will be set
                 * before any I/O is performed on the socket. This
                 * happens in the common case as
                 * SSLSocketFactory.createSocket performs hostname
                 * verification which requires that SSL handshaking be
                 * performed.
                 */
            prepareSocket(sock, context, params);
            if (layered_sf != null) {
                Socket layeredsock = layered_sf.createSocket(sock, target.getHostName(), schm.resolvePort(target.getPort()), true);
                if (layeredsock != sock) {
                    conn.opening(layeredsock, target);
                }
                conn.openCompleted(sf.isSecure(layeredsock), params);
            } else {
                conn.openCompleted(sf.isSecure(sock), params);
            }
            break;
        // BEGIN android-changed
        //       catch SocketException to cover any kind of connect failure
        } catch (SocketException ex) {
            if (i == addresses.length - 1) {
                ConnectException cause = ex instanceof ConnectException ? (ConnectException) ex : new ConnectException(ex.getMessage(), ex);
                throw new HttpHostConnectException(target, cause);
            }
        // END android-changed
        } catch (ConnectTimeoutException ex) {
            if (i == addresses.length - 1) {
                throw ex;
            }
        }
    }
}
Also used : SocketException(java.net.SocketException) Scheme(org.apache.http.conn.scheme.Scheme) PlainSocketFactory(org.apache.http.conn.scheme.PlainSocketFactory) LayeredSocketFactory(org.apache.http.conn.scheme.LayeredSocketFactory) SocketFactory(org.apache.http.conn.scheme.SocketFactory) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) LayeredSocketFactory(org.apache.http.conn.scheme.LayeredSocketFactory) InetAddress(java.net.InetAddress) Socket(java.net.Socket) HttpHostConnectException(org.apache.http.conn.HttpHostConnectException) ConnectException(java.net.ConnectException) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 64 with Socket

use of java.net.Socket in project robovm by robovm.

the class SingleClientConnManager method getConnection.

/**
     * Obtains a connection.
     * This method does not block.
     *
     * @param route     where the connection should point to
     *
     * @return  a connection that can be used to communicate
     *          along the given route
     */
public ManagedClientConnection getConnection(HttpRoute route, Object state) {
    if (route == null) {
        throw new IllegalArgumentException("Route may not be null.");
    }
    assertStillUp();
    if (log.isDebugEnabled()) {
        log.debug("Get connection for route " + route);
    }
    if (managedConn != null)
        revokeConnection();
    // check re-usability of the connection
    boolean recreate = false;
    boolean shutdown = false;
    // Kill the connection if it expired.
    closeExpiredConnections();
    if (uniquePoolEntry.connection.isOpen()) {
        RouteTracker tracker = uniquePoolEntry.tracker;
        shutdown = (// can happen if method is aborted
        tracker == null || !tracker.toRoute().equals(route));
    } else {
        // If the connection is not open, create a new PoolEntry,
        // as the connection may have been marked not reusable,
        // due to aborts -- and the PoolEntry should not be reused
        // either.  There's no harm in recreating an entry if
        // the connection is closed.
        recreate = true;
    }
    if (shutdown) {
        recreate = true;
        try {
            uniquePoolEntry.shutdown();
        } catch (IOException iox) {
            log.debug("Problem shutting down connection.", iox);
        }
    }
    if (recreate)
        uniquePoolEntry = new PoolEntry();
    // updated statistics options.
    try {
        final Socket socket = uniquePoolEntry.connection.getSocket();
        if (socket != null) {
            SocketTagger.get().tag(socket);
        }
    } catch (IOException iox) {
        log.debug("Problem tagging socket.", iox);
    }
    // END android-changed
    managedConn = new ConnAdapter(uniquePoolEntry, route);
    return managedConn;
}
Also used : IOException(java.io.IOException) RouteTracker(org.apache.http.conn.routing.RouteTracker) Socket(java.net.Socket)

Example 65 with Socket

use of java.net.Socket in project databus by linkedin.

the class TestUtil method checkServerRunning.

/**
   * Checks if a server is running on a given host and port
   * @param host        the server host
   * @param port        the server port
   * @param log         logger for diagnostic messages (can be null)
   * @return true if successful
   * @throws IOException
   */
public static boolean checkServerRunning(String host, int port, Logger log, boolean logError) {
    boolean success = false;
    try {
        Socket socket = new Socket(host, port);
        log.info("host=" + host + " port=" + port);
        log.info("Socket Info:" + socket.toString());
        log.info("IsConnected=" + socket.isConnected() + " isClosed=" + socket.isClosed() + " isBound=" + socket.isBound());
        success = socket.isConnected();
        socket.close();
    } catch (ConnectException ce) {
        if (null != log)
            log.error("Fail to connect to port:" + port);
        if (logError && null != log)
            log.error("Connect error", ce);
        success = false;
    } catch (IOException e) {
        if (logError && null != log)
            log.error("connect error", e);
    } catch (RuntimeException e) {
        if (logError && null != log)
            log.error("runtime error", e);
    }
    return success;
}
Also used : IOException(java.io.IOException) Socket(java.net.Socket) ConnectException(java.net.ConnectException)

Aggregations

Socket (java.net.Socket)1633 IOException (java.io.IOException)705 ServerSocket (java.net.ServerSocket)578 OutputStream (java.io.OutputStream)377 InetSocketAddress (java.net.InetSocketAddress)367 Test (org.junit.Test)362 InputStream (java.io.InputStream)259 InputStreamReader (java.io.InputStreamReader)179 BufferedReader (java.io.BufferedReader)160 SocketException (java.net.SocketException)137 SSLSocket (javax.net.ssl.SSLSocket)111 SocketTimeoutException (java.net.SocketTimeoutException)97 UnknownHostException (java.net.UnknownHostException)86 ConnectException (java.net.ConnectException)84 InetAddress (java.net.InetAddress)78 ByteArrayOutputStream (java.io.ByteArrayOutputStream)76 OutputStreamWriter (java.io.OutputStreamWriter)70 DataOutputStream (java.io.DataOutputStream)68 ServletOutputStream (javax.servlet.ServletOutputStream)68 CountDownLatch (java.util.concurrent.CountDownLatch)65