Example usage for java.net Socket setSoTimeout

List of usage examples for java.net Socket setSoTimeout

Introduction

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

Prototype

public synchronized void setSoTimeout(int timeout) throws SocketException 

Source Link

Document

Enable/disable SocketOptions#SO_TIMEOUT SO_TIMEOUT with the specified timeout, in milliseconds.

Usage

From source file:org.dcache.srm.client.FlexibleCredentialSSLConnectionSocketFactory.java

@Override
public Socket connectSocket(final int connectTimeout, final Socket socket, final HttpHost host,
        final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpContext context)
        throws IOException {
    Args.notNull(host, "HTTP host");
    Args.notNull(remoteAddress, "Remote address");
    final Socket sock = socket != null ? socket : createSocket(context);
    if (localAddress != null) {
        sock.bind(localAddress);/*from  ww  w .ja  v a 2  s .  c o m*/
    }
    try {
        if (connectTimeout > 0 && sock.getSoTimeout() == 0) {
            sock.setSoTimeout(connectTimeout);
        }
        LOGGER.debug("Connecting socket to {} with timeout {}", remoteAddress, connectTimeout);
        sock.connect(remoteAddress, connectTimeout);
    } catch (final IOException ex) {
        try {
            sock.close();
        } catch (final IOException ignore) {
        }
        throw ex;
    }
    // Setup SSL layering if necessary
    if (sock instanceof SSLSocket) {
        final SSLSocket sslsock = (SSLSocket) sock;
        LOGGER.debug("Starting handshake");
        sslsock.startHandshake();
        verifyHostname(sslsock, host.getHostName());
        return sock;
    } else {
        return createLayeredSocket(sock, host.getHostName(), remoteAddress.getPort(), context);
    }
}

From source file:com.serphacker.serposcope.scraper.http.extensions.ScrapClientSSLConnectionFactory.java

@Override
public Socket connectSocket(final int connectTimeout, final Socket socket, final HttpHost host,
        final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpContext context)
        throws IOException {
    Args.notNull(host, "HTTP host");
    Args.notNull(remoteAddress, "Remote address");
    final Socket sock = socket != null ? socket : createSocket(context);
    if (localAddress != null) {
        sock.bind(localAddress);// ww w .j  a  v  a2  s  . c om
    }
    try {
        if (connectTimeout > 0 && sock.getSoTimeout() == 0) {
            sock.setSoTimeout(connectTimeout);
        }
        if (this.log.isDebugEnabled()) {
            this.log.debug("Connecting socket to " + remoteAddress + " with timeout " + connectTimeout);
        }
        sock.connect(remoteAddress, connectTimeout);
    } catch (final IOException ex) {
        try {
            sock.close();
        } catch (final IOException ignore) {
        }
        throw ex;
    }
    // Setup SSL layering if necessary
    if (sock instanceof SSLSocket) {
        final SSLSocket sslsock = (SSLSocket) sock;
        this.log.debug("Starting handshake");
        sslsock.startHandshake();
        verifyHostname(sslsock, host.getHostName());
        return sock;
    } else {
        return createLayeredSocket(sock, host.getHostName(), remoteAddress.getPort(), context);
    }
}

From source file:net.sbbi.upnp.ServicesEventing.java

/**
 * Unregisters events notifications from a service
 * @param service the service that need to be unregistered
 * @param handler the handler that registered for this service
 * @return true if unregistered false otherwise ( the given handler never registred for the given service )
 * @throws IOException if some IOException error happens during coms with the device
 *///w  w w  .  ja v a2s .  com
