Example usage for javax.net.ssl SSLSocket close

List of usage examples for javax.net.ssl SSLSocket close

Introduction

In this page you can find the example usage for javax.net.ssl SSLSocket close.

Prototype

public synchronized void close() throws IOException 

Source Link

Document

Closes this socket.

Usage

From source file:org.kuali.mobility.push.factory.iOSConnectionFactory.java

@Override
public void destroyObject(SSLSocket obj) throws Exception {
    if (obj == null) {
        /* If an exception ocurred during the creation of an object
         * we will receive an null object to destroy */
        return;/*from w w  w.java2 s  .  c om*/
    }
    try {
        obj.close();
    } catch (Exception e) {
        // Don't worry - just try and close
    }
}

From source file:org.kuali.mobility.push.dao.PushDaoImpl.java

private void closeConnectionToAPNS(SSLSocket s) {
    try {//from   www .j a  v a2s. co  m
        s.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:test.integ.be.fedict.trust.XKMSTrustTest.java

@Test
public void testValidateUnilateralTLSTrust() throws Exception {
    LOG.debug("validate using unilateral TLS Trust.");

    // Retrieve server public key
    SSLTrustManager.initialize();//from   www .j a  va  2  s  .c o m
    SSLSocketFactory factory = HttpsURLConnection.getDefaultSSLSocketFactory();
    SSLSocket socket = (SSLSocket) factory.createSocket(TestUtils.XKMS_WS_HOST, port);
    socket.startHandshake();
    Certificate[] serverCerts = socket.getSession().getPeerCertificates();
    PublicKey publicKey = serverCerts[0].getPublicKey();
    LOG.debug("server public key: " + publicKey);
    socket.close();

    /*
     * Override default verification that CN of server SSL certificate has
     * to be equal to the hostname.
     */
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return hostname.equals(TestUtils.XKMS_WS_HOST);
        }
    });

    // setup
    List<X509Certificate> signCertificateChain = TestUtils.getSignCertificateChain();
    XKMS2Client client = new XKMS2Client(
            "https://" + TestUtils.XKMS_WS_HOST + ":" + port + TestUtils.XKMS_WS_CONTEXT_PATH);
    client.setServicePublicKey(publicKey);

    /*
     * Operate: validate non repudiation
     */
    client.validate(TrustServiceDomains.BELGIAN_EID_NON_REPUDIATION_TRUST_DOMAIN, signCertificateChain);
}

From source file:com.leetchi.api.client.ssl.SSLConnectionSocketFactory.java

private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException {
    try {//  w  w  w .  j ava2s . c o m
        this.hostnameVerifier.verify(hostname, sslsock);
        // verifyHostName() didn't blowup - good!
    } catch (final IOException iox) {
        // close the socket before re-throwing the exception
        try {
            sslsock.close();
        } catch (final Exception x) {
            /*ignore*/ }
        throw iox;
    }
}

From source file:de.vanita5.twittnuker.util.net.ssl.HostResolvedSSLConnectionSocketFactory.java

private void verifyHostname(final SSLSocket sslsock, final String hostname, final HttpContext context)
        throws IOException {
    try {/* w  ww  . j ava  2  s  . co m*/
        hostnameVerifier.verify(getHostname(hostname, context), sslsock);
        // verifyHostName() didn't blowup - good!
    } catch (final IOException iox) {
        // close the socket before re-throwing the exception
        try {
            sslsock.close();
        } catch (final Exception x) { /* ignore */
        }
        throw iox;
    }
}

From source file:be.fgov.kszbcss.rhq.websphere.connector.agent.ConnectorSubsystemComponent.java

