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.zaproxy.zap.extension.ascanrulesBeta.HeartBleedActiveScanner.java

/** scans the node for the vulnerability */
@Override//  ww w  . ja  v a2  s  .  co  m
public void scan() {

    try {
        // get the network details for the attack
        String hostname = this.getBaseMsg().getRequestHeader().getURI().getHost();
        int portnumber = this.getBaseMsg().getRequestHeader().getURI().getPort();
        // use the default HTTPS port, if the URI did not contain an explicit port number
        // or if the URL was via HTTP, rather than via HTTPS (yes, we will still check it)
        if (portnumber == -1 || portnumber == 80)
            portnumber = 443;

        if (log.isDebugEnabled())
            log.debug("About to look for HeartBleed on " + hostname + ":" + portnumber);
        for (int tlsIndex = 0; tlsIndex < tlsBuffers.length; tlsIndex++) {
            if (log.isDebugEnabled())
                log.debug("-------------------- Trying " + tlsNames[tlsIndex] + " --------------------");

            Socket socket = null;
            OutputStream os = null;
            InputStream is = null;
            try {
                // establish a raw socket connection, without proxying it (the request will
                // definitely not appear in Zap's history tab)
                socket = new Socket();
                try {
                    socket.connect(new InetSocketAddress(hostname, portnumber), this.timeoutMs);
                    if (log.isDebugEnabled())
                        log.debug("Connected");
                    // set a timeout on the socket for reads..
                    socket.setSoTimeout(this.timeoutMs);
                } catch (Exception e) {
                    // we cannot connect at all.. no point in continuing.
                    log.debug("Cannot establish a socket connection to " + hostname + ":" + portnumber
                            + " for HeartBleed");
                    return;
                }

                // get the streams
                os = socket.getOutputStream();
                is = socket.getInputStream();

                // send the client Hello
                // prepare some length info - 3 byte message length, and 2 byte record length
                int messagelen = tlsBuffers[tlsIndex].length + helloBuffer.length;
                int recordlen = messagelen + 4;
                byte[] messageLenBytes = new byte[3];
                messageLenBytes[0] = (byte) (messagelen >> 16);
                messageLenBytes[1] = (byte) (messagelen >> 8);
                messageLenBytes[2] = (byte) (messagelen);
                byte[] recordLenBytes = new byte[2];
                recordLenBytes[0] = (byte) (recordlen >> 8);
                recordLenBytes[1] = (byte) (recordlen);

                // now write the Hello message
                os.write(handshakeRecordByte);
                os.write(tlsBuffers[tlsIndex]);
                os.write(recordLenBytes);
                os.write(handShakeClientHello);
                os.write(messageLenBytes);
                os.write(tlsBuffers[tlsIndex]);
                os.write(helloBuffer);
                if (log.isDebugEnabled())
                    log.debug("Wrote the Client Hello");

                getParent().notifyNewMessage(this);

                // read through messages until we get a handshake message back from the server
                try {
                    while (true) {
                        SSLRecord sslRecord = recvmsg(is, this.timeoutMs);
                        if (sslRecord.typ == handshakeRecordByte && sslRecord.len > 0
                                && sslRecord.pay[0] == 0x0E) {
                            break;
                        }
                        if (log.isDebugEnabled())
                            log.debug(
                                    "Got a reponse from the server, but it was not a server hello 'Done' message");
                    }
                } catch (SocketTimeoutException es) {
                    throw new IOException("The timeout was exceeded while attempting to read the Server Hello");
                } catch (IOException e) {
                    // if we do not get back a server hello, it is because
                    // the server does not support the SSL/TLS variant we passed it.
                    throw new IOException(tlsNames[tlsIndex]
                            + " is not supported by the server, or a common cipher suite could not be agreed");
                }

                if (log.isDebugEnabled())
                    log.debug("Got the Server Hello");

                // all the SSL initialisation is complete.  So is the SSL server vulnerable?
                boolean vulnerable = isVulnerable(is, os, this.timeoutMs, tlsBuffers[tlsIndex]); // put a timeout on the check for each of
                // the TLS variants
                if (vulnerable) {
                    if (log.isDebugEnabled())
                        log.debug("Vulnerable");
                    // bingo!
                    String extraInfo = Constant.messages.getString(MESSAGE_PREFIX + "extrainfo",
                            tlsNames[tlsIndex]);
                    bingo(getRisk(), Alert.CONFIDENCE_MEDIUM, getName(), getDescription(),
                            getBaseMsg().getRequestHeader().getURI().getURI(), "", // param
                            "", // attack
                            extraInfo, getSolution(), "", // evidence
                            getBaseMsg());
                }
                if (is != null)
                    is.close();
                if (os != null)
                    os.close();
                if (socket != null)
                    socket.close();
            } catch (Exception e) {
                // this particular variant is not vulnerable. skip to the next one..
                if (log.isDebugEnabled())
                    log.debug("The SSL server does not appear to be vulnerable, using " + tlsNames[tlsIndex]
                            + ": " + e.getMessage());
            } finally {
                if (log.isDebugEnabled())
                    log.debug("Tidying up");
                if (is != null)
                    is.close();
                if (os != null)
                    os.close();
                if (socket != null)
                    socket.close();
            }
        }
    } catch (Exception e) {
        // needed to catch exceptions from the "finally" statement
        log.error("Error scanning a node for HeartBleed: " + e.getMessage(), e);
    }
}