public boolean unRegister(UPNPService service, ServiceEventHandler handler) throws IOException {

    URL eventingLoc = service.getEventSubURL();

    if (eventingLoc != null) {

        Subscription sub = lookupSubscriber(service, handler);
        if (sub != null) {
            synchronized (registered) {
                registered.remove(sub);
            }
            if (registered.size() == 0) {
                stopServicesEventingThread();
            }

            StringBuffer packet = new StringBuffer(64);
            packet.append("UNSUBSCRIBE  ").append(eventingLoc.getFile()).append(" HTTP/1.1\r\n");
            packet.append("HOST: ").append(eventingLoc.getHost()).append(":").append(eventingLoc.getPort())
                    .append("\r\n");
            packet.append("SID: ").append(sub.sub.getSID()).append("\r\n\r\n");
            Socket skt = new Socket(eventingLoc.getHost(), eventingLoc.getPort());
            skt.setSoTimeout(30000); // 30 secs timeout according to the specs
            if (log.isDebugEnabled())
                log.debug(packet);
            OutputStream out = skt.getOutputStream();
            out.write(packet.toString().getBytes());
            out.flush();

            InputStream in = skt.getInputStream();
            StringBuffer data = new StringBuffer();
            int readen = 0;
            byte[] buffer = new byte[256];
            while ((readen = in.read(buffer)) != -1) {
                data.append(new String(buffer, 0, readen));
            }
            in.close();
            out.close();
            skt.close();
            if (log.isDebugEnabled())
                log.debug(data.toString());
            if (data.toString().trim().length() > 0) {
                HttpResponse resp = new HttpResponse(data.toString());
                if (resp.getHeader().startsWith("HTTP/1.1 200 OK")) {
                    return true;
                }
            }
        }
    }
    return false;
}

From source file:org.sonatype.nexus.bundle.launcher.support.DefaultNexusBundle.java

/**
 * Starts Nexus.// w w  w . j av  a2  s  .c  om
 * <p/>
 * {@inheritDoc}
 *
 * @since 2.0
 */
@Override
protected void startApplication() {
    try {
        keepAliveThread = new CommandMonitorThread(keepAlivePort, new PingCommand(), new StopMonitorCommand(),
                new ExitCommand(), new HaltCommand());
        keepAliveThread.start();
    } catch (IOException e) {
        throw new RuntimeException("Could not start keep alive thread", e);
    }
    installStopShutdownHook(commandMonitorPort);

    final File nexusDir = getNexusDirectory();

    makeExecutable(nexusDir, "bin/*");

    // log whenever ports are configured to aid solving test port conflicts
    log.info("{} ({}) spawned env [{}={},{}={}]", getName(), getConfiguration().getId(),
            strategy.commandMonitorProperty(), commandMonitorPort, strategy.keepAliveProperty(), keepAlivePort);
    onDirectory(nexusDir).apply(fileTaskBuilder.exec().spawn()
            .script(path("bin/nexus" + (Os.isFamily(Os.FAMILY_WINDOWS) ? ".bat" : ""))).withArgument("start")
            .withEnv(strategy.commandMonitorProperty(), String.valueOf(commandMonitorPort))
            .withEnv(strategy.keepAliveProperty(), String.valueOf(keepAlivePort)));

    if (getConfiguration().isSuspendOnStart()) {
        // verify the debugger socket has been opened and is waiting for a debugger to connect
        // command monitor thread is not started while suspended so this is the best we can do
        final boolean jvmSuspended = new TimedCondition() {
            @Override
            protected boolean isSatisfied() throws Exception {
                Socket socket = new Socket();
                socket.setSoTimeout(5000);
                socket.connect(new InetSocketAddress(getConfiguration().getHostName(),
                        getConfiguration().getDebugPort()));
                return true;
            }
        }.await(Time.seconds(10), Time.seconds(100), Time.seconds(1));
        if (jvmSuspended) {
            log.info("{} ({}) suspended for debugging at {}:{}", getName(), getConfiguration().getId(),
                    getConfiguration().getHostName(), getConfiguration().getDebugPort());
        } else {
            throw new RuntimeException(format("%s (%s) no open socket for debugging at %s:%s within 10 seconds",
                    getName(), getConfiguration().getId(), getConfiguration().getHostName(),
                    getConfiguration().getDebugPort()));
        }
    } else {
        // when not suspending, we expect the internal command monitor thread to start well before bundle is ready
        // so we only give it 10 seconds to be available
        log.info("{} ({}) pinging command monitor at {}:{}", getName(), getConfiguration().getId(),
                getConfiguration().getHostName(), commandMonitorPort);
        final boolean monitorInstalled = new TimedCondition() {
            @Override
            protected boolean isSatisfied() throws Exception {
                // FIXME replace LOCALHOST with getHostName() after making default hostname be 127.0.0.1
                new CommandMonitorTalker(LOCALHOST, commandMonitorPort).send(PingCommand.NAME);
                return true;
            }
        }.await(Time.seconds(10), Time.seconds(100), Time.seconds(1));
        if (monitorInstalled) {
            log.debug("{} ({}) command monitor detected at {}:{}", getName(), getConfiguration().getId(),
                    getConfiguration().getHostName(), commandMonitorPort);
        } else {
            throw new RuntimeException(
                    format("%s (%s) no command monitor detected at %s:%s within 10 seconds", getName(),
                            getConfiguration().getId(), getConfiguration().getHostName(), commandMonitorPort));
        }
    }
}

