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.datanode.TestDataNodeVolumeFailure.java

/**
 * try to access a block on a data node. If fails - throws exception
 * @param datanode//from w  ww  . j  a v  a  2  s.c  o m
 * @param lblock
 * @throws IOException
 */
private void accessBlock(DatanodeInfo datanode, LocatedBlock lblock) throws IOException {
    InetSocketAddress targetAddr = null;
    Socket s = null;
    ExtendedBlock block = lblock.getBlock();

    targetAddr = NetUtils.createSocketAddr(datanode.getName());

    s = new Socket();
    s.connect(targetAddr, HdfsServerConstants.READ_TIMEOUT);
    s.setSoTimeout(HdfsServerConstants.READ_TIMEOUT);

    String file = BlockReaderFactory.getFileName(targetAddr, "test-blockpoolid", block.getBlockId());
    BlockReader blockReader = BlockReaderFactory.newBlockReader(s, file, block, lblock.getBlockToken(), 0, -1,
            4096);

    // nothing - if it fails - it will throw and exception
}

From source file:com.owncloud.android.network.AdvancedSslSocketFactory.java

/**
 * Attempts to get a new socket connection to the given host within the
 * given time limit.// ww  w. j  a  v  a 2 s.  com
 * 
 * @param host the host name/IP
 * @param port the port on the host
 * @param clientHost the local host name/IP to bind the socket to
 * @param clientPort the port on the local machine
 * @param params {@link HttpConnectionParams Http connection parameters}
 * 
 * @return Socket a new socket
 * 
 * @throws IOException if an I/O error occurs while creating the socket
 * @throws UnknownHostException if the IP address of the host cannot be
 *             determined
 */
public Socket createSocket(final String host, final int port, final InetAddress localAddress,
        final int localPort, final HttpConnectionParams params)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    Log_OC.d(TAG, "Creating SSL Socket with remote " + host + ":" + port + ", local " + localAddress + ":"
            + localPort + ", params: " + params);
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null");
    }
    int timeout = params.getConnectionTimeout();
    SocketFactory socketfactory = mSslContext.getSocketFactory();
    Log_OC.d(TAG, " ... with connection timeout " + timeout + " and socket timeout " + params.getSoTimeout());
    Socket socket = socketfactory.createSocket();
    SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
    SocketAddress remoteaddr = new InetSocketAddress(host, port);
    socket.setSoTimeout(params.getSoTimeout());
    socket.bind(localaddr);
    socket.connect(remoteaddr, timeout);
    verifyPeerIdentity(host, port, socket);
    return socket;
}

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

private void sendRecvData(String testDescription, boolean eofExpected) throws IOException {
    /* Opens a socket to datanode
     * sends the data in sendBuf.//from   www .j av a 2 s  .  c o m
     * If there is data in expectedBuf, expects to receive the data
     *     from datanode that matches expectedBuf.
     * If there is an exception while recieving, throws it
     *     only if exceptionExcepted is false.
     */

    Socket sock = null;
    try {

        if (testDescription != null) {
            LOG.info("Testing : " + testDescription);
        }
        sock = new Socket();
        sock.connect(dnAddr, FSConstants.READ_TIMEOUT);
        sock.setSoTimeout(FSConstants.READ_TIMEOUT);

        OutputStream out = sock.getOutputStream();
        // Should we excuse 
        byte[] retBuf = new byte[recvBuf.size()];

        DataInputStream in = new DataInputStream(sock.getInputStream());
        out.write(sendBuf.toByteArray());
        try {
            in.readFully(retBuf);
        } catch (EOFException eof) {
            if (eofExpected) {
                LOG.info("Got EOF as expected.");
                return;
            }
            throw eof;
        }
        for (int i = 0; i < retBuf.length; i++) {
            System.out.print(retBuf[i]);
        }
        System.out.println(":");

        if (eofExpected) {
            throw new IOException("Did not recieve IOException when an exception "
                    + "is expected while reading from " + datanode.getName());
        }

        byte[] needed = recvBuf.toByteArray();
        for (int i = 0; i < retBuf.length; i++) {
            System.out.print(retBuf[i]);
            assertEquals("checking byte[" + i + "]", needed[i], retBuf[i]);
        }
    } finally {
        IOUtils.closeSocket(sock);
    }
}

