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.apache.sling.maven.slingstart.run.LauncherCallable.java

public static void stop(final Log LOG, final ProcessDescription cfg) throws Exception {
    boolean isNew = false;

    if (cfg.getProcess() != null || isNew) {
        LOG.info("Stopping Launchpad " + cfg.getId());
        boolean destroy = true;
        final int twoMinutes = 2 * 60 * 1000;
        final File controlPortFile = getControlPortFile(cfg.getDirectory());
        LOG.debug("Control port file " + controlPortFile + " exists: " + controlPortFile.exists());
        if (controlPortFile.exists()) {
            // reading control port
            int controlPort = -1;
            String secretKey = null;
            LineNumberReader lnr = null;
            String serverName = null;
            try {
                lnr = new LineNumberReader(new FileReader(controlPortFile));
                final String portLine = lnr.readLine();
                final int pos = portLine.indexOf(':');
                controlPort = Integer.parseInt(portLine.substring(pos + 1));
                if (pos > 0) {
                    serverName = portLine.substring(0, pos);
                }//from www  . j  a v  a2  s .  c o m
                secretKey = lnr.readLine();
            } catch (final NumberFormatException ignore) {
                // we ignore this
                LOG.debug("Error reading control port file " + controlPortFile, ignore);
            } catch (final IOException ignore) {
                // we ignore this
                LOG.debug("Error reading control port file " + controlPortFile, ignore);
            } finally {
                IOUtils.closeQuietly(lnr);
            }

            if (controlPort != -1) {
                final List<String> hosts = new ArrayList<String>();
                if (serverName != null) {
                    hosts.add(serverName);
                }
                hosts.add("localhost");
                hosts.add("127.0.0.1");
                LOG.debug("Found control port " + controlPort);
                int index = 0;
                while (destroy && index < hosts.size()) {
                    final String hostName = hosts.get(index);

                    Socket clientSocket = null;
                    DataOutputStream out = null;
                    BufferedReader in = null;
                    try {
                        LOG.debug("Trying to connect to " + hostName + ":" + controlPort);
                        clientSocket = new Socket();
                        // set a socket timeout
                        clientSocket.connect(new InetSocketAddress(hostName, controlPort), twoMinutes);
                        // without that, read() call on the InputStream associated with this Socket is infinite
                        clientSocket.setSoTimeout(twoMinutes);

                        LOG.debug(hostName + ":" + controlPort
                                + " connection estabilished, sending the 'stop' command...");

                        out = new DataOutputStream(clientSocket.getOutputStream());
                        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                        if (secretKey != null) {
                            out.writeBytes(secretKey);
                            out.write(' ');
                        }
                        out.writeBytes("stop\n");
                        in.readLine();
                        destroy = false;
                        LOG.debug("'stop' command sent to " + hostName + ":" + controlPort);
                    } catch (final Throwable ignore) {
                        // catch Throwable because InetSocketAddress and Socket#connect throws unchecked exceptions
                        // we ignore this for now
                        LOG.debug("Error sending 'stop' command to " + hostName + ":" + controlPort
                                + " due to: " + ignore.getMessage());
                    } finally {
                        IOUtils.closeQuietly(in);
                        IOUtils.closeQuietly(out);
                        IOUtils.closeQuietly(clientSocket);
                    }
                    index++;
                }
            }
        }
        if (cfg.getProcess() != null) {
            final Process process = cfg.getProcess();

            if (!destroy) {
                // as shutdown might block forever, we use a timeout
                final long now = System.currentTimeMillis();
                final long end = now + twoMinutes;

                LOG.debug("Waiting for process to stop...");

                while (isAlive(process) && (System.currentTimeMillis() < end)) {
                    try {
                        Thread.sleep(2500);
                    } catch (InterruptedException e) {
                        // ignore
                    }
                }
                if (isAlive(process)) {
                    LOG.debug("Process timeout out after 2 minutes");
                    destroy = true;
                } else {
                    LOG.debug("Process stopped");
                }
            }

            if (destroy) {
                LOG.debug("Destroying process...");
                process.destroy();
                LOG.debug("Process destroyed");
            }

            cfg.setProcess(null);
        }
    } else {
        LOG.warn("Launchpad already stopped");
    }
}

From source file:com.smartwork.client.gsocket.CommonSocketFactory.java

public Object makeObject(Object key) throws Exception {
    ServerAddress address = (ServerAddress) key;
    Socket conn = new Socket();
    conn.setSoTimeout(networkConfig.getReadTimeout() * 1000);
    conn.setTcpNoDelay(networkConfig.isTcpNoDelay());
    conn.setReuseAddress(networkConfig.isReuseAddress());
    conn.setSoLinger(networkConfig.getSoLinger() > 0, networkConfig.getSoLinger());
    conn.setSendBufferSize(networkConfig.getSendBufferSize());
    conn.setReceiveBufferSize(networkConfig.getReceiveBufferSize());
    conn.connect(new InetSocketAddress(address.getHost(), address.getPort()),
            networkConfig.getConnectTimeout() * 1000);
    return conn;//  w  ww.  j  av a2 s.  c  o m
}

From source file:org.elasticsearch.hadoop.rest.commonshttp.SocksSocketFactory.java

public Socket createSocket(final String host, final int port, final InetAddress localAddress,
        final int localPort, final HttpConnectionParams params)
        throws IOException, UnknownHostException, ConnectTimeoutException {

    InetSocketAddress socksAddr = new InetSocketAddress(socksHost, socksPort);
    Proxy proxy = new Proxy(Proxy.Type.SOCKS, socksAddr);
    int timeout = params.getConnectionTimeout();

    Socket socket = new Socket(proxy);
    socket.setSoTimeout(timeout);

    SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
    SocketAddress remoteaddr = new InetSocketAddress(host, port);
    socket.bind(localaddr);/*from   ww  w.  j ava 2  s.co m*/
    socket.connect(remoteaddr, timeout);
    return socket;
}