From source file:net.java.sip.communicator.service.httputil.SSLSocketFactoryEx.java

/**
 * @since 4.1/*www  .jav a2s.c  o m*/
 */
@Override
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 may not be null");
    }
    if (params == null) {
        throw new IllegalArgumentException("HTTP parameters may not be null");
    }
    Socket sock = socket != null ? socket : this.context.getSocketFactory().createSocket();
    if (localAddress != null) {
        sock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params));
        sock.bind(localAddress);
    }

    int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
    int soTimeout = HttpConnectionParams.getSoTimeout(params);

    try {
        sock.setSoTimeout(soTimeout);
        sock.connect(remoteAddress, connTimeout);
    } catch (SocketTimeoutException ex) {
        throw new ConnectTimeoutException("Connect to " + remoteAddress + " timed out");
    }

    String hostname;
    if (remoteAddress instanceof HttpInetSocketAddress) {
        hostname = ((HttpInetSocketAddress) remoteAddress).getHttpHost().getHostName();
    } else {
        hostname = remoteAddress.getHostName();
    }

    SSLSocket sslsock;
    // Setup SSL layering if necessary
    if (sock instanceof SSLSocket) {
        sslsock = (SSLSocket) sock;
    } else {
        int port = remoteAddress.getPort();
        sslsock = (SSLSocket) this.context.getSocketFactory().createSocket(sock, hostname, port, true);
    }

    return sslsock;
}

From source file:net.lightbody.bmp.proxy.jetty.http.SocketListener.java

/** Handle Job.
 * Implementation of ThreadPool.handle(), calls handleConnection.
 * @param socket A Connection./*from  w w  w.ja  va  2  s .  c om*/
 */
public void handleConnection(Socket socket) throws IOException {
    HttpConnection connection = createConnection(socket);

    try {
        if (_lowResourcePersistTimeMs > 0 && isLowOnResources()) {
            socket.setSoTimeout(_lowResourcePersistTimeMs);
            connection.setThrottled(true);
        } else {
            socket.setSoTimeout(getMaxIdleTimeMs());
            connection.setThrottled(false);
        }

    } catch (Exception e) {
        log.warn(LogSupport.EXCEPTION, e);
    }

    connection.handle();
}

From source file:com.epam.reportportal.apache.http.impl.conn.HttpClientConnectionOperator.java

public void connect(final ManagedHttpClientConnection conn, final HttpHost host,
        final InetSocketAddress localAddress, final int connectTimeout, final SocketConfig socketConfig,
        final HttpContext context) throws IOException {
    final Lookup<ConnectionSocketFactory> registry = getSocketFactoryRegistry(context);
    final ConnectionSocketFactory sf = registry.lookup(host.getSchemeName());
    if (sf == null) {
        throw new UnsupportedSchemeException(host.getSchemeName() + " protocol is not supported");
    }/*from   w  ww.j a  va 2s  . c o  m*/
    final InetAddress[] addresses = this.dnsResolver.resolve(host.getHostName());
    final int port = this.schemePortResolver.resolve(host);
    for (int i = 0; i < addresses.length; i++) {
        final InetAddress address = addresses[i];
        final boolean last = i == addresses.length - 1;

        Socket sock = sf.createSocket(context);
        sock.setReuseAddress(socketConfig.isSoReuseAddress());
        conn.bind(sock);

        final InetSocketAddress remoteAddress = new InetSocketAddress(address, port);
        if (this.log.isDebugEnabled()) {
            this.log.debug("Connecting to " + remoteAddress);
        }
        try {
            sock.setSoTimeout(socketConfig.getSoTimeout());
            sock = sf.connectSocket(connectTimeout, sock, host, remoteAddress, localAddress, context);
            sock.setTcpNoDelay(socketConfig.isTcpNoDelay());
            sock.setKeepAlive(socketConfig.isSoKeepAlive());
            final int linger = socketConfig.getSoLinger();
            if (linger >= 0) {
                sock.setSoLinger(linger > 0, linger);
            }
            conn.bind(sock);
            return;
        } catch (final SocketTimeoutException ex) {
            if (last) {
                throw new ConnectTimeoutException(ex, host, addresses);
            }
        } catch (final ConnectException ex) {
            if (last) {
                final String msg = ex.getMessage();
                if ("Connection timed out".equals(msg)) {
                    throw new ConnectTimeoutException(ex, host, addresses);
                } else {
                    throw new HttpHostConnectException(ex, host, addresses);
                }
            }
        }
        if (this.log.isDebugEnabled()) {
            this.log.debug("Connect to " + remoteAddress + " timed out. "
                    + "Connection will be retried using another IP address");
        }
    }
}

