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.opennms.netmgt.poller.monitors.SmtpMonitor.java

/**
 * {@inheritDoc}//  w w  w .  j av  a2 s. c o m
 *
 * <P>
 * Poll the specified address for SMTP service availability.
 * </P>
 *
 * <P>
 * During the poll an attempt is made to connect on the specified port (by
 * default TCP port 25). If the connection request is successful, the banner
 * line generated by the interface is parsed and if the extracted return
 * code indicates that we are talking to an SMTP server we continue. Next,
 * an SMTP 'HELO' command is sent to the interface. Again the response is
 * parsed and a return code extracted and verified. Finally, an SMTP 'QUIT'
 * command is sent. Provided that the interface's response is valid we set
 * the service status to SERVICE_AVAILABLE and return.
 * </P>
 */
@Override
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
    NetworkInterface<InetAddress> iface = svc.getNetInterface();

    // Get interface address from NetworkInterface
    //
    if (iface.getType() != NetworkInterface.TYPE_INET) {
        throw new NetworkInterfaceNotSupportedException(
                "Unsupported interface type, only TYPE_INET currently supported");
    }

    TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);

    int port = ParameterMap.getKeyedInteger(parameters, "port", DEFAULT_PORT);

    // Get interface address from NetworkInterface
    //
    InetAddress ipAddr = iface.getAddress();

    final String hostAddress = InetAddressUtils.str(ipAddr);
    LOG.debug("poll: address = {}, port = {}, {}", hostAddress, port, tracker);

    PollStatus serviceStatus = PollStatus.unavailable();

    for (tracker.reset(); tracker.shouldRetry() && !serviceStatus.isAvailable(); tracker.nextAttempt()) {
        Socket socket = null;
        try {
            // create a connected socket
            //
            tracker.startAttempt();

            socket = new Socket();
            socket.connect(new InetSocketAddress(ipAddr, port), tracker.getConnectionTimeout());
            socket.setSoTimeout(tracker.getSoTimeout());

            LOG.debug("SmtpMonitor: connected to host: {} on port: {}", ipAddr, port);

            // We're connected, so upgrade status to unresponsive
            serviceStatus = PollStatus.unresponsive();
            // Forcing to check for CRLF instead of any other line terminator as per RFC specification
            CRLFLineReader rdr = new CRLFLineReader(new InputStreamReader(socket.getInputStream(), "ASCII"));

            //
            // Tokenize the Banner Line, and check the first
            // line for a valid return.
            //
            String banner = sendMessage(socket, rdr, null);
            LOG.debug("poll: banner = {}", banner);

            StringTokenizer t = new StringTokenizer(banner);
            int rc = Integer.parseInt(t.nextToken());
            if (rc == 220) {
                //
                // Send the HELO command
                //
                String cmd = "HELO " + LOCALHOST_NAME + "\r\n";
                socket.getOutputStream().write(cmd.getBytes());

                //
                // get the returned string, tokenize, and
                // verify the correct output.
                //
                String response = rdr.readLine();
                double responseTime = tracker.elapsedTimeInMillis();

                if (response == null) {
                    continue;
                }

                if (MULTILINE.matcher(response).find()) {
                    // Ok we have a multi-line response...first three
                    // chars of the response line are the return code.
                    // The last line of the response will start with
                    // return code followed by a space.
                    String multiLineRC = new String(response.getBytes("ASCII"), 0, 3, "ASCII");

                    // Create new regExp to look for last line
                    // of this multi line response
                    Pattern endMultiline = null;
                    try {
                        endMultiline = Pattern.compile(multiLineRC);
                    } catch (PatternSyntaxException ex) {
                        throw new java.lang.reflect.UndeclaredThrowableException(ex);
                    }

                    // read until we hit the last line of the multi-line
                    // response
                    do {
                        response = rdr.readLine();
                    } while (response != null && !endMultiline.matcher(response).find());
                    if (response == null) {
                        continue;
                    }
                }

                t = new StringTokenizer(response);
                rc = Integer.parseInt(t.nextToken());
                if (rc == 250) {
                    response = sendMessage(socket, rdr, "QUIT\r\n");

                    t = new StringTokenizer(response);
                    rc = Integer.parseInt(t.nextToken());

                    if (rc == 221) {
                        serviceStatus = PollStatus.available(responseTime);
                    }
                }
            } else if (rc == 554) {
                String response = sendMessage(socket, rdr, "QUIT\r\n");
                serviceStatus = PollStatus.unavailable("Server rejecting transactions with 554");
            }

            // If we get this far and the status has not been set to
            // available, then something didn't verify during the banner
            // checking or HELO/QUIT comand process.
            if (!serviceStatus.isAvailable()) {
                serviceStatus = PollStatus.unavailable(serviceStatus.getReason());
            }
        } catch (NumberFormatException e) {
            String reason = "NumberFormatException while polling address " + hostAddress;
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
        } catch (NoRouteToHostException e) {
            String reason = "No route to host exception for address " + hostAddress;
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
            break; // Break out of for(;;)
        } catch (InterruptedIOException e) {
            String reason = "Did not receive expected response within timeout " + tracker;
            LOG.debug(reason);
            serviceStatus = PollStatus.unavailable(reason);
        } catch (ConnectException e) {
            String reason = "Unable to connect to address " + hostAddress;
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
        } catch (IOException e) {
            String reason = "IOException while polling address " + hostAddress;
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
        } finally {
            try {
                // Close the socket
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
                e.fillInStackTrace();
                LOG.debug("poll: Error closing socket.", e);
            }
        }
    }

    //
    // return the status of the service
    //
    return serviceStatus;
}

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

