Example usage for java.net Socket connect

List of usage examples for java.net Socket connect

Introduction

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

Prototype

public void connect(SocketAddress endpoint, int timeout) throws IOException 

Source Link

Document

Connects this socket to the server with a specified timeout value.

Usage

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

/**
 * ?? ? ? ? ??./*from  w  ww.java  2  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.mobilyzer.util.PhoneUtils.java

/**
 * Using MLab service to detect ipv4 or ipv6 compatibility
 * @param ip_detect_type -- "ipv4" or "ipv6"
 * @return IP_TYPE_CANNOT_DECIDE, IP_TYPE_UNCONNECTIVITY, IP_TYPE_CONNECTIVITY
 *//*from   ww  w.  j a va2s  .  co  m*/
private int checkIPCompatibility(String ip_detect_type) {
    if (!ip_detect_type.equals("ipv4") && !ip_detect_type.equals("ipv6")) {
        return IP_TYPE_CANNOT_DECIDE;
    }
    Socket tcpSocket = new Socket();
    try {
        ArrayList<String> hostnameList = MLabNS.Lookup(context, "mobiperf", ip_detect_type, "ip");
        // MLabNS returns at least one ip address
        if (hostnameList.isEmpty())
            return IP_TYPE_CANNOT_DECIDE;
        // Use the first result in the element
        String hostname = hostnameList.get(0);
        SocketAddress remoteAddr = new InetSocketAddress(hostname, portNum);
        tcpSocket.setTcpNoDelay(true);
        tcpSocket.connect(remoteAddr, tcpTimeout);
    } catch (ConnectException e) {
        // Server is not reachable due to client not support ipv6
        Logger.e("Connection exception is " + e.getMessage());
        return IP_TYPE_UNCONNECTIVITY;
    } catch (IOException e) {
        // Client timer expired
        Logger.e("Fail to setup TCP in checkIPCompatibility(). " + e.getMessage());
        return IP_TYPE_CANNOT_DECIDE;
    } catch (InvalidParameterException e) {
        // MLabNS service lookup fail
        Logger.e("InvalidParameterException in checkIPCompatibility(). " + e.getMessage());
        return IP_TYPE_CANNOT_DECIDE;
    } catch (IllegalArgumentException e) {
        Logger.e("IllegalArgumentException in checkIPCompatibility(). " + e.getMessage());
        return IP_TYPE_CANNOT_DECIDE;
    } finally {
        try {
            tcpSocket.close();
        } catch (IOException e) {
            Logger.e("Fail to close TCP in checkIPCompatibility().");
            return IP_TYPE_CANNOT_DECIDE;
        }
    }
    return IP_TYPE_CONNECTIVITY;
}

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 ww. ja v  a 2s.  com*/

    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: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();//from  www . j a  va  2s .  c  o  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, 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:com.groupon.odo.bmp.http.SimulatedSocketFactory.java

@Override
public Socket connectSocket(Socket sock, InetSocketAddress remoteAddress, InetSocketAddress localAddress,
        HttpParams params) throws IOException {
    if (remoteAddress == null) {
        throw new IllegalArgumentException("Target host may not be null.");
    }//from w  w  w.  j a  va 2  s  . co  m

    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null.");
    }

    if (sock == null) {
        sock = createSocket(null);
    }

    if ((localAddress != null)) {
        sock.bind(localAddress);
    }

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

    InetSocketAddress remoteAddr = remoteAddress;
    // BEGIN ODO CHANGES
    if (this.hostNameResolver != null) {
        // send request to Odo HTTP port
        int port = Utils.getSystemPort(Constants.SYS_HTTP_PORT);
        remoteAddr = new InetSocketAddress(this.hostNameResolver.resolve(hostName), port);
    }
    // END ODO CHANGES

    int timeout = HttpConnectionParams.getConnectionTimeout(params);

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

    return sock;
}

From source file:com.emc.storageos.systemservices.impl.upgrade.CoordinatorClientExt.java

/**
 * Zookeeper leader nodes listens on 2888(see coordinator-var.xml) for follower/observers.
 *  We depends on this behaviour to check if leader election is started
 *
 * @param nodeIP/* w ww. j  a va2s.co  m*/
 * @param port
 * @return
 */
private boolean isZookeeperLeader(String nodeIP, int port) {
    try {
        Socket sock = new Socket();
        sock.connect(new InetSocketAddress(nodeIP, port), 10000); // 10 seconds timeout
        sock.close();
        return true;
    } catch (IOException ex) {
        _log.warn("Unexpected IO errors when checking local coordinator state. {}", ex.toString());
    }
    return false;
}

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  w  w  . j av a  2s.  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:fr.novia.zaproxyplugin.ZAProxy.java