public OperationResult invokeOperation(String name, Configuration parameters)
        throws InterruptedException, Exception {
    if (name.equals("importCertificateFromFile")) {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream in = new FileInputStream(parameters.getSimple("file").getStringValue());
        try {//  w ww .  j  a v  a 2s .c  o m
            Iterator<? extends Certificate> it = cf.generateCertificates(in).iterator();
            if (it.hasNext()) {
                TrustStoreManager.getInstance().addCertificate(parameters.getSimple("alias").getStringValue(),
                        (X509Certificate) it.next());
            } else {
                throw new Exception("No certificate found");
            }
        } finally {
            in.close();
        }
        return null;
    } else if (name.equals("retrieveCellCertificate")) {
        DeploymentManager dm = new DeploymentManager(null, new ConfigurationBasedProcessLocator(parameters));
        String cell = dm.getCell();
        ConfigQueryExecutor configQueryExecutor = ConfigQueryServiceFactory.getInstance()
                .getConfigQueryExecutor(dm);
        try {
            X509Certificate cert = configQueryExecutor.query(CellRootCertificateQuery.INSTANCE);
            TrustStoreManager.getInstance().addCertificate("cell:" + cell, cert);
        } finally {
            configQueryExecutor.destroy();
        }
        return null;
    } else if (name.equals("retrieveCertificateFromPort")) {
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(new KeyManager[0],
                new TrustManager[] {
                        new AutoImportTrustManager(parameters.getSimple("alias").getStringValue()) },
                new SecureRandom());
        SSLSocket socket = (SSLSocket) sslContext.getSocketFactory().createSocket(
                parameters.getSimple("host").getStringValue(), parameters.getSimple("port").getIntegerValue());
        try {
            socket.startHandshake();
        } finally {
            socket.close();
        }
        return null;
    } else if (name.equals("listCertificates")) {
        final PropertyList certificates = new PropertyList("certificates");
        TrustStoreManager.getInstance().execute(new TrustStoreAction() {
            public void execute(KeyStore truststore) throws Exception {
                // Sort the aliases for convenience
                Set<String> aliases = new TreeSet<String>();
                for (Enumeration<String> e = truststore.aliases(); e.hasMoreElements();) {
                    aliases.add(e.nextElement());
                }
                for (String alias : aliases) {
                    X509Certificate cert = (X509Certificate) truststore.getCertificate(alias);
                    PropertyMap map = new PropertyMap("certificate");
                    map.put(new PropertySimple("alias", alias));
                    map.put(new PropertySimple("subject", cert.getSubjectDN().toString()));
                    MessageDigest md = MessageDigest.getInstance("SHA-1");
                    md.update(cert.getEncoded());
                    byte[] digest = md.digest();
                    StringBuilder fingerprint = new StringBuilder();
                    for (int i = 0; i < digest.length; i++) {
                        if (i > 0) {
                            fingerprint.append(':');
                        }
                        fingerprint.append(getHexDigit(((int) digest[i] & 0xf0) >> 4));
                        fingerprint.append(getHexDigit((int) digest[i] & 0x0f));
                    }
                    map.put(new PropertySimple("fingerprint", fingerprint.toString()));
                    certificates.add(map);
                }
            }
        }, true);
        if (log.isDebugEnabled()) {
            log.debug("certificates=" + certificates);
        }
        OperationResult result = new OperationResult();
        result.getComplexResults().put(certificates);
        return result;
    } else if (name.equals("removeCertificate")) {
        final String alias = parameters.getSimple("alias").getStringValue();
        TrustStoreManager.getInstance().execute(new TrustStoreAction() {
            public void execute(KeyStore truststore) throws Exception {
                truststore.deleteEntry(alias);
            }
        }, false);
        return null;
    } else if (name.equals("renameCertificate")) {
        final String oldAlias = parameters.getSimple("oldAlias").getStringValue();
        final String newAlias = parameters.getSimple("newAlias").getStringValue();
        TrustStoreManager.getInstance().execute(new TrustStoreAction() {
            public void execute(KeyStore truststore) throws Exception {
                Certificate cert = truststore.getCertificate(oldAlias);
                truststore.setCertificateEntry(newAlias, cert);
                truststore.deleteEntry(oldAlias);
            }
        }, false);
        return null;
    } else {
        return null;
    }
}

From source file:org.wso2.carbon.identity.relyingparty.saml.IssuerCertificateUtil.java