public String getMediaIds(File[] pics, Twitter twitter) {
    JSONObject jsonresponse = new JSONObject();
    String ids = "";

    for (int i = 0; i < pics.length; i++) {
        File file = pics[i];//from   w w w .java2  s .  co m
        try {
            AccessToken token = twitter.getOAuthAccessToken();
            String oauth_token = token.getToken();
            String oauth_token_secret = token.getTokenSecret();

            // generate authorization header
            String get_or_post = "POST";
            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";
            System.out.println("Twitter.updateStatusWithMedia(): parameter_string=" + parameter_string);

            String twitter_endpoint = "https://upload.twitter.com/1.1/media/upload.json";
            String twitter_endpoint_host = "upload.twitter.com";
            String twitter_endpoint_path = "/1.1/media/upload.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);

            try {
                try {
                    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("POST",
                            twitter_endpoint_path);

                    // need to add status parameter to this POST
                    MultipartEntity reqEntity = new MultipartEntity();

                    FileBody sb_image = new FileBody(file);
                    reqEntity.addPart("media", sb_image);

                    request2.setEntity(reqEntity);
                    request2.setParams(params);

                    request2.addHeader("Authorization", authorization_header_string);
                    System.out.println(
                            "Twitter.updateStatusWithMedia(): Entity, params and header added to request. Preprocessing and executing...");
                    httpexecutor.preProcess(request2, httpproc, context);
                    HttpResponse response2 = httpexecutor.execute(request2, conn, context);
                    System.out.println("Twitter.updateStatusWithMedia(): ... done. Postprocessing...");
                    response2.setParams(params);
                    httpexecutor.postProcess(response2, httpproc, context);
                    String responseBody = EntityUtils.toString(response2.getEntity());
                    System.out.println("Twitter.updateStatusWithMedia(): done. response=" + responseBody);
                    // error checking here. Otherwise, status should be updated.
                    jsonresponse = new JSONObject(responseBody);
                    if (jsonresponse.has("errors")) {
                        JSONObject temp_jo = new JSONObject();
                        temp_jo.put("response_status", "error");
                        temp_jo.put("message",
                                jsonresponse.getJSONArray("errors").getJSONObject(0).getString("message"));
                        temp_jo.put("twitter_code",
                                jsonresponse.getJSONArray("errors").getJSONObject(0).getInt("code"));
                        jsonresponse = temp_jo;
                    }

                    // add it to the media_ids string
                    ids += jsonresponse.getString("media_id_string");
                    if (i != pics.length - 1) {
                        ids += ",";
                    }

                    conn.close();
                } catch (HttpException he) {
                    System.out.println(he.getMessage());
                    jsonresponse.put("response_status", "error");
                    jsonresponse.put("message",
                            "updateStatusWithMedia HttpException message=" + he.getMessage());
                    return null;
                } catch (NoSuchAlgorithmException nsae) {
                    System.out.println(nsae.getMessage());
                    jsonresponse.put("response_status", "error");
                    jsonresponse.put("message",
                            "updateStatusWithMedia NoSuchAlgorithmException message=" + nsae.getMessage());
                    return null;
                } catch (KeyManagementException kme) {
                    System.out.println(kme.getMessage());
                    jsonresponse.put("response_status", "error");
                    jsonresponse.put("message",
                            "updateStatusWithMedia KeyManagementException message=" + kme.getMessage());
                    return null;
                } finally {
                    conn.close();
                }
            } catch (IOException ioe) {
                ioe.printStackTrace();
                jsonresponse.put("response_status", "error");
                jsonresponse.put("message", "updateStatusWithMedia IOException message=" + ioe.getMessage());
                return null;
            }
        } catch (Exception e) {
            return null;
        }

    }
    return ids;
}