From source file:org.wso2.carbon.databridge.agent.endpoint.binary.BinaryClientPoolFactory.java

@Override
public Object createClient(String protocol, String hostName, int port)
        throws DataEndpointException, DataEndpointAgentConfigurationException {
    if (protocol.equalsIgnoreCase(DataEndpointConfiguration.Protocol.TCP.toString())) {
        int timeout = AgentHolder.getInstance()
                .getDataEndpointAgent(DataEndpointConstants.BINARY_DATA_AGENT_TYPE).getAgentConfiguration()
                .getSocketTimeoutMS();//from  w  w  w  .  j  a  va 2  s  .c o  m
        try {
            Socket socket = new Socket(hostName, port);
            socket.setSoTimeout(timeout);
            return socket;
        } catch (IOException e) {
            throw new DataEndpointException(
                    "Error while opening socket to " + hostName + ":" + port + ". " + e.getMessage(), e);
        }
    } else {
        throw new DataEndpointException("Unsupported protocol: " + protocol + ". Currently only "
                + DataEndpointConfiguration.Protocol.TCP.toString() + " supported.");
    }
}

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

@Override
public SocketOutputStream create(SocketConnectionInfos connectionInfos) throws Exception {
    Socket socket = new Socket();
    socket.setKeepAlive(true);/*from   w w w.  ja va  2 s . c o  m*/
    socket.setSoTimeout(socketTimeoutInMillis);
    socket.connect(new InetSocketAddress(connectionInfos.getHost(), connectionInfos.getPort()),
            socketConnectTimeoutInMillis);

    return new SocketOutputStream(socket);
}

From source file:com.flipkart.phantom.thrift.impl.proxy.SocketObjectFactory.java

/**
 * Interface method implementation. Creates and returns a new {@link java.net.Socket}
 * @see org.apache.commons.pool.PoolableObjectFactory#makeObject()
 *///from   w w w .j av a 2 s  . c  o  m
public Socket makeObject() throws Exception {
    Socket socket = new Socket();
    socket.setSoTimeout(this.getThriftProxy().getThriftTimeoutMillis());
    socket.connect(new InetSocketAddress(this.getThriftProxy().getThriftServer(),
            this.getThriftProxy().getThriftPort()));
    LOGGER.info("Creating a new socket for server : {} at port : {}", this.getThriftProxy().getThriftServer(),
            this.getThriftProxy().getThriftPort());
    return socket;
}

From source file:hudson.plugins.chainreactorclient.ChainReactorInvalidServerException.java

public boolean connect(ChainReactorServer server) {
    try {/*from   w  ww  . ja v a  2s.  co  m*/
        InetSocketAddress sockaddr = server.getSocketAddress();
        Socket sock = new Socket();
        sock.setSoTimeout(2000);
        sock.connect(sockaddr, 2000);
        BufferedReader rd = new BufferedReader(new InputStreamReader(sock.getInputStream()));
        BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
        ensureValidServer(rd);
        logger.println("Connected to chain reactor server");
        sendBuildInfo(wr);
        rd.close();
        wr.close();
        sock.close();
    } catch (UnknownHostException uhe) {
        logError("Failed to resolve host: " + server.getUrl());
    } catch (SocketTimeoutException ste) {
        logError("Time out while trying to connect to " + server.toString());
    } catch (IOException ioe) {
        logError(ioe.getMessage());
    } catch (ChainReactorInvalidServerException crise) {
        logError(crise.getMessage());
    }

    return true;
}

From source file:org.xapek.zs.InsecureSSLProtocolSocketFactory.java

/**
 * {@inheritDoc}/*w  ww  . ja  v  a2  s. com*/
 */
public Socket createSocket(final String host, final int port) throws IOException, UnknownHostException {
    Socket createSocket = context_.getSocketFactory().createSocket(host, port);
    createSocket.setSoTimeout(1);
    return createSocket;
}

From source file:org.xapek.zs.InsecureSSLProtocolSocketFactory.java

/**
 * {@inheritDoc}//from   w  w  w .ja v  a  2 s  .  c  o m
 */
public Socket createSocket(final Socket socket, final String host, final int port, final boolean autoClose)
        throws IOException {
    Socket createSocket = context_.getSocketFactory().createSocket(socket, host, port, autoClose);
    createSocket.setSoTimeout(1);
    return createSocket;
}

From source file:fm.last.moji.tracker.impl.AbstractTrackerFactory.java

public Tracker newTracker(InetSocketAddress newAddress) throws TrackerException {
    log.debug("new {}()", TrackerImpl.class.getSimpleName());
    Tracker tracker = null;/*from   w w  w. jav a  2  s  .c  om*/
    BufferedReader reader = null;
    Writer writer = null;
    Socket socket = null;
    try {
        socket = new Socket(netConfig.getProxy());
        socket.setSoTimeout(netConfig.getTrackerReadTimeout());
        log.debug("Connecting to: {}:", newAddress, socket.getPort());
        socket.connect(newAddress, netConfig.getTrackerConnectTimeout());
        reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        RequestHandler requestHandler = new RequestHandler(writer, reader);
        tracker = new TrackerImpl(socket, requestHandler);
    } catch (IOException e) {
        IOUtils.closeQuietly(reader);
        IOUtils.closeQuietly(writer);
        IOUtils.closeQuietly(socket);
        throw new TrackerException(e);
    }
    return tracker;
}