/**
 * Wait for ZAProxy initialization, so it's ready to use at the end of this method
 * (otherwise, catch exception). This method is launched on the remote machine (if there is one)
 *   //from  ww w .  j av a 2s . c  o m
 * @param timeout the time in sec to try to connect at zap proxy. 
 * @param listener the listener to display log during the job execution in jenkins
 * @see <a href="https://groups.google.com/forum/#!topic/zaproxy-develop/gZxYp8Og960">
 *       https://groups.google.com/forum/#!topic/zaproxy-develop/gZxYp8Og960</a>
 */
private void waitForSuccessfulConnectionToZap(int timeout, BuildListener listener) {
    int timeoutInMs = getMilliseconds(timeout);
    int connectionTimeoutInMs = timeoutInMs;
    int pollingIntervalInMs = getMilliseconds(1);
    boolean connectionSuccessful = false;
    long startTime = System.currentTimeMillis();
    Socket socket = null;
    do {
        try {
            socket = new Socket();
            socket.connect(new InetSocketAddress(evaluatedZapProxyHost, evaluatedZapProxyPort),
                    connectionTimeoutInMs);
            connectionSuccessful = true;
        } catch (SocketTimeoutException ignore) {
            listener.error(ExceptionUtils.getStackTrace(ignore));
            throw new BuildException("Unable to connect to ZAP's proxy after " + timeout + " seconds.");

        } catch (IOException ignore) {
            // and keep trying but wait some time first...
            try {
                Thread.sleep(pollingIntervalInMs);
            } catch (InterruptedException e) {
                listener.error(ExceptionUtils.getStackTrace(ignore));
                throw new BuildException("The task was interrupted while sleeping between connection polling.",
                        e);
            }

            long ellapsedTime = System.currentTimeMillis() - startTime;
            if (ellapsedTime >= timeoutInMs) {
                listener.error(ExceptionUtils.getStackTrace(ignore));
                throw new BuildException("Unable to connect to ZAP's proxy after " + timeout + " seconds.");
            }
            connectionTimeoutInMs = (int) (timeoutInMs - ellapsedTime);
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    listener.error(ExceptionUtils.getStackTrace(e));
                }
            }
        }
    } while (!connectionSuccessful);
}

From source file:org.apache.geode.internal.net.SocketCreator.java

/**
 * Return a client socket, timing out if unable to connect and timeout > 0 (millis). The parameter
 * <i>timeout</i> is ignored if SSL is being used, as there is no timeout argument in the ssl
 * socket factory/*from  w  w w.j ava2  s . co m*/
 */
public Socket connect(InetAddress inetadd, int port, int timeout, ConnectionWatcher optionalWatcher,
        boolean clientSide, int socketBufferSize, boolean sslConnection) throws IOException {
    Socket socket = null;
    SocketAddress sockaddr = new InetSocketAddress(inetadd, port);
    printConfig();
    try {
        if (sslConnection) {
            if (this.sslContext == null) {
                throw new GemFireConfigException("SSL not configured correctly, Please look at previous error");
            }
            SocketFactory sf = this.sslContext.getSocketFactory();
            socket = sf.createSocket();

            // Optionally enable SO_KEEPALIVE in the OS network protocol.
            socket.setKeepAlive(ENABLE_TCP_KEEP_ALIVE);

            // If necessary, set the receive buffer size before connecting the
            // socket so that large buffers will be allocated on accepted sockets
            // (see java.net.Socket.setReceiverBufferSize javadocs for details)
            if (socketBufferSize != -1) {
                socket.setReceiveBufferSize(socketBufferSize);
            }

            if (optionalWatcher != null) {
                optionalWatcher.beforeConnect(socket);
            }
            socket.connect(sockaddr, Math.max(timeout, 0));
            configureClientSSLSocket(socket, timeout);
            return socket;
        } else {
            if (clientSide && this.clientSocketFactory != null) {
                socket = this.clientSocketFactory.createSocket(inetadd, port);
            } else {
                socket = new Socket();

                // Optionally enable SO_KEEPALIVE in the OS network protocol.
                socket.setKeepAlive(ENABLE_TCP_KEEP_ALIVE);

                // If necessary, set the receive buffer size before connecting the
                // socket so that large buffers will be allocated on accepted sockets
                // (see java.net.Socket.setReceiverBufferSize javadocs for details)
                if (socketBufferSize != -1) {
                    socket.setReceiveBufferSize(socketBufferSize);
                }

                if (optionalWatcher != null) {
                    optionalWatcher.beforeConnect(socket);
                }
                socket.connect(sockaddr, Math.max(timeout, 0));
            }
            return socket;
        }
    } finally {
        if (optionalWatcher != null) {
            optionalWatcher.afterConnect(socket);
        }
    }
}