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.openadaptor.auxil.connector.socket.SocketReadConnector.java

private void doHandshake(Socket socket) {
    /**//  w w  w  .  j  a  v a  2  s.  co  m
     *
     * Do handshaking 
     * The handshaking passes the writer and reader to the delegated handshaker, 
     * This allows the handshaker to control what it sends and gets back as part of the handshake
     * Default handshaker does nothing if unless the handshakeSay / handshakeProgress attributes are set
    */
    OutputStream socketWriter;
    BufferedReader socketReader;
    try {
        socketWriter = socket.getOutputStream();
        socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    } catch (IOException e) {
        throw new ConnectionException(
                "In " + this.getClass().getName() + " doHandShake(socket) " + e.getMessage(), this);
    }

    try {
        int saveReadTimeOut = 0;
        if (gethandshakeTimeoutMs() > 0) {
            saveReadTimeOut = socket.getSoTimeout(); //Save current timeout
            socket.setSoTimeout(gethandshakeTimeoutMs()); //Set specified timeout
        }
        if (isInitiatedConnection()) {
            getSocketHandshake().offerHandshake(socketWriter, socketReader);
        } else {
            getSocketHandshake().acceptHandshake(socketWriter, socketReader);
        }
        if (gethandshakeTimeoutMs() > 0) {
            socket.setSoTimeout(saveReadTimeOut); //Set saved timeout
        }
    } catch (IOException e) {
        throw new ConnectionException(e.getMessage(), this);
    } catch (RuntimeException e) {
        throw new ConnectionException(e.getMessage(), this);
    }
}

From source file:com.sshtools.appframework.ui.SshToolsApplication.java