From source file:fi.iki.elonen.NanoHTTPD.java

/**
 * Start the server.//from  w ww  . j a  va  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();
                    if (inputStream == null) {
                        safeClose(finalAccept);
                        unRegisterConnection(finalAccept);
                    } else {
                        asyncRunner.exec(new Runnable() {
                            @Override
                            public void run() {
                                BufferedInputStream bufferedInputStream = null;
                                OutputStream outputStream = null;
                                try {
                                    bufferedInputStream = new BufferedInputStream(inputStream);
                                    outputStream = finalAccept.getOutputStream();
                                    TempFileManager tempFileManager = tempFileManagerFactory.create();
                                    HTTPSession session = new HTTPSession(tempFileManager, bufferedInputStream,
                                            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(bufferedInputStream);
                                    safeClose(outputStream);
                                    safeClose(finalAccept);
                                    unRegisterConnection(finalAccept);
                                }
                            }
                        });
                    }
                } catch (IOException e) {
                }
            } while (!myServerSocket.isClosed());
        }
    });
    myThread.setDaemon(true);
    myThread.setName("NanoHttpd Main Listener");
    myThread.start();
}

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

private void copyBlock(DFSClient dfs, LocatedBlock lblock, OutputStream fos) throws Exception {
    int failures = 0;
    InetSocketAddress targetAddr = null;
    TreeSet<DatanodeInfo> deadNodes = new TreeSet<DatanodeInfo>();
    Socket s = null;
    DFSClient.BlockReader blockReader = null;
    Block block = lblock.getBlock();/*  w w w.  j a va2 s  .  co  m*/

    while (s == null) {
        DatanodeInfo chosenNode;

        try {
            chosenNode = bestNode(dfs, lblock.getLocations(), deadNodes);
            targetAddr = NetUtils.createSocketAddr(chosenNode.getName());
        } catch (IOException ie) {
            if (failures >= DFSClient.MAX_BLOCK_ACQUIRE_FAILURES) {
                throw new IOException("Could not obtain block " + lblock);
            }
            LOG.info("Could not obtain block from any node:  " + ie);
            try {
                Thread.sleep(10000);
            } catch (InterruptedException iex) {
            }
            deadNodes.clear();
            failures++;
            continue;
        }
        try {
            s = new Socket();
            s.connect(targetAddr, HdfsConstants.READ_TIMEOUT);
            s.setSoTimeout(HdfsConstants.READ_TIMEOUT);

            blockReader = DFSClient.BlockReader.newBlockReader(s,
                    targetAddr.toString() + ":" + block.getBlockId(), block.getBlockId(),
                    lblock.getBlockToken(), block.getGenerationStamp(), 0, -1,
                    conf.getInt("io.file.buffer.size", 4096));

        } catch (IOException ex) {
            // Put chosen node into dead list, continue
            LOG.info("Failed to connect to " + targetAddr + ":" + ex);
            deadNodes.add(chosenNode);
            if (s != null) {
                try {
                    s.close();
                } catch (IOException iex) {
                }
            }
            s = null;
        }
    }
    if (blockReader == null) {
        throw new Exception("Could not open data stream for " + lblock.getBlock());
    }
    byte[] buf = new byte[1024];
    int cnt = 0;
    boolean success = true;
    long bytesRead = 0;
    try {
        while ((cnt = blockReader.read(buf, 0, buf.length)) > 0) {
            fos.write(buf, 0, cnt);
            bytesRead += cnt;
        }
        if (bytesRead != block.getNumBytes()) {
            throw new IOException("Recorded block size is " + block.getNumBytes() + ", but datanode returned "
                    + bytesRead + " bytes");
        }
    } catch (Exception e) {
        e.printStackTrace();
        success = false;
    } finally {
        try {
            s.close();
        } catch (Exception e1) {
        }
    }
    if (!success)
        throw new Exception("Could not copy block data for " + lblock.getBlock());
}