From source file:hu.netmind.beankeeper.node.impl.NodeManagerImpl.java

/**
 * Connect to server. This does not need to be synchronized, because it is
 * called from node manager state update, which is synchronized.
 *///from w ww . ja va  2 s.co  m
private Socket connect(String hostips, int hostport) {
    // Cook ips
    try {
        if ("".equals(hostips))
            hostips = InetAddress.getLocalHost().getHostAddress();
    } catch (Exception e) {
        throw new StoreException(
                "can not determine local adapter, but there is another node, which would need to be contacted.",
                e);
    }
    // Connect
    logger.debug("(re)connecting to server: " + hostips + ":" + hostport);
    try {
        // Connect physically
        StringTokenizer tokens = new StringTokenizer(hostips, ",");
        while (tokens.hasMoreTokens()) {
            try {
                String ip = tokens.nextToken();
                Socket socket = new Socket();
                socket.connect(new InetSocketAddress(ip, hostport), SOCKET_CONNECT_TIMEOUT);
                logger.debug("established connection with: " + ip + ", out of " + hostips);
                return socket;
            } catch (Exception e) {
                if (!tokens.hasMoreTokens())
                    throw e; // If no more ips, throw exception
            }
        }
    } catch (StoreException e) {
        throw e;
    } catch (Exception e) {
        throw new StoreException("exception while trying to connect " + hostips + ":" + hostport, e);
    }
    return null;
}

From source file:org.eclipse.ecf.internal.provider.filetransfer.httpclient4.ECFHttpClientSecureProtocolSocketFactory.java

private void performConnection(final Socket socket, final InetSocketAddress remoteAddress,
        final InetSocketAddress localAddress, final HttpParams params) throws SocketException, IOException {
    try {//from  w  w  w  .  j a  v  a 2 s  . com
        socket.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params));
        socket.bind(localAddress);

        int connectionTimeout = HttpConnectionParams.getConnectionTimeout(params);
        int socketTimeout = HttpConnectionParams.getSoTimeout(params);

        socket.connect(remoteAddress, connectionTimeout);
        socket.setSoTimeout(socketTimeout);
    } catch (SocketException e) {
        Trace.catching(Activator.PLUGIN_ID, DebugOptions.EXCEPTIONS_CATCHING,
                ECFHttpClientSecureProtocolSocketFactory.class, "performConnection", e); //$NON-NLS-1$
        fireEvent(this.socketConnectListener, new SocketClosedEvent(source, socket, socket));
        Trace.throwing(Activator.PLUGIN_ID, DebugOptions.EXCEPTIONS_THROWING,
                ECFHttpClientSecureProtocolSocketFactory.class, "performConnection", e); //$NON-NLS-1$
        throw e;
    } catch (IOException e) {
        Trace.catching(Activator.PLUGIN_ID, DebugOptions.EXCEPTIONS_CATCHING,
                ECFHttpClientSecureProtocolSocketFactory.class, "performConnection", e); //$NON-NLS-1$
        fireEvent(this.socketConnectListener, new SocketClosedEvent(source, socket, socket));
        Trace.throwing(Activator.PLUGIN_ID, DebugOptions.EXCEPTIONS_THROWING,
                ECFHttpClientSecureProtocolSocketFactory.class, "performConnection", e); //$NON-NLS-1$
        throw e;
    }
}

From source file:com.clustercontrol.port.protocol.ReachAddressTCP.java

/**
 * ????????????/*from   ww w.j  a v a  2s  .  c o  m*/
 * 
 * @param addressText
 * @return PORT
 */