From source file:com.owncloud.android.lib.common.network.AdvancedSslSocketFactory.java

/**
  * Attempts to get a new socket connection to the given host within the
  * given time limit./*from  ww w.  ja va 2  s  . c om*/
  * 
  * @param host the host name/IP
  * @param port the port on the host
  * @param clientHost the local host name/IP to bind the socket to
  * @param clientPort 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
  *             determined
  */
public Socket createSocket(final String host, final int port, final InetAddress localAddress,
        final int localPort, final HttpConnectionParams params)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    Log_OC.d(TAG, "Creating SSL Socket with remote " + host + ":" + port + ", local " + localAddress + ":"
            + localPort + ", params: " + params);
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null");
    }
    int timeout = params.getConnectionTimeout();

    //logSslInfo();

    SocketFactory socketfactory = mSslContext.getSocketFactory();
    Log_OC.d(TAG, " ... with connection timeout " + timeout + " and socket timeout " + params.getSoTimeout());
    Socket socket = socketfactory.createSocket();
    enableSecureProtocols(socket);
    SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
    SocketAddress remoteaddr = new InetSocketAddress(host, port);
    socket.setSoTimeout(params.getSoTimeout());
    socket.bind(localaddr);
    ServerNameIndicator.setServerNameIndication(host, (SSLSocket) socket);
    socket.connect(remoteaddr, timeout);
    verifyPeerIdentity(host, port, socket);
    return socket;
}

From source file:net.sbbi.upnp.ServicesEventing.java

/**
 * Register state variable events notification for a device service
 * @param service the service to register with
 * @param handler the registrant object// w  w w  .  j a  v a2  s  .com
 * @param subscriptionDuration subscription time in seconds, -1 for infinite time
 * @return an ServiceEventSubscription object instance containing all the required info or null if no subscription done
 * @throws IOException if some IOException error happens during coms with the device
 */