From source file:net.carlh.toast.Client.java

public void start(final String hostName, final int port)
        throws java.net.UnknownHostException, java.io.IOException {

    /* Thread to read stuff from the server */
    readThread = new Thread(new Runnable() {

        private byte[] getData(Socket socket, int length) {
            byte[] d = new byte[length];
            int offset = 0;
            while (offset < length) {
                try {
                    int t = socket.getInputStream().read(d, offset, length - offset);
                    if (t == -1) {
                        break;
                    }/*w ww. j  a  va2  s.  c  o  m*/
                    offset += t;
                } catch (SocketException e) {
                    /* This is probably because the socket has been closed in order to make
                       this thread terminate.
                    */
                    Log.e("Toast", "SocketException in client.getData", e);
                    break;
                } catch (IOException e) {
                    Log.e("Toast", "IOException in Client.getData()", e);
                    break;
                }
            }

            return java.util.Arrays.copyOf(d, offset);
        }

        public void run() {
            while (!stop.get()) {
                try {
                    synchronized (mutex) {
                        /* Connect */
                        socket = new Socket(hostName, port);
                        socket.setSoTimeout(timeout);
                    }

                    /* Keep going until there is a problem on read */

                    while (true) {
                        byte[] b = getData(socket, 4);

                        if (b.length != 4) {
                            break;
                        }

                        int length = ((b[0] & 0xff) << 24) | ((b[1] & 0xff) << 16) | ((b[2] & 0xff) << 8)
                                | (b[3] & 0xff);
                        if (length < 0 || length > (256 * 1024)) {
                            /* Don't like the sound of that */
                            Log.e("Toast", "Strange length " + length);
                            break;
                        }

                        byte[] d = getData(socket, length);

                        if (d.length != length) {
                            break;
                        }

                        try {
                            handler(new JSONObject(new String(d)));
                        } catch (JSONException e) {
                            Log.e("Toast", "Exception " + e.toString());
                        }
                    }

                    synchronized (mutex) {
                        /* Close the socket and go back round to connect again */
                        socket.close();
                        socket = null;
                    }

                } catch (ConnectException e) {
                    Log.e("Toast", "ConnectException");
                } catch (UnknownHostException e) {
                    Log.e("Toast", "UnknownHostException");
                } catch (IOException e) {
                    Log.e("Client", "IOException");
                } finally {
                    try {
                        Thread.sleep(timeout);
                    } catch (java.lang.InterruptedException e) {

                    }
                }
            }
        }
    });

    readThread.start();

    /* Thread to send stuff to the server */
    writeThread = new Thread(new Runnable() {

        public void run() {

            while (!stop.get()) {

                lock.lock();
                try {
                    while (toWrite.size() == 0 && !stop.get()) {
                        writeCondition.await();
                    }
                } catch (InterruptedException e) {

                } finally {
                    lock.unlock();
                }

                String s = null;
                lock.lock();
                if (toWrite.size() > 0) {
                    s = toWrite.get(0);
                    toWrite.remove(0);
                }
                lock.unlock();

                synchronized (mutex) {
                    try {
                        if (socket != null && s != null) {
                            socket.getOutputStream().write((s.length() >> 24) & 0xff);
                            socket.getOutputStream().write((s.length() >> 16) & 0xff);
                            socket.getOutputStream().write((s.length() >> 8) & 0xff);
                            socket.getOutputStream().write((s.length() >> 0) & 0xff);
                            socket.getOutputStream().write(s.getBytes());
                        }
                    } catch (IOException e) {
                        Log.e("Toast", "IOException in write");
                    }
                }
            }
        }
    });

    writeThread.start();

    /* Thread to send pings every so often */
    pingThread = new Thread(new Runnable() {
        public void run() {
            while (!stop.get()) {
                if (ping.get() == true && pong.get() == false) {
                    for (Handler h : handlers) {
                        h.sendEmptyMessage(0);
                    }
                    setConnected(false);
                }
                pong.set(false);
                try {
                    JSONObject json = new JSONObject();
                    json.put("type", "ping");
                    send(json);
                    ping.set(true);
                    Thread.sleep(pingInterval);
                } catch (JSONException e) {
                } catch (InterruptedException e) {
                }

            }
        }
    });

    pingThread.start();
}