@Override
protected boolean isRunning(String addressText) {

    m_message = "";
    m_messageOrg = "";
    m_response = -1;

    boolean isReachable = false;

    try {
        long start = 0; // 
        long end = 0; // 

        StringBuffer bufferOrg = new StringBuffer(); // 
        String result = "";

        // Reachability ?? ICMP ??
        boolean retry = true;

        InetAddress address = InetAddress.getByName(addressText);

        bufferOrg.append("Monitoring the port of " + address.getHostName() + "[" + address.getHostAddress()
                + "]:" + m_portNo + ".\n\n");

        // 
        Socket socket = null;

        for (int i = 0; i < m_sentCount && retry; i++) {
            try {
                // ?
                socket = new Socket();
                InetSocketAddress isa = new InetSocketAddress(address, m_portNo);

                bufferOrg.append(HinemosTime.getDateString() + " Tried to Connect: ");
                start = HinemosTime.currentTimeMillis();
                socket.connect(isa, m_timeout);
                end = HinemosTime.currentTimeMillis();

                m_response = end - start;
                if (m_response > 0) {
                    if (m_response < m_timeout) {
                        result = ("Response Time = " + m_response + "ms");
                    } else {
                        m_response = m_timeout;
                        result = ("Response Time = " + m_response + "ms");
                    }
                } else {
                    result = ("Response Time < 1ms");
                }
                retry = false;
                isReachable = true;
            } catch (BindException e) {
                result = (e.getMessage() + "[BindException]");
                retry = true;
                isReachable = false;
            } catch (ConnectException e) {
                result = (e.getMessage() + "[ConnectException]");
                retry = false;
                isReachable = false;
            } catch (NoRouteToHostException e) {
                result = (e.getMessage() + "[NoRouteToHostException]");
                retry = true;
                isReachable = false;
            } catch (PortUnreachableException e) {
                result = (e.getMessage() + "[PortUnreachableException]");
                retry = true;
                isReachable = false;
            } catch (IOException e) {
                result = (e.getMessage() + "[IOException]");
                retry = true;
                isReachable = false;
            } finally {
                bufferOrg.append(result + "\n");
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        m_log.warn("isRunning(): " + "socket close failed: " + e.getMessage(), e);
                    }
                }
            }

            if (i < m_sentCount - 1 && retry) {
                try {
                    Thread.sleep(m_sentInterval);
                } catch (InterruptedException e) {
                    break;
                }
            }
        }

        m_message = result + "(TCP/" + m_portNo + ")";
        m_messageOrg = bufferOrg.toString();
        return isReachable;
    } catch (UnknownHostException e) {
        m_log.debug("isRunning(): " + MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage()
                + e.getMessage());

        m_message = MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage() + " (" + e.getMessage()
                + ")";

        return false;
    }
}

From source file:gov.va.med.imaging.proxy.ssl.AuthSSLProtocolSocketFactory.java

/**
 * Attempts to get a new socket connection to the given host within the
 * given time limit.// ww  w  .ja v  a2 s . c  om
 * <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.dcache.srm.client.FlexibleCredentialSSLConnectionSocketFactory.java

@Override
public Socket connectSocket(final int connectTimeout, final Socket socket, final HttpHost host,
        final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpContext context)
        throws IOException {
    Args.notNull(host, "HTTP host");
    Args.notNull(remoteAddress, "Remote address");
    final Socket sock = socket != null ? socket : createSocket(context);
    if (localAddress != null) {
        sock.bind(localAddress);//from   w  ww  .  j  a  va2  s .com
    }
    try {
        if (connectTimeout > 0 && sock.getSoTimeout() == 0) {
            sock.setSoTimeout(connectTimeout);
        }
        LOGGER.debug("Connecting socket to {} with timeout {}", remoteAddress, connectTimeout);
        sock.connect(remoteAddress, connectTimeout);
    } catch (final IOException ex) {
        try {
            sock.close();
        } catch (final IOException ignore) {
        }
        throw ex;
    }
    // Setup SSL layering if necessary
    if (sock instanceof SSLSocket) {
        final SSLSocket sslsock = (SSLSocket) sock;
        LOGGER.debug("Starting handshake");
        sslsock.startHandshake();
        verifyHostname(sslsock, host.getHostName());
        return sock;
    } else {
        return createLayeredSocket(sock, host.getHostName(), remoteAddress.getPort(), context);
    }
}

From source file:com.eviware.soapui.impl.wsdl.support.http.SoapUISSLSocketFactory.java

/**
 * @since 4.1//w  w  w  .  java  2s .  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 : new Socket();
    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.getHostName() + "/" + remoteAddress.getAddress() + " timed out");
    }
    SSLSocket sslsock;
    // Setup SSL layering if necessary
    if (sock instanceof SSLSocket) {
        sslsock = (SSLSocket) sock;
    } else {
        sslsock = (SSLSocket) getSocketFactory().createSocket(sock, remoteAddress.getHostName(),
                remoteAddress.getPort(), true);
        sslsock = enableSocket(sslsock);
    }
    // do we need it? trust all hosts
    //      if( getHostnameVerifier() != null )
    //      {
    //         try
    //         {
    //            getHostnameVerifier().verify( remoteAddress.getHostName(), sslsock );
    //            // verifyHostName() didn't blowup - good!
    //         }
    //         catch( IOException iox )
    //         {
    //            // close the socket before re-throwing the exception
    //            try
    //            {
    //               sslsock.close();
    //            }
    //            catch( Exception x )
    //            { /* ignore */
    //            }
    //            throw iox;
    //         }
    //      }
    return sslsock;
}