public void init(String[] args) throws SshToolsApplicationException {
    instance = this;

    boolean listen = isReuseCapable();

    // Do parse 1 of the command line arguments - see if we need to start
    // the daemon
    Options options1 = new Options();
    SshToolsApplication.this.buildCLIOptions(options1);

    pluginManager = new PluginManager();
    try {/*from w  ww  . j ava2  s  . c  o m*/
        initPluginManager(options1);
    } catch (PluginException e1) {
        log(PluginHostContext.LOG_ERROR, "Failed to initialise plugin manager.", e1);
    }

    CommandLineParser parser1 = new PosixParser();
    CommandLine commandLine1;

    try {
        // parse the command line arguments
        commandLine1 = parser1.parse(options1, args);
        if (commandLine1.hasOption("d")) {
            listen = false;
        }

        if (commandLine1.hasOption('r')) {
            reusePort = Integer.parseInt(commandLine1.getOptionValue('r'));
        }
    } catch (Exception e) {
        // Don't care at the moment
    }

    // Try and message the reuse daemon if possible - saves starting another
    // instance
    if (listen) {
        Socket s = null;
        try {
            String hostname = "localhost";
            if (reusePort == -1) {
                reusePort = getDefaultReusePort();
            }
            log.debug("Attempting connection to reuse server on " + hostname + ":" + reusePort);
            s = new Socket(hostname, reusePort);
            log.debug("Found reuse server on " + hostname + ":" + reusePort + ", sending arguments");
            s.setSoTimeout(5000);
            PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
            for (int i = 0; args != null && i < args.length; i++) {
                pw.println(args[i]);
            }
            pw.println();
            BufferedReader r = new BufferedReader(new InputStreamReader(s.getInputStream()));
            log.debug("Waiting for reuse server reply");
            String error = r.readLine();
            log.debug("Reuse server replied with '" + error + "'");
            if (error != null && !error.equals("")) {
                throw new SshToolsApplicationException(error);
            }
            System.exit(0);
        } catch (SshToolsApplicationException t) {
            throw t;
        } catch (SocketException se) {
            log.debug("No reuse server found.");
        } catch (SocketTimeoutException se) {
            log.debug("Reuse server not responding.", se);
        } catch (Exception e) {
            throw new SshToolsApplicationException(e);
        } finally {
            if (s != null) {
                try {
                    s.close();
                } catch (IOException ioe) {
                }
            }
        }
    }

    additionalOptionsTabs = new ArrayList<OptionsTab>();
    log.info("Initialising application");
    File f = getApplicationPreferencesDirectory();
    if (f != null) {
        //
        FilePreferencesFactory.setPreferencesFile(new File(f, "javaprefs.properties"));
        PreferencesStore.init(new File(f, getApplicationName() + ".properties"));
    }
    setLookAndFeel(getDefaultLAF());

    log.debug("Plugin manager initialised, adding global preferences tabs");

    postInitialization();
    addAdditionalOptionsTab(new GlobalOptionsTab(this));

    Options options = new Options();
    buildCLIOptions(options);
    log.debug("Parsing command line");
    CommandLineParser parser = new PosixParser();
    try {
        // parse the command line arguments
        cli = parser.parse(options, args);
        if (cli.hasOption("?")) {
            printHelp(options);
            System.exit(0);
        }
    } catch (Exception e) {
        System.err.println("Invalid option: " + e.getMessage());
        printHelp(options);
        System.exit(1);
    }
    log.debug("Parsed command line");

    if (listen) {
        Thread t = new Thread("RemoteCommandLine") {
            @Override
            public void run() {
                Socket s = null;
                try {
                    reuseServerSocket = new ServerSocket(reusePort, 1);
                    while (true) {
                        s = reuseServerSocket.accept();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
                        String line = null;
                        List<String> args = new ArrayList<String>();
                        while ((line = reader.readLine()) != null && !line.equals("")) {
                            args.add(line);
                        }
                        final PrintWriter pw = new PrintWriter(s.getOutputStream());
                        String[] a = new String[args.size()];
                        args.toArray(a);
                        CommandLineParser parser = new PosixParser();
                        Options options = new Options();
                        buildCLIOptions(options);
                        // parse the command line arguments
                        final CommandLine remoteCLI = parser.parse(options, a);
                        pw.println("");
                        SwingUtilities.invokeAndWait(new Runnable() {
                            public void run() {
                                try {
                                    reuseRequest(remoteCLI);
                                } catch (Throwable t) {
                                    pw.println(t.getMessage());
                                }
                            }
                        });
                        s.close();
                        s = null;
                    }
                } catch (Exception e) {
                    /* DEBUG */e.printStackTrace();
                } finally {
                    if (s != null) {
                        try {
                            s.close();
                        } catch (IOException ioe) {

                        }
                    }
                }
            }
        };
        t.setDaemon(true);
        t.start();
    }
}

From source file:org.apache.hadoop.hdfs.server.namenode.FileSystemProvider.java

/**
 * ?? ? ? ? ??./*ww w.  j av  a2 s .  co m*/
 *
 * @param inetSocketAddress     InetSocketAddress
 * @param blockToken            Token<BlockTokenIdentifier>
 * @param fileSize              FileSize
 * @param startOffset           StartOffset
 * @param chunkSizeToView       ChunkSizeToView
 * @param conf                  Configuration
 * @param fileLocation          FileLocation
 * @param clientName            ClientName
 * @param block                 Block
 * @param verifyChecksum        VerifyChecksum
 * @param peer                  Peer
 * @param datanodeID            DataNodeID
 * @param cachingStrategy       CachingStrategy
 * @return String
 * @throws IOException
 */