From source file:org.apache.hadoop.dfs.NamenodeFsck.java

private void copyBlock(DFSClient dfs, LocatedBlock lblock, OutputStream fos) throws Exception {
    int failures = 0;
    InetSocketAddress targetAddr = null;
    TreeSet<DatanodeInfo> deadNodes = new TreeSet<DatanodeInfo>();
    Socket s = null;
    DFSClient.BlockReader blockReader = null;
    Block block = lblock.getBlock();// w w w. jav a2  s  . c  om

    while (s == null) {
        DatanodeInfo chosenNode;

        try {
            chosenNode = bestNode(dfs, lblock.getLocations(), deadNodes);
            targetAddr = NetUtils.createSocketAddr(chosenNode.getName());
        } catch (IOException ie) {
            if (failures >= DFSClient.MAX_BLOCK_ACQUIRE_FAILURES) {
                throw new IOException("Could not obtain block " + lblock);
            }
            LOG.info("Could not obtain block from any node:  " + ie);
            try {
                Thread.sleep(10000);
            } catch (InterruptedException iex) {
            }
            deadNodes.clear();
            failures++;
            continue;
        }
        try {
            s = new Socket();
            s.connect(targetAddr, FSConstants.READ_TIMEOUT);
            s.setSoTimeout(FSConstants.READ_TIMEOUT);

            blockReader = DFSClient.BlockReader.newBlockReader(s,
                    targetAddr.toString() + ":" + block.getBlockId(), block.getBlockId(),
                    block.getGenerationStamp(), 0, -1, conf.getInt("io.file.buffer.size", 4096));

        } catch (IOException ex) {
            // Put chosen node into dead list, continue
            LOG.info("Failed to connect to " + targetAddr + ":" + ex);
            deadNodes.add(chosenNode);
            if (s != null) {
                try {
                    s.close();
                } catch (IOException iex) {
                }
            }
            s = null;
        }
    }
    if (blockReader == null) {
        throw new Exception("Could not open data stream for " + lblock.getBlock());
    }
    byte[] buf = new byte[1024];
    int cnt = 0;
    boolean success = true;
    long bytesRead = 0;
    try {
        while ((cnt = blockReader.read(buf, 0, buf.length)) > 0) {
            fos.write(buf, 0, cnt);
            bytesRead += cnt;
        }
        if (bytesRead != block.getNumBytes()) {
            throw new IOException("Recorded block size is " + block.getNumBytes() + ", but datanode returned "
                    + bytesRead + " bytes");
        }
    } catch (Exception e) {
        e.printStackTrace();
        success = false;
    } finally {
        try {
            s.close();
        } catch (Exception e1) {
        }
    }
    if (!success)
        throw new Exception("Could not copy block data for " + lblock.getBlock());
}

From source file:SocketFetcher.java

