Example usage for java.net Socket getSoTimeout

List of usage examples for java.net Socket getSoTimeout

Introduction

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

Prototype

public synchronized int getSoTimeout() throws SocketException 

Source Link

Document

Returns setting for SocketOptions#SO_TIMEOUT SO_TIMEOUT .

Usage

From source file:org.apache.jxtadoop.net.NetUtils.java

/**
 * Same as getInputStream(socket, socket.getSoTimeout()).<br><br>
 * /*from   w  w w . jav  a  2s  . c om*/
 * From documentation for {@link #getInputStream(Socket, long)}:<br>
 * Returns InputStream for the socket. If the socket has an associated
 * SocketChannel then it returns a 
 * {@link SocketInputStream} with the given timeout. If the socket does not
 * have a channel, {@link Socket#getInputStream()} is returned. In the later
 * case, the timeout argument is ignored and the timeout set with 
 * {@link Socket#setSoTimeout(int)} applies for reads.<br><br>
 *
 * Any socket created using socket factories returned by {@link #NetUtils},
 * must use this interface instead of {@link Socket#getInputStream()}.
 *     
 * @see #getInputStream(Socket, long)
 * 
 * @param socket
 * @return InputStream for reading from the socket.
 * @throws IOException
 */
public static InputStream getInputStream(Socket socket) throws IOException {
    // return socket.getInputStream();
    return getInputStream(socket, socket.getSoTimeout());
}

From source file:org.archive.modules.fetcher.FetchFTP.java

/**
 * Fetches a document from an FTP server.
 * /*from   w w  w .  java  2  s  . com*/
 * @param curi      the URI of the document to fetch
 * @param client    the FTPClient to use for the fetch
 * @param recorder  the recorder to preserve the document in
 * @throws IOException  if a network or protocol error occurs
 * @throws InterruptedException  if the thread is interrupted
 */
private void fetch(CrawlURI curi, ClientFTP client, Recorder recorder)
        throws IOException, InterruptedException {
    // Connect to the FTP server.
    UURI uuri = curi.getUURI();
    int port = uuri.getPort();
    if (port == -1) {
        port = 21;
    }

    if (socketFactory == null) {
        socketFactory = new SocketFactoryWithTimeout();
    }
    socketFactory.setConnectTimeoutMs(getSoTimeoutMs());
    client.setSocketFactory(socketFactory);
    client.setConnectTimeout(getSoTimeoutMs());
    client.setDefaultTimeout(getSoTimeoutMs());
    client.setDataTimeout(getSoTimeoutMs());

    client.connect(uuri.getHost(), port);

    client.setSoTimeout(getSoTimeoutMs()); // must be after connect()

    // Authenticate.
    String[] auth = getAuth(curi);
    client.login(auth[0], auth[1]);

    // The given resource may or may not be a directory.
    // To figure out which is which, execute a CD command to
    // the UURI's path.  If CD works, it's a directory.
    boolean isDirectory = client.changeWorkingDirectory(uuri.getPath());

    // Get a data socket.  This will either be the result of a NLST
    // command for a directory, or a RETR command for a file.
    int command;
    String path;
    if (isDirectory) {
        curi.getAnnotations().add("ftpDirectoryList");
        command = FTPCommand.NLST;
        client.setFileType(FTP.ASCII_FILE_TYPE);
        path = ".";
    } else {
        command = FTPCommand.RETR;
        client.setFileType(FTP.BINARY_FILE_TYPE);
        path = uuri.getPath();
    }

    client.enterLocalPassiveMode();
    Socket socket = null;

    try {
        socket = client.openDataConnection(command, path);

        // if "227 Entering Passive Mode" these will get reset later
        curi.setFetchStatus(client.getReplyCode());
        curi.getData().put(A_FTP_FETCH_STATUS, client.getReplyStrings()[0]);
    } catch (IOException e) {
        // try it again, see AbstractFrontier.needsRetrying()
        curi.setFetchStatus(FetchStatusCodes.S_CONNECT_LOST);
    }

    // Save the streams in the CURI, where downstream processors
    // expect to find them.
    if (socket != null) {
        if (socket.getSoTimeout() != getSoTimeoutMs()) {
            logger.warning("data socket timeout " + socket.getSoTimeout() + "ms is not expected value "
                    + getSoTimeoutMs() + "ms");
        }
        // Shall we get a digest on the content downloaded?
        boolean digestContent = getDigestContent();
        String algorithm = null;
        if (digestContent) {
            algorithm = getDigestAlgorithm();
            recorder.getRecordedInput().setDigest(algorithm);
            recorder.getRecordedInput().startDigest();
        } else {
            // clear
            recorder.getRecordedInput().setDigest((MessageDigest) null);
        }

        try {
            saveToRecorder(curi, socket, recorder);
        } finally {
            recorder.close();
            client.closeDataConnection(); // does socket.close()
            curi.setContentSize(recorder.getRecordedInput().getSize());

            // "226 Transfer complete."
            client.getReply();
            curi.setFetchStatus(client.getReplyCode());
            curi.getData().put(A_FTP_FETCH_STATUS, client.getReplyStrings()[0]);

            if (isDirectory) {
                curi.setContentType("text/plain");
            } else {
                curi.setContentType("application/octet-stream");
            }

            if (logger.isLoggable(Level.FINE)) {
                logger.fine("read " + recorder.getRecordedInput().getSize() + " bytes from ftp data socket");
            }

            if (digestContent) {
                curi.setContentDigest(algorithm, recorder.getRecordedInput().getDigestValue());
            }
        }

        if (isDirectory) {
            extract(curi, recorder);
        }
    } else {
        // no data - without this, content size is -1
        curi.setContentSize(0);
    }

    addParent(curi);
}

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 ww  w.  ja  va2 s .  co  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:org.mule.transport.http.HttpServerConnection.java

public HttpServerConnection(final Socket socket, String encoding, HttpConnector connector) throws IOException {
    super();//from  w  w w.j  a va 2s.co  m

    if (socket == null) {
        throw new IllegalArgumentException("Socket may not be null");
    }

    this.socket = socket;

    if (this.socket instanceof SSLSocket) {
        ((SSLSocket) socket).addHandshakeCompletedListener(this);
    }

    setSocketTcpNoDelay();
    this.socket.setKeepAlive(connector.isKeepAlive());

    if (connector.getReceiveBufferSize() != Connector.INT_VALUE_NOT_SET
            && socket.getReceiveBufferSize() != connector.getReceiveBufferSize()) {
        socket.setReceiveBufferSize(connector.getReceiveBufferSize());
    }
    if (connector.getServerSoTimeout() != Connector.INT_VALUE_NOT_SET
            && socket.getSoTimeout() != connector.getServerSoTimeout()) {
        socket.setSoTimeout(connector.getServerSoTimeout());
    }

    this.in = socket.getInputStream();
    this.out = new DataOutputStream(socket.getOutputStream());
    this.encoding = encoding;
}

From source file:org.mule.transport.tcp.TcpConnector.java

public void configureSocket(boolean client, Socket socket) throws SocketException {
    // There is some overhead in setting socket timeout and buffer size, so we're
    // careful here only to set if needed

    if (newValue(getReceiveBufferSize(), socket.getReceiveBufferSize())) {
        socket.setReceiveBufferSize(getReceiveBufferSize());
    }/*  w ww .  j  a v a2s .  co  m*/
    if (newValue(getSendBufferSize(), socket.getSendBufferSize())) {
        socket.setSendBufferSize(getSendBufferSize());
    }
    if (client) {
        if (newValue(getClientSoTimeout(), socket.getSoTimeout())) {
            socket.setSoTimeout(getClientSoTimeout());
        }
    } else {
        if (newValue(getServerSoTimeout(), socket.getSoTimeout())) {
            socket.setSoTimeout(getServerSoTimeout());
        }
    }
    if (newValue(getSocketSoLinger(), socket.getSoLinger())) {
        socket.setSoLinger(true, getSocketSoLinger());
    }
    try {
        socket.setTcpNoDelay(isSendTcpNoDelay());
    } catch (SocketException e) {
        // MULE-2800 - Bug in Solaris
    }
    socket.setKeepAlive(isKeepAlive());
}

From source file:org.openadaptor.auxil.connector.socket.SocketReadConnector.java

private void doHandshake(Socket socket) {
    /**// w ww  .ja  v a  2s .c  o 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:org.openadaptor.auxil.connector.socket.SocketWriteConnector.java

private void getCOMMITResponse(Socket socket) {
    BufferedReader socketReader;/*from  w w  w  . ja  v a 2  s .  c  om*/
    String reply = "";
    int saveReadTimeOut = 0;
    try {
        if (getPseudoTransactionTimeoutMs() > 0) {
            saveReadTimeOut = socket.getSoTimeout(); //Save current timeout
            socket.setSoTimeout(getPseudoTransactionTimeoutMs());
        }
        socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        while (reply.length() == 0) {
            reply = socketReader.readLine();
            log.debug("reply length was: " + reply.length() + " in " + this.getId());
        }
        if (getPseudoTransactionTimeoutMs() > 0) {
            socket.setSoTimeout(saveReadTimeOut); //Set saved timeout
        }
    } catch (IOException e) {
        throw new ComponentException(
                "In " + this.getClass().getName() + " getCOMMITResponse(socket) " + e.getMessage(), this);
    }

    if (reply != null && ("COMMIT".equals(reply) || reply.length() == 0)) {
        log.debug("Received commit response: " + reply + " in " + this.getId());
    } else {
        log.debug("Received commit response: " + reply + " in " + this.getId());
        throw new ComponentException("In " + this.getClass().getName()
                + " getCOMMITResponse(socket) we did not get the expected response.", this);
    }
}

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();/*from w  w  w. jav a  2  s . c o 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());
    }
}