public String streamBlockInAscii(InetSocketAddress inetSocketAddress, Token<BlockTokenIdentifier> blockToken,
        long fileSize, long startOffset, long chunkSizeToView, Configuration conf, String fileLocation,
        String clientName, ExtendedBlock block, boolean verifyChecksum, Peer peer, DatanodeID datanodeID,
        CachingStrategy cachingStrategy) throws IOException {
    if (chunkSizeToView == 0) {
        throw new ServiceException("Cannot read chunk size to view.");
    }

    Socket socket = NetUtils.getDefaultSocketFactory(conf).createSocket();
    socket.connect(inetSocketAddress, HdfsServerConstants.READ_TIMEOUT);
    socket.setSoTimeout(HdfsServerConstants.READ_TIMEOUT);

    BlockReader blockReader = RemoteBlockReader2.newBlockReader(fileLocation, block, blockToken, startOffset,
            chunkSizeToView, verifyChecksum, clientName, peer, datanodeID, null, cachingStrategy);

    int amtToRead = (int) Math.min(chunkSizeToView, fileSize);
    final byte[] buf = new byte[amtToRead];
    int readOffset = 0;
    int retires = 2;

    while (amtToRead > 0) {
        int numRead = amtToRead;
        try {
            blockReader.readFully(buf, readOffset, amtToRead);
        } catch (IOException e) {
            retires--;
            if (retires == 0) {
                throw new ServiceException("Could not read data from datanode.");
            }
            continue;
        }
        amtToRead -= numRead;
        readOffset += numRead;
    }

    blockReader.close();
    socket.close();
    return new String(buf);
}

From source file:com.predic8.membrane.core.rules.SSLProxy.java

@Override
public SSLContext getSslInboundContext() {
    return new SSLContext(new SSLParser(), router.getResolverMap(), router.getBaseLocation()) {

        @Override//w  w  w  .  ja  va2s .  c om
        public Socket wrap(Socket socket, byte[] buffer, int position) throws IOException {
            int port = target.getPort();
            if (port == -1)
                port = getPort();

            StreamPump.StreamPumpStats streamPumpStats = router.getStatistics().getStreamPumpStats();
            String protocol = "SSL";

            Connection con = cm.getConnection(target.getHost(), port, connectionConfiguration.getLocalAddr(),
                    null, connectionConfiguration.getTimeout());

            con.out.write(buffer, 0, position);
            con.out.flush();

            String source = socket.getRemoteSocketAddress().toString();
            String dest = con.toString();
            final StreamPump a = new StreamPump(con.in, socket.getOutputStream(), streamPumpStats,
                    protocol + " " + source + " <- " + dest, SSLProxy.this);
            final StreamPump b = new StreamPump(socket.getInputStream(), con.out, streamPumpStats,
                    protocol + " " + source + " -> " + dest, SSLProxy.this);

            socket.setSoTimeout(0);

            String threadName = Thread.currentThread().getName();
            new Thread(a, threadName + " " + protocol + " Backward Thread").start();
            try {
                Thread.currentThread().setName(threadName + " " + protocol + " Onward Thread");
                b.run();
            } finally {
                try {
                    con.close();
                } catch (IOException e) {
                    log.debug("", e);
                }
            }
            throw new SocketException("SSL Forwarding Connection closed.");
        }
    };
}

From source file:com.mirth.connect.connectors.tcp.TcpReceiver.java

private void initSocket(Socket socket) throws SocketException {
    logger.debug("Initializing socket (" + connectorProperties.getName() + " \"Source\" on channel "
            + getChannelId() + ").");
    socket.setReceiveBufferSize(bufferSize);
    socket.setSendBufferSize(bufferSize);
    socket.setSoTimeout(timeout);
    socket.setKeepAlive(connectorProperties.isKeepConnectionOpen());
    socket.setReuseAddress(true);//from   w  w  w .jav  a  2 s  .  co  m
    socket.setTcpNoDelay(true);
}

From source file:com.smartmarmot.dbforbix.config.Config.java

/**
 * Send request to Zabbix Server:/*www .  j av a 2 s. c o m*/
 * @param host - Zabbix Server
 * @param port - Zabbix Server Port
 * @param json - body of request in json format
 * @return - body of response in json format
 */