From source file:hd3gtv.as5kpc.Serverchannel.java

private Socket connect() throws IOException {
    Socket socket = new Socket();
    socket.setKeepAlive(false);/*  w ww .j  a  v  a2s .  c o  m*/
    socket.connect(new InetSocketAddress(server, port), 4000);
    return socket;
}

From source file:org.opennms.netmgt.provision.detector.msexchange.client.MSExchangeDetectorClient.java

private String connectAndGetResponse(final InetAddress address, final Integer port, final int timeout) {
    Socket socket = null;
    InputStreamReader isr = null;
    BufferedReader lineRdr = null;

    if (port != null) {
        try {//  w w  w . j  a va  2s. c  o  m
            socket = new Socket();
            final InetSocketAddress inetSocketAddress = new InetSocketAddress(address, port.intValue());
            socket.connect(inetSocketAddress, timeout);
            socket.setSoTimeout(timeout);

            // Allocate a line reader
            isr = new InputStreamReader(socket.getInputStream());
            lineRdr = new BufferedReader(isr);

            // Read the banner line and see if it contains the
            // substring "Microsoft Exchange"
            //
            final String banner = lineRdr.readLine();

            socket.close();
            return banner;

        } catch (final Exception e) {
            LOG.debug("An error occurred while connecting to {}:{}", InetAddressUtils.str(address), port, e);
            IOUtils.closeQuietly(lineRdr);
            IOUtils.closeQuietly(isr);
            if (socket != null) {
                try {
                    socket.close();
                } catch (final IOException e1) {
                    LOG.debug("Additionally, an exception occurred while trying to close the socket.", e);
                }
            }
        }
    }
    return null;
}

From source file:com.mgmtp.perfload.core.client.web.ssl.LtSSLSocketFactory.java

@Override
public Socket connectSocket(final Socket sock, final InetSocketAddress remoteAddress,
        final InetSocketAddress localAddress, final HttpParams params) throws IOException {
    checkArgument(remoteAddress != null, "Remote address may not be null");
    checkArgument(params != null, "HTTP parameters may not be null");

    Socket socket = sock != null ? sock : new Socket();
    if (localAddress != null) {
        socket.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params));
        socket.bind(localAddress);//from   ww  w .ja v a 2s.c  om
    }

    socket.setSoTimeout(HttpConnectionParams.getSoTimeout(params));
    socket.connect(remoteAddress, HttpConnectionParams.getConnectionTimeout(params));

    if (socket instanceof SSLSocket) {
        return socket;
    }

    return getSSLContext().getSocketFactory().createSocket(socket, remoteAddress.getHostName(),
            remoteAddress.getPort(), true);
}

From source file:com.jaspersoft.ireport.jasperserver.ws.IReportSSLSocketFactory.java

/**
        /*from ww w.  ja v  a 2  s  . co  m*/
 * Attempts to get a new socket connection to the given host within the given time limit.
        
 * <p>
        
 * To circumvent the limitations of older JREs that do not support connect timeout a
        
 * controller thread is executed. The controller thread attempts to create a new socket
        
 * within the given limit of time. If socket constructor does not return until the
        
 * timeout expires, the controller terminates and throws an {@link ConnectTimeoutException}
        
 * </p>
        
 *
        
 * @param host the host name/IP
        
 * @param port the port on the host
        
 * @param clientHost the local host name/IP to bind the socket to
        
 * @param clientPort the port on the local machine
        
 * @param params {@link HttpConnectionParams Http connection parameters}
        
 *
        
 * @return Socket a new socket
        
 *
        
 * @throws IOException if an I/O error occurs while creating the socket
        
 * @throws UnknownHostException if the IP address of the host cannot be
        
 * determined
        
 */