/**
 * This method returns a Socket. Properties control the use of socket
 * factories and other socket characteristics. The properties used are:
 * <p>//from ww w  . j  a  v  a2s . c  o  m
 * <ul>
 * <li> <i>prefix</i>.socketFactory.class
 * <li> <i>prefix</i>.socketFactory.fallback
 * <li> <i>prefix</i>.socketFactory.port
 * <li> <i>prefix</i>.timeout
 * <li> <i>prefix</i>.connectiontimeout
 * <li> <i>prefix</i>.localaddress
 * <li> <i>prefix</i>.localport
 * </ul>
 * <p>
 * If the socketFactory.class property isn't set, the socket returned is an
 * instance of java.net.Socket connected to the given host and port. If the
 * socketFactory.class property is set, it is expected to contain a fully
 * qualified classname of a javax.net.SocketFactory subclass. In this case,
 * the class is dynamically instantiated and a socket created by that
 * SocketFactory is returned.
 * <p>
 * 
 * If the socketFactory.fallback property is set to false, don't fall back to
 * using regular sockets if the socket factory fails.
 * <p>
 * 
 * The socketFactory.port specifies a port to use when connecting through the
 * socket factory. If unset, the port argument will be used.
 * <p>
 * 
 * If the connectiontimeout property is set, we use a separate thread to make
 * the connection so that we can timeout that connection attempt.
 * <p>
 * 
 * If the timeout property is set, it is used to set the socket timeout.
 * <p>
 * 
 * If the localaddress property is set, it's used as the local address to bind
 * to. If the localport property is also set, it's used as the local port
 * number to bind to.
 * 
 * @param host
 *          The host to connect to
 * @param port
 *          The port to connect to at the host
 * @param props
 *          Properties object containing socket properties
 * @param prefix
 *          Property name prefix, e.g., "mail.imap"
 * @param useSSL
 *          use the SSL socket factory as the default
 */
public static Socket getSocket(String host, int port, Properties props, String prefix, boolean useSSL)
        throws IOException {

    if (prefix == null)
        prefix = "socket";
    if (props == null)
        props = new Properties(); // empty
    String s = props.getProperty(prefix + ".connectiontimeout", null);
    int cto = -1;
    if (s != null) {
        try {
            cto = Integer.parseInt(s);
        } catch (NumberFormatException nfex) {
        }
    }

    Socket socket = null;
    String timeout = props.getProperty(prefix + ".timeout", null);
    String localaddrstr = props.getProperty(prefix + ".localaddress", null);
    InetAddress localaddr = null;
    if (localaddrstr != null)
        localaddr = InetAddress.getByName(localaddrstr);
    String localportstr = props.getProperty(prefix + ".localport", null);
    int localport = 0;
    if (localportstr != null) {
        try {
            localport = Integer.parseInt(localportstr);
        } catch (NumberFormatException nfex) {
        }
    }

    boolean fb = false;
    String fallback = props.getProperty(prefix + ".socketFactory.fallback", null);
    fb = fallback == null || (!fallback.equalsIgnoreCase("false"));

    String sfClass = props.getProperty(prefix + ".socketFactory.class", null);
    int sfPort = -1;
    try {
        SocketFactory sf = getSocketFactory(sfClass);
        if (sf != null) {
            String sfPortStr = props.getProperty(prefix + ".socketFactory.port", null);
            if (sfPortStr != null) {
                try {
                    sfPort = Integer.parseInt(sfPortStr);
                } catch (NumberFormatException nfex) {
                }
            }

            // if port passed in via property isn't valid, use param
            if (sfPort == -1)
                sfPort = port;
            socket = createSocket(localaddr, localport, host, sfPort, cto, sf, useSSL);
        }
    } catch (Exception ex) {
        if (!fb) {
            if (ex instanceof InvocationTargetException) {
                Throwable t = ((InvocationTargetException) ex).getTargetException();
                if (t instanceof Exception)
                    ex = (Exception) t;
            }
            if (ex instanceof IOException)
                throw (IOException) ex;
            IOException ioex = new IOException("Couldn't connect using \"" + sfClass
                    + "\" socket factory to host, port: " + host + ", " + sfPort + "; Exception: " + ex);
            throw ioex;
        }
    }

    if (socket == null)
        socket = createSocket(localaddr, localport, host, port, cto, null, useSSL);

    int to = -1;
    if (timeout != null) {
        try {
            to = Integer.parseInt(timeout);
        } catch (NumberFormatException nfex) {
        }
    }
    if (to >= 0)
        socket.setSoTimeout(to);

    configureSSLSocket(socket, props, prefix);
    return socket;
}

From source file:org.apache.jmeter.protocol.tcp.sampler.TCPSampler.java

