package com.nbusy.sdk.titan.jsonrpc.neptulon;

import android.net.SSLCertificateSocketFactory;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;

import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManagerFactory;

/**
 * Neptulon client implementation: https://github.com/neptulon/neptulon
 */
public class NeptulonClient implements Neptulon {
    private SSLSocket socket;

    public void connect(String pemEncodedCaCert) {
        InputStream caCertStream = new ByteArrayInputStream(pemEncodedCaCert.getBytes());
        SSLCertificateSocketFactory factory = getSocketFactory(caCertStream);

        socket = (SSLSocket)factory.createSocket("localhost", 8081);
    }

    private SSLCertificateSocketFactory getSocketFactory(InputStream caCertStream) {
        SSLCertificateSocketFactory factory = (SSLCertificateSocketFactory)SSLCertificateSocketFactory.getDefault(60 * 1000, null);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");

        try {
            Certificate ca = cf.generateCertificate(caCertStream);
        } finally {
            caCertStream.close();
        }

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        keyStore.setCertificateEntry("ca", ca);
        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(keyStore);
        factory.setTrustManagers(tmf.getTrustManagers());

        return factory;
    }
}

@@ -118,32 +118,60 @@
 rayInputStream;%0A
+import java.io.IOException;%0A
 import java.io.I
@@ -234,32 +234,167 @@
 ecurity.
-cert.Certificate
+KeyStoreException;%0Aimport java.security.NoSuchAlgorithmException;%0Aimport java.security.cert.Certificate;%0Aimport java.security.cert.CertificateException
 ;%0Aimport
@@ -718,16 +718,102 @@
 dCaCert)
+ throws IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException
  %7B%0A     
@@ -1048,24 +1048,100 @@
 81);%0A    %7D%0A%0A
+    public void close() throws IOException %7B%0A        socket.close();%0A    %7D%0A%0A
     private 
@@ -1210,16 +1210,102 @@
 tStream)
+ throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException
  %7B%0A     
@@ -1501,24 +1501,48 @@
 (%22X.509%22);%0A%0A
+        Certificate ca;%0A
         try 
@@ -1555,28 +1555,16 @@
         
-Certificate 
 ca = cf.

fix compile