public Socket createSocket(

        final String host,

        final int port,

        final InetAddress localAddress,

        final int localPort,

        final HttpConnectionParams params

) throws IOException, UnknownHostException, ConnectTimeoutException {

    if (params == null) {

        throw new IllegalArgumentException("Parameters may not be null");

    }

    int timeout = params.getConnectionTimeout();

    SocketFactory socketfactory = getSSLContext().getSocketFactory();

    if (timeout == 0) {

        return socketfactory.createSocket(host, port, localAddress, localPort);

    } else {

        Socket socket = socketfactory.createSocket();

        SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);

        SocketAddress remoteaddr = new InetSocketAddress(host, port);

        socket.bind(localaddr);

        socket.connect(remoteaddr, timeout);

        return socket;

    }

}

From source file:org.apache.hadoop.hdfs.TestDataTransferProtocol.java

private void sendRecvData(String testDescription, boolean eofExpected) throws IOException {
    /* Opens a socket to datanode
     * sends the data in sendBuf./*from   www . j  ava  2  s .  c om*/
     * If there is data in expectedBuf, expects to receive the data
     *     from datanode that matches expectedBuf.
     * If there is an exception while recieving, throws it
     *     only if exceptionExcepted is false.
     */

    Socket sock = null;
    try {

        if (testDescription != null) {
            LOG.info("Testing : " + testDescription);
        }
        sock = new Socket();
        sock.connect(dnAddr, HdfsConstants.READ_TIMEOUT);
        sock.setSoTimeout(HdfsConstants.READ_TIMEOUT);

        OutputStream out = sock.getOutputStream();
        // Should we excuse 
        byte[] retBuf = new byte[recvBuf.size()];

        DataInputStream in = new DataInputStream(sock.getInputStream());
        out.write(sendBuf.toByteArray());
        try {
            in.readFully(retBuf);
        } catch (EOFException eof) {
            if (eofExpected) {
                LOG.info("Got EOF as expected.");
                return;
            }
            throw eof;
        }
        for (int i = 0; i < retBuf.length; i++) {
            System.out.print(retBuf[i]);
        }
        System.out.println(":");

        if (eofExpected) {
            throw new IOException("Did not recieve IOException when an exception "
                    + "is expected while reading from " + datanode.getName());
        }

        byte[] needed = recvBuf.toByteArray();
        for (int i = 0; i < retBuf.length; i++) {
            System.out.print(retBuf[i]);
            assertEquals("checking byte[" + i + "]", needed[i], retBuf[i]);
        }
    } finally {
        IOUtils.closeSocket(sock);
    }
}

From source file:net.java.sip.communicator.service.httputil.SSLSocketFactoryEx.java

/**
 * @since 4.1// w w w . j a  v a 2  s . c  o  m
 */
@Override
public Socket connectSocket(final Socket socket, final InetSocketAddress remoteAddress,
        final InetSocketAddress localAddress, final HttpParams params)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    if (remoteAddress == null) {
        throw new IllegalArgumentException("Remote address may not be null");
    }
    if (params == null) {
        throw new IllegalArgumentException("HTTP parameters may not be null");
    }
    Socket sock = socket != null ? socket : this.context.getSocketFactory().createSocket();
    if (localAddress != null) {
        sock.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params));
        sock.bind(localAddress);
    }

    int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
    int soTimeout = HttpConnectionParams.getSoTimeout(params);

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

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

    SSLSocket sslsock;
    // Setup SSL layering if necessary
    if (sock instanceof SSLSocket) {
        sslsock = (SSLSocket) sock;
    } else {
        int port = remoteAddress.getPort();
        sslsock = (SSLSocket) this.context.getSocketFactory().createSocket(sock, hostname, port, true);
    }

    return sslsock;
}