private Socket getSocket(String socketKey) {
    Map<String, Object> cp = tp.get();
    Socket con = null;
    if (isReUseConnection()) {
        con = (Socket) cp.get(socketKey);
        if (con != null) {
            log.debug(this + " Reusing connection " + con); //$NON-NLS-1$
        }// ww w.j  av  a  2 s.c o  m
    }
    if (con == null) {
        // Not in cache, so create new one and cache it
        try {
            closeSocket(socketKey); // Bug 44910 - close previous socket (if any)
            SocketAddress sockaddr = new InetSocketAddress(getServer(), getPort());
            con = new Socket();
            if (getPropertyAsString(SO_LINGER, "").length() > 0) {
                con.setSoLinger(true, getSoLinger());
            }
            con.connect(sockaddr, getConnectTimeout());
            if (log.isDebugEnabled()) {
                log.debug("Created new connection " + con); //$NON-NLS-1$
            }
            cp.put(socketKey, con);
        } catch (UnknownHostException e) {
            log.warn("Unknown host for " + getLabel(), e);//$NON-NLS-1$
            cp.put(ERRKEY, e.toString());
            return null;
        } catch (IOException e) {
            log.warn("Could not create socket for " + getLabel(), e); //$NON-NLS-1$
            cp.put(ERRKEY, e.toString());
            return null;
        }
    }
    // (re-)Define connection params - Bug 50977 
    try {
        con.setSoTimeout(getTimeout());
        con.setTcpNoDelay(getNoDelay());
        if (log.isDebugEnabled()) {
            log.debug(this + "  Timeout " + getTimeout() + " NoDelay " + getNoDelay()); //$NON-NLS-1$
        }
    } catch (SocketException se) {
        log.warn("Could not set timeout or nodelay for " + getLabel(), se); //$NON-NLS-1$
        cp.put(ERRKEY, se.toString());
    }
    return con;
}

From source file:org.apache.hadoop.hdfs.server.datanode.DWRRDataXceiver.java