From source file:com.cws.esolutions.core.utils.NetworkUtils.java

/**
 * Creates an telnet connection to a target host and port number. Silently
 * succeeds if no issues are encountered, if so, exceptions are logged and
 * re-thrown back to the requestor.//  w  w  w  .j a  v a2  s  . c  o m
 *
 * If an exception is thrown during the <code>socket.close()</code> operation,
 * it is logged but NOT re-thrown. It's not re-thrown because it does not indicate
 * a connection failure (indeed, it means the connection succeeded) but it is
 * logged because continued failures to close the socket could result in target
 * system instability.
 * 
 * @param hostName - The target host to make the connection to
 * @param portNumber - The port number to attempt the connection on
 * @param timeout - The timeout for the connection
 * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing
 */
public static final synchronized void executeTelnetRequest(final String hostName, final int portNumber,
        final int timeout) throws UtilityException {
    final String methodName = NetworkUtils.CNAME
            + "#executeTelnetRequest(final String hostName, final int portNumber, final int timeout) throws UtilityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug(hostName);
        DEBUGGER.debug("portNumber: {}", portNumber);
        DEBUGGER.debug("timeout: {}", timeout);
    }

    Socket socket = null;

    try {
        synchronized (new Object()) {
            if (InetAddress.getByName(hostName) == null) {
                throw new UnknownHostException("No host was found in DNS for the given name: " + hostName);
            }

            InetSocketAddress socketAddress = new InetSocketAddress(hostName, portNumber);

            socket = new Socket();
            socket.setSoTimeout((int) TimeUnit.SECONDS.toMillis(timeout));
            socket.setSoLinger(false, 0);
            socket.setKeepAlive(false);
            socket.connect(socketAddress, (int) TimeUnit.SECONDS.toMillis(timeout));

            if (!(socket.isConnected())) {
                throw new ConnectException("Failed to connect to host " + hostName + " on port " + portNumber);
            }

            PrintWriter pWriter = new PrintWriter(socket.getOutputStream(), true);

            pWriter.println(NetworkUtils.TERMINATE_TELNET + NetworkUtils.CRLF);

            pWriter.flush();
            pWriter.close();
        }
    } catch (ConnectException cx) {
        throw new UtilityException(cx.getMessage(), cx);
    } catch (UnknownHostException ux) {
        throw new UtilityException(ux.getMessage(), ux);
    } catch (SocketException sx) {
        throw new UtilityException(sx.getMessage(), sx);
    } catch (IOException iox) {
        throw new UtilityException(iox.getMessage(), iox);
    } finally {
        try {
            if ((socket != null) && (!(socket.isClosed()))) {
                socket.close();
            }
        } catch (IOException iox) {
            // log it - this could cause problems later on
            ERROR_RECORDER.error(iox.getMessage(), iox);
        }
    }
}

From source file:eu.alefzero.owncloud.authenticator.EasySSLSocketFactory.java

/**
 * Attempts to get a new socket connection to the given host within the
 * given time limit./*from   w w w .  j  ava 2 s  .  com*/
 * <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) {
        Socket socket = socketfactory.createSocket(host, port, localAddress, localPort);
        socket.setSoTimeout(params.getSoTimeout());
        return socket;
    } else {
        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);
        return socket;
    }
}