From source file:com.klinker.android.twitter.utils.api_helper.TwitterMultipleImageHelper.java

public ArrayList<String> getImageURLs(Status status, Twitter twitter) {

    ArrayList<String> images = TweetLinkUtils.getAllExternalPictures(status);
    try {/* w  w  w .  j  a v a 2  s .  c om*/
        AccessToken token = twitter.getOAuthAccessToken();
        String oauth_token = token.getToken();
        String oauth_token_secret = token.getTokenSecret();

        // generate authorization header
        String get_or_post = "GET";
        String oauth_signature_method = "HMAC-SHA1";

        String uuid_string = UUID.randomUUID().toString();
        uuid_string = uuid_string.replaceAll("-", "");
        String oauth_nonce = uuid_string; // any relatively random alphanumeric string will work here

        // get the timestamp
        Calendar tempcal = Calendar.getInstance();
        long ts = tempcal.getTimeInMillis();// get current time in milliseconds
        String oauth_timestamp = (new Long(ts / 1000)).toString(); // then divide by 1000 to get seconds

        // the parameter string must be in alphabetical order, "text" parameter added at end
        String parameter_string = "oauth_consumer_key=" + AppSettings.TWITTER_CONSUMER_KEY + "&oauth_nonce="
                + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp="
                + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0";

        String twitter_endpoint = "https://api.twitter.com/1.1/statuses/show/" + status.getId() + ".json";
        String twitter_endpoint_host = "api.twitter.com";
        String twitter_endpoint_path = "/1.1/statuses/show/" + status.getId() + ".json";
        String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&"
                + encode(parameter_string);
        String oauth_signature = computeSignature(signature_base_string,
                AppSettings.TWITTER_CONSUMER_SECRET + "&" + encode(oauth_token_secret));

        String authorization_header_string = "OAuth oauth_consumer_key=\"" + AppSettings.TWITTER_CONSUMER_KEY
                + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp
                + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\""
                + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\"";

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        HttpProtocolParams.setUserAgent(params, "HttpCore/1.1");
        HttpProtocolParams.setUseExpectContinue(params, false);
        HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
                // Required protocol interceptors
                new RequestContent(), new RequestTargetHost(),
                // Recommended protocol interceptors
                new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

        HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
        HttpContext context = new BasicHttpContext(null);
        HttpHost host = new HttpHost(twitter_endpoint_host, 443);
        DefaultHttpClientConnection conn = new DefaultHttpClientConnection();

        context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(null, null, null);
        SSLSocketFactory ssf = sslcontext.getSocketFactory();
        Socket socket = ssf.createSocket();
        socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0);
        conn.bind(socket, params);
        BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("GET",
                twitter_endpoint_path);
        request2.setParams(params);
        request2.addHeader("Authorization", authorization_header_string);
        httpexecutor.preProcess(request2, httpproc, context);
        HttpResponse response2 = httpexecutor.execute(request2, conn, context);
        response2.setParams(params);
        httpexecutor.postProcess(response2, httpproc, context);
        String responseBody = EntityUtils.toString(response2.getEntity());
        conn.close();

        JSONObject fullJson = new JSONObject(responseBody);
        JSONObject extendedEntities = fullJson.getJSONObject("extended_entities");
        JSONArray media = extendedEntities.getJSONArray("media");

        Log.v("talon_images", media.toString());

        for (int i = 0; i < media.length(); i++) {
            JSONObject entity = media.getJSONObject(i);
            try {
                // parse through the objects and get the media_url
                String url = entity.getString("media_url");
                String type = entity.getString("type");

                // want to check to make sure it doesn't have it already
                // this also checks to confirm that the entity is in fact a photo
                if (!images.contains(url) && type.equals("photo")) {
                    images.add(url);
                }
            } catch (Exception e) {

            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return images;
}