@Override
public void replaceBlock(final ExtendedBlock block, final Token<BlockTokenIdentifier> blockToken,
        final String delHint, final DatanodeInfo proxySource) throws IOException {
    updateCurrentThreadName("Replacing block " + block + " from " + delHint);

    /* read header */
    block.setNumBytes(DataXceiverServer.estimateBlockSize);
    if (datanode.isBlockTokenEnabled) {
        try {//from ww  w .  j a va 2s  .  co m
            datanode.blockPoolTokenSecretManager.checkAccess(blockToken, null, block,
                    BlockTokenSecretManager.AccessMode.REPLACE);
        } catch (InvalidToken e) {
            LOG.warn("Invalid access token in request from " + remoteAddress
                    + " for OP_REPLACE_BLOCK for block " + block + " : " + e.getLocalizedMessage());
            sendResponse(ERROR_ACCESS_TOKEN, "Invalid access token");
            return;
        }
    }

    if (!DataXceiverServer.balanceThrottler.acquire()) { // not able to start
        String msg = "Not able to receive block " + block.getBlockId() + " from "
                + peer.getRemoteAddressString() + " because threads " + "quota is exceeded.";
        LOG.warn(msg);
        sendResponse(ERROR, msg);
        return;
    }

    Socket proxySock = null;
    DataOutputStream proxyOut = null;
    Status opStatus = SUCCESS;
    String errMsg = null;
    BlockReceiver blockReceiver = null;
    DataInputStream proxyReply = null;

    try {
        // get the output stream to the proxy
        final String dnAddr = proxySource.getXferAddr(connectToDnViaHostname);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Connecting to datanode " + dnAddr);
        }
        InetSocketAddress proxyAddr = NetUtils.createSocketAddr(dnAddr);
        proxySock = datanode.newSocket();
        NetUtils.connect(proxySock, proxyAddr, dnConf.socketTimeout);
        proxySock.setSoTimeout(dnConf.socketTimeout);

        OutputStream unbufProxyOut = NetUtils.getOutputStream(proxySock, dnConf.socketWriteTimeout);
        InputStream unbufProxyIn = NetUtils.getInputStream(proxySock);
        if (dnConf.encryptDataTransfer
                && !dnConf.trustedChannelResolver.isTrusted(proxySock.getInetAddress())) {
            IOStreamPair encryptedStreams = DataTransferEncryptor.getEncryptedStreams(unbufProxyOut,
                    unbufProxyIn,
                    datanode.blockPoolTokenSecretManager.generateDataEncryptionKey(block.getBlockPoolId()));
            unbufProxyOut = encryptedStreams.out;
            unbufProxyIn = encryptedStreams.in;
        }

        proxyOut = new DataOutputStream(
                new BufferedOutputStream(unbufProxyOut, HdfsConstants.SMALL_BUFFER_SIZE));
        proxyReply = new DataInputStream(
                new BufferedInputStream(unbufProxyIn, HdfsConstants.IO_FILE_BUFFER_SIZE));

        /* send request to the proxy */
        new Sender(proxyOut).copyBlock(block, blockToken);

        // receive the response from the proxy

        BlockOpResponseProto copyResponse = BlockOpResponseProto.parseFrom(PBHelper.vintPrefixed(proxyReply));

        if (copyResponse.getStatus() != SUCCESS) {
            if (copyResponse.getStatus() == ERROR_ACCESS_TOKEN) {
                throw new IOException("Copy block " + block + " from " + proxySock.getRemoteSocketAddress()
                        + " failed due to access token error");
            }
            throw new IOException(
                    "Copy block " + block + " from " + proxySock.getRemoteSocketAddress() + " failed");
        }

        // get checksum info about the block we're copying
        ReadOpChecksumInfoProto checksumInfo = copyResponse.getReadOpChecksumInfo();
        DataChecksum remoteChecksum = DataTransferProtoUtil.fromProto(checksumInfo.getChecksum());
        // open a block receiver and check if the block does not exist
        blockReceiver = new BlockReceiver(block, proxyReply, proxySock.getRemoteSocketAddress().toString(),
                proxySock.getLocalSocketAddress().toString(), null, 0, 0, 0, "", null, datanode, remoteChecksum,
                CachingStrategy.newDropBehind());

        // receive a block
        blockReceiver.receiveBlock(null, null, null, null, DataXceiverServer.balanceThrottler, null);

        // notify name node
        datanode.notifyNamenodeReceivedBlock(block, delHint, blockReceiver.getStorageUuid());

        LOG.info("Moved " + block + " from " + peer.getRemoteAddressString() + ", delHint=" + delHint);

    } catch (IOException ioe) {
        opStatus = ERROR;
        errMsg = "opReplaceBlock " + block + " received exception " + ioe;
        LOG.info(errMsg);
        throw ioe;
    } finally {
        // receive the last byte that indicates the proxy released its thread resource
        if (opStatus == SUCCESS) {
            try {
                proxyReply.readChar();
            } catch (IOException ignored) {
            }
        }

        // now release the thread resource
        DataXceiverServer.balanceThrottler.release();

        // send response back
        try {
            sendResponse(opStatus, errMsg);
        } catch (IOException ioe) {
            LOG.warn("Error writing reply back to " + peer.getRemoteAddressString());
        }
        IOUtils.closeStream(proxyOut);
        IOUtils.closeStream(blockReceiver);
        IOUtils.closeStream(proxyReply);
    }

    //update metrics
    datanode.metrics.addReplaceBlockOp(elapsed());
}

From source file:org.apache.hadoop.hbase.zookeeper.ZooKeeperWrapper.java

/**
 * Gets the statistics from the given server.
 *
 * @param server  The server to get the statistics from.
 * @param timeout  The socket timeout to use.
 * @return The array of response strings.
 * @throws IOException When the socket communication fails.
 *///from  w  ww  . j a va2 s  .  co m
public String[] getServerStats(String server, int timeout) throws IOException {
    String[] sp = server.split(":");
    String host = sp[0];
    int port = sp.length > 1 ? Integer.parseInt(sp[1]) : HConstants.DEFAULT_ZOOKEPER_CLIENT_PORT;

    Socket socket = new Socket();
    InetSocketAddress sockAddr = new InetSocketAddress(host, port);
    socket.connect(sockAddr, timeout);
    socket.setSoTimeout(timeout);

    PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    out.println("stat");
    out.flush();

    ArrayList<String> res = new ArrayList<String>();
    while (true) {
        String line = in.readLine();
        if (line != null)
            res.add(line);
        else
            break;
    }
    socket.close();
    return res.toArray(new String[res.size()]);
}

From source file:SocketFetcher.java