public String requestZabbix(String host, int port, String json) {
    byte[] response = new byte[2048];
    Socket zabbix = null;
    OutputStreamWriter out = null;
    InputStream in = null;
    byte[] data = null;
    String resp = new String();

    try {
        zabbix = new Socket();
        //TODO socket timeout has to be read from config file
        zabbix.setSoTimeout(30000);

        zabbix.connect(new InetSocketAddress(host, port));
        OutputStream os = zabbix.getOutputStream();

        data = getRequestToZabbixServer(json);

        //send request
        os.write(data);
        os.flush();

        //read response
        in = zabbix.getInputStream();

        //convert response to string (expecting json)
        int pos1 = 13;
        int bRead = 0;
        while (true) {
            bRead = in.read(response);
            //LOG.debug("read="+read+"\nresponse="+new String(response));
            if (bRead <= 0)
                break;
            //remove binary header
            resp += new String(Arrays.copyOfRange(response, pos1, bRead));
            pos1 = 0;
        }
        //LOG.debug("requestZabbix(): resp: "+ resp);
        //resp=resp.substring(13);//remove binary header
        if (resp.isEmpty())
            throw new ZBXBadResponseException("Zabbix Server (" + host + ":" + port
                    + ") has returned empty response for request:\n" + json);

    } catch (ZBXBadResponseException respEx) {
        LOG.error(respEx.getLocalizedMessage());
    } catch (Exception ex) {
        LOG.error("Error getting data from Zabbix server (" + host + ":" + port + "): " + ex.getMessage());
    } finally {
        if (in != null)
            try {
                in.close();
            } catch (IOException e) {
            }
        if (out != null)
            try {
                out.close();
            } catch (IOException e) {
            }
        if (zabbix != null)
            try {
                zabbix.close();
            } catch (IOException e) {
            }
    }

    return resp;
}

From source file:com.groupon.odo.bmp.BrowserMobProxyHandler.java

/**
 * Copied from original SeleniumProxyHandler
 * Changed SslRelay to SslListener and getSslRelayOrCreateNew to getSslRelayOrCreateNewOdo
 * No other changes to the function/*w w w . ja v a 2 s.com*/
 *
 * @param pathInContext
 * @param pathParams
 * @param request
 * @param response
 * @throws HttpException
 * @throws IOException
 */
public void handleConnectOriginal(String pathInContext, String pathParams, HttpRequest request,
        HttpResponse response) throws HttpException, IOException {
    URI uri = request.getURI();

    try {
        LOG.fine("CONNECT: " + uri);
        InetAddrPort addrPort;
        // When logging, we'll attempt to send messages to hosts that don't exist
        if (uri.toString().endsWith(".selenium.doesnotexist:443")) {
            // so we have to do set the host to be localhost (you can't new up an IAP with a non-existent hostname)
            addrPort = new InetAddrPort(443);
        } else {
            addrPort = new InetAddrPort(uri.toString());
        }

        if (isForbidden(HttpMessage.__SSL_SCHEME, addrPort.getHost(), addrPort.getPort(), false)) {
            sendForbid(request, response, uri);
        } else {
            HttpConnection http_connection = request.getHttpConnection();
            http_connection.forceClose();

            HttpServer server = http_connection.getHttpServer();

            SslListener listener = getSslRelayOrCreateNewOdo(uri, addrPort, server);

            int port = listener.getPort();

            // Get the timeout
            int timeoutMs = 30000;
            Object maybesocket = http_connection.getConnection();
            if (maybesocket instanceof Socket) {
                Socket s = (Socket) maybesocket;
                timeoutMs = s.getSoTimeout();
            }

            // Create the tunnel
            HttpTunnel tunnel = newHttpTunnel(request, response, InetAddress.getByName(null), port, timeoutMs);

            if (tunnel != null) {
                // TODO - need to setup semi-busy loop for IE.
                if (_tunnelTimeoutMs > 0) {
                    tunnel.getSocket().setSoTimeout(_tunnelTimeoutMs);
                    if (maybesocket instanceof Socket) {
                        Socket s = (Socket) maybesocket;
                        s.setSoTimeout(_tunnelTimeoutMs);
                    }
                }
                tunnel.setTimeoutMs(timeoutMs);

                customizeConnection(pathInContext, pathParams, request, tunnel.getSocket());
                request.getHttpConnection().setHttpTunnel(tunnel);
                response.setStatus(HttpResponse.__200_OK);
                response.setContentLength(0);
            }
            request.setHandled(true);
        }
    } catch (Exception e) {
        LOG.fine("error during handleConnect", e);
        response.sendError(HttpResponse.__500_Internal_Server_Error, e.toString());
    }
}