public ServiceEventSubscription registerEvent(UPNPService service, ServiceEventHandler handler,
        int subscriptionDuration) throws IOException {

    URL eventingLoc = service.getEventSubURL();

    if (eventingLoc != null) {

        if (!inService)
            startServicesEventingThread();
        String duration = Integer.toString(subscriptionDuration);
        if (subscriptionDuration == -1) {
            duration = "infinite";
        }

        Subscription sub = lookupSubscriber(service, handler);
        if (sub != null) {
            // allready registered let's try to unregister it
            unRegister(service, handler);
        }

        StringBuffer packet = new StringBuffer(64);
        packet.append("SUBSCRIBE ").append(eventingLoc.getFile()).append(" HTTP/1.1\r\n");
        packet.append("HOST: ").append(eventingLoc.getHost()).append(":").append(eventingLoc.getPort())
                .append("\r\n");
        packet.append("CALLBACK: <http://").append(InetAddress.getLocalHost().getHostAddress()).append(":")
                .append(daemonPort).append("").append(eventingLoc.getFile()).append(">\r\n");
        packet.append("NT: upnp:event\r\n");
        packet.append("Connection: close\r\n");
        packet.append("TIMEOUT: Second-").append(duration).append("\r\n\r\n");

        Socket skt = new Socket(eventingLoc.getHost(), eventingLoc.getPort());
        skt.setSoTimeout(30000); // 30 secs timeout according to the specs
        if (log.isDebugEnabled())
            log.debug(packet);
        OutputStream out = skt.getOutputStream();
        out.write(packet.toString().getBytes());
        out.flush();

        InputStream in = skt.getInputStream();
        StringBuffer data = new StringBuffer();
        int readen = 0;
        byte[] buffer = new byte[256];
        while ((readen = in.read(buffer)) != -1) {
            data.append(new String(buffer, 0, readen));
        }
        in.close();
        out.close();
        skt.close();
        if (log.isDebugEnabled())
            log.debug(data.toString());
        if (data.toString().trim().length() > 0) {
            HttpResponse resp = new HttpResponse(data.toString());

            if (resp.getHeader().startsWith("HTTP/1.1 200 OK")) {
                String sid = resp.getHTTPHeaderField("SID");
                String actualTimeout = resp.getHTTPHeaderField("TIMEOUT");
                int durationTime = 0;
                // actualTimeout = Second-xxx or Second-infinite
                if (!actualTimeout.equalsIgnoreCase("Second-infinite")) {
                    durationTime = Integer.parseInt(actualTimeout.substring(7));
                }
                sub = new Subscription();
                sub.handler = handler;
                sub.sub = new ServiceEventSubscription(service.getServiceType(), service.getServiceId(),
                        service.getEventSubURL(), sid, skt.getInetAddress(), durationTime);
                synchronized (registered) {
                    registered.add(sub);
                }
                return sub.sub;
            }
        }
    }
    return null;

}

From source file:org.apache.http.impl.conn.HttpClientConnectionOperator.java

public void connect(final ManagedHttpClientConnection conn, final HttpHost host,
        final InetSocketAddress localAddress, final int connectTimeout, final SocketConfig socketConfig,
        final HttpContext context) throws IOException {
    final Lookup<ConnectionSocketFactory> registry = getSocketFactoryRegistry(context);
    final ConnectionSocketFactory sf = registry.lookup(host.getSchemeName());
    if (sf == null) {
        throw new UnsupportedSchemeException(host.getSchemeName() + " protocol is not supported");
    }//from w ww.j a  v a2 s . c  o  m
    final InetAddress[] addresses = this.dnsResolver.resolve(host.getHostName());
    final int port = this.schemePortResolver.resolve(host);
    for (int i = 0; i < addresses.length; i++) {
        final InetAddress address = addresses[i];
        final boolean last = i == addresses.length - 1;

        Socket sock = sf.createSocket(context);
        sock.setReuseAddress(socketConfig.isSoReuseAddress());
        conn.bind(sock);

        final InetSocketAddress remoteAddress = new InetSocketAddress(address, port);
        if (this.log.isDebugEnabled()) {
            this.log.debug("Connecting to " + remoteAddress);
        }
        try {
            sock.setSoTimeout(socketConfig.getSoTimeout());
            sock = sf.connectSocket(connectTimeout, sock, host, remoteAddress, localAddress, context);
            sock.setTcpNoDelay(socketConfig.isTcpNoDelay());
            sock.setKeepAlive(socketConfig.isSoKeepAlive());
            final int linger = socketConfig.getSoLinger();
            if (linger >= 0) {
                sock.setSoLinger(linger > 0, linger);
            }
            conn.bind(sock);
            if (this.log.isDebugEnabled()) {
                this.log.debug("Connection established " + conn);
            }
            return;
        } catch (final SocketTimeoutException ex) {
            if (last) {
                throw new ConnectTimeoutException(ex, host, addresses);
            }
        } catch (final ConnectException ex) {
            if (last) {
                final String msg = ex.getMessage();
                if ("Connection timed out".equals(msg)) {
                    throw new ConnectTimeoutException(ex, host, addresses);
                } else {
                    throw new HttpHostConnectException(ex, host, addresses);
                }
            }
        }
        if (this.log.isDebugEnabled()) {
            this.log.debug("Connect to " + remoteAddress + " timed out. "
                    + "Connection will be retried using another IP address");
        }
    }
}