/**
 * This method returns a Socket.  Properties control the use of
 * socket factories and other socket characteristics.  The properties
 * used are: <p>//from  w ww  . ja  va2s. c o m
 * <ul>
 * <li> <i>prefix</i>.socketFactory.class
 * <li> <i>prefix</i>.socketFactory.fallback
 * <li> <i>prefix</i>.socketFactory.port
 * <li> <i>prefix</i>.timeout
 * <li> <i>prefix</i>.connectiontimeout
 * <li> <i>prefix</i>.localaddress
 * <li> <i>prefix</i>.localport
 * </ul> <p>
 * If the socketFactory.class property isn't set, the socket
 * returned is an instance of java.net.Socket connected to the
 * given host and port. If the socketFactory.class property is set,
 * it is expected to contain a fully qualified classname of a
 * javax.net.SocketFactory subclass.  In this case, the class is
 * dynamically instantiated and a socket created by that
 * SocketFactory is returned. <p>
 *
 * If the socketFactory.fallback property is set to false, don't
 * fall back to using regular sockets if the socket factory fails. <p>
 *
 * The socketFactory.port specifies a port to use when connecting
 * through the socket factory.  If unset, the port argument will be
 * used.  <p>
 *
 * If the connectiontimeout property is set, we use a separate thread
 * to make the connection so that we can timeout that connection attempt.
 * <p>
 *
 * If the timeout property is set, it is used to set the socket timeout.
 * <p>
 *
 * If the localaddress property is set, it's used as the local address
 * to bind to.  If the localport property is also set, it's used as the
 * local port number to bind to.
 *
 * @param host The host to connect to
 * @param port The port to connect to at the host
 * @param props Properties object containing socket properties
 * @param prefix Property name prefix, e.g., "mail.imap"
 * @param useSSL use the SSL socket factory as the default
 */
public static Socket getSocket(String host, int port, Properties props, String prefix, boolean useSSL)
        throws IOException {

    if (prefix == null)
        prefix = "socket";
    if (props == null)
        props = new Properties(); // empty
    String s = props.getProperty(prefix + ".connectiontimeout", null);
    int cto = -1;
    if (s != null) {
        try {
            cto = Integer.parseInt(s);
        } catch (NumberFormatException nfex) {
        }
    }

    Socket socket = null;
    String timeout = props.getProperty(prefix + ".timeout", null);
    String localaddrstr = props.getProperty(prefix + ".localaddress", null);
    InetAddress localaddr = null;
    if (localaddrstr != null)
        localaddr = InetAddress.getByName(localaddrstr);
    String localportstr = props.getProperty(prefix + ".localport", null);
    int localport = 0;
    if (localportstr != null) {
        try {
            localport = Integer.parseInt(localportstr);
        } catch (NumberFormatException nfex) {
        }
    }

    boolean fb = false;
    String fallback = props.getProperty(prefix + ".socketFactory.fallback", null);
    fb = fallback == null || (!fallback.equalsIgnoreCase("false"));

    String sfClass = props.getProperty(prefix + ".socketFactory.class", null);
    int sfPort = -1;
    try {
        SocketFactory sf = getSocketFactory(sfClass);
        if (sf != null) {
            String sfPortStr = props.getProperty(prefix + ".socketFactory.port", null);
            if (sfPortStr != null) {
                try {
                    sfPort = Integer.parseInt(sfPortStr);
                } catch (NumberFormatException nfex) {
                }
            }

            // if port passed in via property isn't valid, use param
            if (sfPort == -1)
                sfPort = port;
            socket = createSocket(localaddr, localport, host, sfPort, cto, sf, useSSL);
        }
    } catch (SocketTimeoutException sex) {
        throw sex;
    } catch (Exception ex) {
        if (!fb) {
            if (ex instanceof InvocationTargetException) {
                Throwable t = ((InvocationTargetException) ex).getTargetException();
                if (t instanceof Exception)
                    ex = (Exception) t;
            }
            if (ex instanceof IOException)
                throw (IOException) ex;
            IOException ioex = new IOException("Couldn't connect using \"" + sfClass
                    + "\" socket factory to host, port: " + host + ", " + sfPort + "; Exception: " + ex);
            ioex.initCause(ex);
            throw ioex;
        }
    }

    if (socket == null)
        socket = createSocket(localaddr, localport, host, port, cto, null, useSSL);

    int to = -1;
    if (timeout != null) {
        try {
            to = Integer.parseInt(timeout);
        } catch (NumberFormatException nfex) {
        }
    }
    if (to >= 0)
        socket.setSoTimeout(to);

    configureSSLSocket(socket, props, prefix);
    return socket;
}