From source file:org.openqa.selenium.server.ProxyHandler.java

public void handleConnect(String pathInContext, String pathParams, HttpRequest request, HttpResponse response)
        throws HttpException, IOException {
    URI uri = request.getURI();// ww w .j  a  va2  s .co  m

    try {
        if (log.isDebugEnabled()) {
            log.debug("CONNECT: " + uri);
        }
        InetAddrPort addrPort;
        // When logging, we'll attempt to send messages to hosts that don't exist
        if (uri.toString().endsWith(".selenium.doesnotexist:443")) {
            // so we have to do set the host to be localhost (you can't new up an IAP with a non-existent hostname)
            addrPort = new InetAddrPort(443);
        } else {
            addrPort = new InetAddrPort(uri.toString());
        }

        if (isForbidden(HttpMessage.__SSL_SCHEME, addrPort.getHost(), addrPort.getPort(), false)) {
            sendForbid(request, response, uri);
        } else {
            HttpConnection http_connection = request.getHttpConnection();
            http_connection.forceClose();

            HttpServer server = http_connection.getHttpServer();

            SslRelay listener = getSslRelayOrCreateNew(uri, addrPort, server);

            int port = listener.getPort();

            // Get the timeout
            int timeoutMs = 30000;
            Object maybesocket = http_connection.getConnection();
            if (maybesocket instanceof Socket) {
                Socket s = (Socket) maybesocket;
                timeoutMs = s.getSoTimeout();
            }

            // Create the tunnel
            HttpTunnel tunnel = newHttpTunnel(request, response, InetAddress.getLocalHost(), port, timeoutMs);

            if (tunnel != null) {
                // TODO - need to setup semi-busy loop for IE.
                if (_tunnelTimeoutMs > 0) {
                    tunnel.getSocket().setSoTimeout(_tunnelTimeoutMs);
                    if (maybesocket instanceof Socket) {
                        Socket s = (Socket) maybesocket;
                        s.setSoTimeout(_tunnelTimeoutMs);
                    }
                }
                tunnel.setTimeoutMs(timeoutMs);

                customizeConnection(pathInContext, pathParams, request, tunnel.getSocket());
                request.getHttpConnection().setHttpTunnel(tunnel);
                response.setStatus(HttpResponse.__200_OK);
                response.setContentLength(0);
            }
            request.setHandled(true);
        }
    } catch (Exception e) {
        log.debug("error during handleConnect", e);
        response.sendError(HttpResponse.__500_Internal_Server_Error, e.toString());
    }
}

From source file:org.lockss.proxy.ProxyHandler.java