public static Certificate readCertFromUrl(String url) throws Exception {

    URL hostURL = null;// w ww. j  av  a  2  s .c om
    String hostname = null;
    int port;
    SSLSocketFactory factory = null;
    SSLSocket socket = null;

    try {
        // Create the client socket
        hostURL = new URL(url);
        hostname = hostURL.getHost();

        // Check whether the url has a port stated explicitly. If its not present default to 443
        port = hostURL.getPort();
        if (port == -1) {
            port = 443;
        }
        factory = HttpsURLConnection.getDefaultSSLSocketFactory();
        socket = (SSLSocket) factory.createSocket(hostname, port);

        // Connect to the server
        socket.startHandshake();

        // Retrieve the server's certificate chain
        Certificate[] serverCerts = socket.getSession().getPeerCertificates();

        // The local certificate first followed by any certificate authorities.
        if (serverCerts != null && serverCerts.length > 0) {
            if (log.isDebugEnabled()) {
                log.debug("Return any associated certificates suceessfully" + url);
            }
            return serverCerts[0];
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Does not return any associated certificates" + url);
            }
            return null;
        }

    } finally {
        // Close the socket
        if (socket != null) {
            socket.close();
        }
    }
}

From source file:LoginClient.java

public LoginClient() {
    try {/*from w  ww .j av  a  2  s  .  com*/
        SSLSocketFactory socketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
        SSLSocket socket = (SSLSocket) socketFactory.createSocket("localhost", 7070);
        PrintWriter output = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
        String userName = "MyName";
        output.println(userName);
        String password = "MyPass";
        output.println(password);
        output.flush();
        BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String response = input.readLine();
        System.out.println(response);

        output.close();
        input.close();
        socket.close();
    } catch (IOException ioException) {
        ioException.printStackTrace();
    } finally {
        System.exit(0);
    }
}

From source file:edu.htl3r.schoolplanner.backend.network.Network.java

/**
 * Liefert ein {@link SSLSocket}, wenn eine Verbindung via SSL zum Server aufgebaut werden konnte oder 'null', wenn SSL nicht verfuegbar ist.
 * @param sa Die Adresse des Sockets, zum dem die Verbindung aufgebaut werden soll
 * @param set Ein Set mit {@link SSLSocket}s, mithilfe derer versucht werden soll, eine Verbindung aufzubauen 
 * @return Das erste SSLSocket aus dem Set, mit dem eine problemlos Verbindung zum Server aufgebaut werden konnte oder 'null', wenn dies mit keinem moeglich war
 *///from   w w  w  . j av  a 2  s. c  o  m
private SSLSocket getWorkingSSLSocket(SocketAddress sa, Set<SSLSocket> set) {
    final int sslSocketTimeout = 2000;
    for (SSLSocket sslSocket : set) {
        try {
            sslSocket.connect(sa, sslSocketTimeout);
            sslSocket.setSoTimeout(sslSocketTimeout);
            sslSocket.setReuseAddress(true);
            sslSocket.startHandshake();
            return sslSocket;
        } catch (IOException e) {
        } finally {
            try {
                sslSocket.close();
            } catch (IOException e) {
            }
        }
    }
    return null;
}

From source file:com.sonatype.nexus.ssl.plugin.internal.CertificateRetriever.java

/**
 * Retrieves certificate chain of specified host:port using direct socket connection.
 *
 * @param host to get certificate chain from (cannot be null)
 * @param port of host to connect to/*from   w w w  .  j a  v  a  2  s.  c o  m*/
 * @return certificate chain
 * @throws Exception Re-thrown from accessing the remote host
 */
public Certificate[] retrieveCertificates(final String host, final int port) throws Exception {
    checkNotNull(host);

    log.info("Retrieving certificate from {}:{} using direct socket connection", host, port);

    SSLSocket socket = null;
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, new TrustManager[] { ACCEPT_ALL_TRUST_MANAGER }, null);

        javax.net.ssl.SSLSocketFactory sslSocketFactory = sc.getSocketFactory();
        socket = (SSLSocket) sslSocketFactory.createSocket(host, port);
        socket.startHandshake();

        SSLSession session = socket.getSession();
        return session.getPeerCertificates();
    } finally {
        if (socket != null) {
            socket.close();
        }
    }
}