public void handleConnect(String pathInContext, String pathParams, HttpRequest request, HttpResponse response)
        throws HttpException, IOException {
    URI uri = request.getURI();/*from   w  ww .j a v  a 2  s  .c o m*/

    if (connectHost == null || connectHost.length() == 0 || connectPort <= 0) {
        // Not allowed
        sendForbid(request, response, uri);
        logAccess(request, "forbidden method: " + request.getMethod());
        return;
    }
    try {
        if (isForbidden(HttpMessage.__SSL_SCHEME, false)) {
            sendForbid(request, response, uri);
            logAccess(request, "forbidden scheme for CONNECT: " + HttpMessage.__SSL_SCHEME);
        } else {
            Socket socket = new Socket(connectHost, connectPort);

            // XXX - need to setup semi-busy loop for IE.
            int timeoutMs = 30000;
            if (_tunnelTimeoutMs > 0) {
                socket.setSoTimeout(_tunnelTimeoutMs);
                Object maybesocket = request.getHttpConnection().getConnection();
                try {
                    Socket s = (Socket) maybesocket;
                    timeoutMs = s.getSoTimeout();
                    s.setSoTimeout(_tunnelTimeoutMs);
                } catch (Exception e) {
                    log.warning("Couldn't set socket timeout", e);
                }
            }

            customizeConnection(pathInContext, pathParams, request, socket);
            request.getHttpConnection().setHttpTunnel(new HttpTunnel(socket, timeoutMs));
            logAccess(request, "200 redirected to " + connectHost + ":" + connectPort);

            response.setStatus(HttpResponse.__200_OK);
            response.setContentLength(0);
            request.setHandled(true);
        }
    } catch (Exception e) {
        log.error("Error in CONNECT for " + uri, e);
        response.sendError(HttpResponse.__500_Internal_Server_Error, e.getMessage());
    }

    //     try {
    //       if(jlog.isDebugEnabled())jlog.debug("CONNECT: "+uri);
    //       InetAddrPort addrPort=new InetAddrPort(uri.toString());

    //       if (isForbidden(HttpMessage.__SSL_SCHEME, false)) {
    //    sendForbid(request,response,uri);
    //       } else {
    //    Socket socket =
    //      new Socket(addrPort.getInetAddress(),addrPort.getPort());

    //    // XXX - need to setup semi-busy loop for IE.
    //    int timeoutMs=30000;
    //    if (_tunnelTimeoutMs > 0) {
    //      socket.setSoTimeout(_tunnelTimeoutMs);
    //      Object maybesocket = request.getHttpConnection().getConnection();
    //      try {
    //        Socket s = (Socket) maybesocket;
    //        timeoutMs=s.getSoTimeout();
    //        s.setSoTimeout(_tunnelTimeoutMs);
    //      } catch (Exception e) {
    //        LogSupport.ignore(jlog,e);
    //      }
    //    }

    //    customizeConnection(pathInContext,pathParams,request,socket);
    //    request.getHttpConnection().setHttpTunnel(new HttpTunnel(socket,
    //                          timeoutMs));
    //    response.setStatus(HttpResponse.__200_OK);
    //    response.setContentLength(0);
    //    request.setHandled(true);
    //       }
    //     } catch (Exception e) {
    //       LogSupport.ignore(jlog,e);
    //       response.sendError(HttpResponse.__500_Internal_Server_Error,
    //           e.getMessage());
    //     }
}

From source file:NanoHTTPD.java

/**
 * Start the server./*from w  w  w.j  a  v  a  2 s.  com*/
 *
 * @throws IOException if the socket is in use.
 */
public void start() throws IOException {
    myServerSocket = new ServerSocket();
    myServerSocket
            .bind((hostname != null) ? new InetSocketAddress(hostname, myPort) : new InetSocketAddress(myPort));

    myThread = new Thread(new Runnable() {
        @Override
        public void run() {
            do {
                try {
                    final Socket finalAccept = myServerSocket.accept();
                    registerConnection(finalAccept);
                    finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT);
                    final InputStream inputStream = finalAccept.getInputStream();
                    asyncRunner.exec(new Runnable() {
                        @Override
                        public void run() {
                            OutputStream outputStream = null;
                            try {
                                outputStream = finalAccept.getOutputStream();
                                TempFileManager tempFileManager = tempFileManagerFactory.create();
                                HTTPSession session = new HTTPSession(tempFileManager, inputStream,
                                        outputStream, finalAccept.getInetAddress());
                                while (!finalAccept.isClosed()) {
                                    session.execute();
                                }
                            } catch (Exception e) {
                                // When the socket is closed by the client, we throw our own SocketException
                                // to break the  "keep alive" loop above.
                                if (!(e instanceof SocketException
                                        && "NanoHttpd Shutdown".equals(e.getMessage()))) {
                                    e.printStackTrace();
                                }
                            } finally {
                                safeClose(outputStream);
                                safeClose(inputStream);
                                safeClose(finalAccept);
                                unRegisterConnection(finalAccept);
                            }
                        }
                    });
                } catch (IOException e) {
                }
            } while (!myServerSocket.isClosed());
        }
    });
    myThread.setDaemon(true);
    myThread.setName("NanoHttpd Main Listener");
    myThread.start();
}