Tuesday, January 31, 2017

Netbeans: How to add back a deleted java file?

1. Right click the package where the java file used to be in the navigation window.
2. Select "History".
3. Select "Revert Deleted".
4. Choose the file you would like to restore in the pop up window.
---------------------------------------------------------------------------------------------------

                        


If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

NetBeans: How to safely remove unused java files?

You must be very careful when you are going to delete a java file to make sure that it is not used anywhere. Following are the steps to safely remove a java file in NetBeans.

1. Right click the file in the navigation window, and select "Find Usages". Click the "Find" button in the pop up window. If the file is not used anywhere, proceed to step 2. Otherwise leave the file there.

2. Right click the file, choose "Refactor", and then "Safely Delete...". Click the "Refactor" button to remove the file.

---------------------------------------------------------------------------------------------------

                        


If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Wednesday, January 25, 2017

java: generic array creation error

The line of code below incurs a generic array creation error at compile time.

       ArrayList<String>[] sc = new ArrayList<String>[2];

The following code compiles, but it will generate an unchecked cast warning at compile time.

      ArrayList<String>[] sc = (ArrayList<String>[]) new Object[2];

However, if you cast an already built Object array to an ArryList<String>[] and if the array contains object other than ArrayList<String> a ClassCastException will happen at execution time.

        Object[] test = new Object[2];
        test[0] = new ArrayList<String>();
        test[1] = new Integer(9);
        ArrayList<String>[] sc = (ArrayList<String>[])test;

The following code compiles, but gives an unchecked cast warning at compile time. If you don't want to see the warning message, you can supress it.

      @SuppressWarnings("unchecked")
      ArrayList<String>[] sc = (ArrayList<String>[])Array.newInstance(String.class, 2);
or
      ArrayList<String>[] sc = (ArrayList<String>[]) new ArrayList[2];

---------------------------------------------------------------------------------------------------

                        


If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Tuesday, January 24, 2017

java: cleaning / logging before shutdown

1. Use a Shutdown Hook

If you would like to shutdown some connections, restore resources, or print a log message before your program is shut down, you may use the Shutdown hook to achieve it.

public class CleanTest {
      private String name;

      public CleanTest(String name){
            this.name = name;

            Runtime.getRuntime().addShutdownHook(new Thread() {
                 public void run() {
                        Log.write("CleanTest is shutting down....");
                       //shutdown connections
                       //restore resources
                }
         });
    }
}

2. Use a Window Listener

If you are executing a java.awt.Window object such as JFrame and JDialog, you can add a java.awt.event.WindowListener to do the job.

public class CleanTest extends JFrame {
    private String name = "";
 
    public CleanTest (String name) {
        this.name = name;
        //Build your window components
     
        setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);

        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e){
                //shutdown connections
                //restore resources
            }
        });

        pack();
        setVisible(true);
    }


---------------------------------------------------------------------------------------------------

                        


If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

sun.misc.Signal is internal proprietary API and may be removed

When you use code like the below code segment to intercept user incurred shutdown signal to do some setting before it shuts down, you get this compile-time warning.

SignalHandler handler = new SignalHandler () {
        public void handle(Signal signal) {
            System.out.println("Sutting down....");
            //do some cleaning or setting here
            System.exit(0);
        }
 };
 Signal.handle(new Signal("INT"), handler);
 Signal.handle(new Signal("TERM"), handler);
Warning: sun.misc.Signal is internal proprietary API and may be removed

You may alternatively use the following code to avoid the warning message.
Runtime.getRuntime().addShutdownHook(new Thread() {
      public void run() {
            System.out.println("Sutting down....");
            //do some cleaning or setting here
      }
});

-----------------------------------------------------------------------------------------------------------------
Watch the blessing and loving online channel: SupremeMasterTV live




If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book for free here.

Monday, January 23, 2017

java xml parser - The DocumentBuilder

The DocumentBuilder stores its parsed result in a org.w3c.dom.Document object. You can call the Document's getDocumentelement() method to get the root node, and use the getChildNotes() method to get a list of the child nodes.

If you get compile-time warnings such as "warning: com.sun.org.apache.xerces.internal.parsers.DOMParser is Sun proprietary API and may be removed in a future release", you may consider using the SAXParser or the DocumentBuilder in the java.xml.parsers package.

import java.xml.parsers.DocumentBuilder;
import java.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;

public class XMLParser {

    public void domParse(String xmlStr) {
        try {
            InputSource source = new InputSource(new StringReader(xmlStr));
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(source);
            System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

            printNodeNameValue((Node) doc.getDocumentElement(), "Node name: ");
        } catch (ParserConfigurationException e) {
            e.printStackTrace(System.out);
        } catch (SAXException e) {
            e.printStackTrace(System.out);
        } catch (IOException e) {
            e.printStackTrace(System.out);
        }
    }
 
    private void printNodeNameValue(Node node, String nn){
        String nns = "  "+nn;
        String value = node.getNodeValue() == null ? "" : ("; node value: "+node.getNodeValue());
        System.out.println(nn+node.getNodeName()+value);
        if (node.hasChildNodes()){
            NodeList nodeList = node.getChildNodes();
            for(int i = 0; i < nodeList.getLength(); i++){
                printNodeNameValue(nodeList.item(i), nns);
            }
        }
    }
    public static void main(String[] args) {
        StringBuilder xml = new StringBuilder();
        xml.append("<store value='Deliciously Healthy'>")
                .append("<fruit>")
                .append("<name>Apple</name><price>1.68</price>")
                .append("</fruit><fruit>")
                .append("<name>Orange</name><price>0.89</price>")
                .append("</fruit>")
                .append("</store>");
        XMLParser xmlParser = new XMLParser();
        xmlParser.domParse(xml.toString());
    }
}

The output:
Root element :store
Node name: store
  Node name: fruit
    Node name: name
      Node name: #text; node value: Apple
    Node name: price
      Node name: #text; node value: 1.68
  Node name: fruit
    Node name: name
      Node name: #text; node value: Orange
    Node name: price
      Node name: #text; node value: 0.89

-----------------------------------------------------------------------------------------------------------------
Watch the blessing and loving online channel: SupremeMasterTV live




If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book for free here.

java xml parser - The SAXParser

The SAXParser uses a Handler to go over each node and output the associated name and value at your discretion. You may modify the Handler to make it send you the parsed result in a different way.

If you get compile time warnings such as "warning: com.sun.org.apache.xerces.internal.parsers.SAXParser is Sun proprietary API and may be removed in a future release", you may consider use the SAXParser and the DocumentBuilder in the java.xml.parsers package.

import java.xml.parsers.SAXParser;
import java.xml.parsers.SAXParserFactory;

public class XMLParser {

    public void saxParse(String xmlStr) {
        try {
            InputSource source = new InputSource(new StringReader(xmlStr));
            SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
            MyHandler dHandler = new MyHandler();
            parser.parse(source, dHandler);
        } catch (ParserConfigurationException e) {
            e.printStackTrace(System.out);
        } catch (SAXException e) {
            e.printStackTrace(System.out);
        } catch (IOException e) {
            e.printStackTrace(System.out);
        }
    }

    private class MyHandler extends DefaultHandler {
        boolean isName = false;
        boolean isPrice = false;
     
        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes)
                throws SAXException {
            if (qName.equalsIgnoreCase("store")) {
                String value = attributes.getValue("name");
                System.out.println("Node name : "+qName+"; value: " + value);
            } else if (qName.equalsIgnoreCase("fruit")) {
                System.out.println("  "+qName);
            } else if (qName.equalsIgnoreCase("name")) {
                isName = true;
            } else if (qName.equalsIgnoreCase("price")) {
                isPrice = true;
            }
        }

        @Override
        public void endElement(String uri,
                String localName, String qName) throws SAXException {
            if (qName.equalsIgnoreCase("fruit")) {
                System.out.println("End Element :" + qName);
            }
        }

        @Override
        public void characters(char[] ch,
                int start, int length) throws SAXException {
            if (isName) {
                System.out.println("Name: "+ new String(ch, start, length));
                isName = false;
            } else if (isPrice) {
                System.out.println("Price: " + new String(ch, start, length));
                isPrice = false;
            }
        }
    }

    public static void main(String[] args) {
        StringBuilder xml = new StringBuilder();
        xml.append("<store name='Deliciously Healthy'>")
                .append("<fruit>")
                .append("<name>Apple</name><price>1.68</price>")
                .append("</fruit><fruit>")
                .append("<name>Orange</name><price>0.89</price>")
                .append("</fruit>")
                .append("</store>");

        XMLParser xmlParser = new XMLParser();
        xmlParser.saxParse(xml.toString());
    }
}

The output:
Node name : store; value: Deliciously Healthy
  fruit
Name: Apple
Price: 1.68
End Element :fruit
  fruit
Name: Orange
Price: 0.89
End Element :fruit

---------------------------------------------------------------------------------------------------

                        


If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Java encode and decode a String in Base64

The sample code here demonstrates how to encode and decode a string object in the Base64 format.

If you get a compile-time warning such as "warning: com.sun.org.apache.xerces.internal.impl.dv.util. Base64 is internal proprietary API and may be removed in a future release", you may consider to use the java.util.Base64 (java 8) or javax.sml.bind.DatatypeConverter (java 7) to avoid the warning.

1. java 8 or a later version of java

import java.util.Base64;
public class Base64Test {
    public static void main(String [] args){
        String secret = "This message is top secret";
        byte[] encoded = Base64.getEncoder().encode(secret.getBytes());
        System.out.println("encoded value is "+ new String(encoded));
     
        byte[] decoded = Base64.getDecoder().decode(encoded);
        System.out.println("Decoded value is "+new String(decoded));
   }

2. java 7 or an earlier version of java

import javax.xml.bind.DatatypeConverter;
public class Base64Test {
    public static void main(String [] args){
       String secret = "This message is top secret";
        String encoded = DatatypeConverter.printBase64Binary(secret.getBytes());
        System.out.println("encoded value is "+ encoded);
     
        byte[] decoded = DatatypeConverter.parseBase64Binary(encoded);
        System.out.println("Decoded value is "+new String(decoded));
    }
}
-----------------------------------------------------------------------------------------------------------------
Watch the blessing and loving online channel: SupremeMasterTV live




If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book for free here.

Friday, January 20, 2017

java.security.NoSuchAlgorithmException: SunX509 SSLContext not available

The following line of code throws the exception.

SSLContext sc = SSLContext.getDefault();

The exception:
java.security.NoSuchAlgorithmException: SunX509 SSLContext not available
        at sun.security.jca.GetInstance.getInstance(GetInstance.java:159)
        at javax.net.ssl.SSLContext.getInstance(SSLContext.java:156)

The default SSLContext is SunX509 which is not supported.

Use a supported SSLContext algorithm to avoid the exception.

      SSLContext sc = SSLContext.getInstance("<algorithm name>");

You may find the SSLContext algorithm here.

-----------------------------------------------------------------------------------------------------------------
Watch the blessing and loving online channel: SupremeMasterTV live




If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book for free here.

Linux: java SSL socket connections sample code

1. The SSL server

public class SSLServer {
    public static void main(String args[]) {
        //set which keystore to use
        System.setProperty("javax.net.ssl.keyStore", "<path>/<keystore file name>");
        System.setProperty("javax.net.ssl.keyStorePassword", "<keystore password>");

        try {
            // Create a trust manager that does not validate certificate chains
            TrustManager[] trustManagers = new TrustManager[]{new X509TrustManager() {
                  public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { }
                  public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {}
                  public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                         return null;
                  }
             }};

             //Load the keystore
             KeyStore ks = KeyStore.getInstance("JKS");
             InputStream readCert = new FileInputStream("<path>/<keystore file name>");
             try {
                  ks.load(readCert, "<keystore password>".toCharArray());
              } finally {
                  readCert.close();
              }

              //Initialize the KeyManagerFactory
              KeyManagerFactory kmf = KeyManagerFactory.getInstance(
                    KeyManagerFactory.getDefaultAlgorithm());
              kmf.init(ks, "<keystore password>".toCharArray());

              //Initialize the SSLContext
              SSLContext sc = SSLContext.getInstance("TLSv1.2");
              sc.init(kmf.getKeyManagers(), trustManagers, new SecureRandom());

              //Create the SSLServerSocket
              SSLServerSocket serverSocket = (SSLServerSocket) sc.getServerSocketFactory().createServerSocket(csServerPort);
              serverSocket.setEnabledProtocols(new String[]{"TLSv1", "TLSv1.1", "TLSv1.2", "SSLv3"});

            while (true) {
                //accept connections from client
                Socket s = ss.accept();

                //the reader
                BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
                //the wirter
                PrintStream out = new PrintStream(s.getOutputStream());
                String message;
                while (!(message = in.readLine()).equals("end")) {
                      if (message.equals("Got it?")){
                            out.println("Yes, received.");
                      } else if (message.equals("Hello")) {
                            out.println("Hi");
                      } else if (message.equals("Thanks")){
                            out.println("end");
                      }
                }
                out.close();
                s.close();
            }
        } catch (IOException e) {
            e.printStackTrace(System.out);
        }
    }
}

2. The SSL Client

public class SSLClient {
    public static void main(String args[]) throws Exception {
          System.setProperty("javax.net.ssl.trustStore", "<path>/<truststore file name>");
          System.setProperty("javax.net.ssl.keyStorePassword", "<truststore password>");

          // Create a trust manager that does not validate certificate chains
          TrustManager[] trustManagers = new TrustManager[]{new X509TrustManager() {
                  public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { }
                  public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {}
                  public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                         return null;
                  }
             }};

             //Load the keystore
             KeyStore ks = KeyStore.getInstance("JKS");
             FileInputStream readCert = new FileInputStream("<path>/<truststore file name>");
             try {
                  ks.load(readCert, "<truststore password>".toCharArray());
              } finally {
                  readCert.close();
              }

              //Initialize the KeyManagerFactory
              KeyManagerFactory kmf = KeyManagerFactory.getInstance(
                    KeyManagerFactory.getDefaultAlgorithm());
              kmf.init(ks, "<truststore password>".toCharArray());

              //Initialize the SSLContext
              SSLContext sc = SSLContext.getInstance("TLSv1.2");
              sc.init(kmf.getKeyManagers(), trustManagers, new SecureRandom());

              SSLSocketFactory socketFactory = sc.getSocketFactory(); 
              SSLSocket socket = (SSLSocket)socketFactory.createSocket("<server IP>", <port>);               
              socket.setEnabledCipherSuites(socket.getSupportedCipherSuites());

              // SSLSession session = socket.getSession();
              // Certificate[] cchain = session.getPeerCertificates();
              //System.out.println("The Certificates used by peer");
              //for (int i = 0; i < cchain.length; i++) {
                   //  System.out.println(((X509Certificate) cchain[i]).getSubjectDN());
              // }
              // System.out.println("Peer host is " + session.getPeerHost());
              // System.out.println("Cipher is " + session.getCipherSuite());
              // System.out.println("Protocol is " + session.getProtocol());
              // System.out.println("ID is " + new BigInteger(session.getId()));
              //System.out.println("Session created in " + session.getCreationTime());
              // System.out.println("Session accessed in " + session.getLastAccessedTime());

              PrintStream out = new PrintStream(s.getOutputStream());
              out.println("Hello");
             BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
             String x;
             while(!(x = in.readLine()).equals("end")){
                   System.out.println(x);
                   if (x.equals("Hi")){
                        out.println("Got it?");
                   } else if (x.equals("Yes, received.")){
                       out.println("Thanks");
                   }
             }
             out.println("end");
             in.close();
             out.close();
            s.close();
      }
}

-----------------------------------------------------------------------------------------------------------------
Watch the blessing and loving online channel: SupremeMasterTV live




If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book for free here.



java.security.KeyManagementException: Default SSLContext is initialized automatically

The default SSLContext is immutable. If you try to initiate it, it throws this exception.
SSLContext sc = SSLContext.getDefault();
sc.init(<the KeyManagers>, <the TrustManagers>, new SecureRandom());
The above code segment will throw the following exception.

java.security.KeyManagementException: Default SSLContext is initialized automatically
        at sun.security.ssl.SSLContextImpl$DefaultSSLContext.engineInit(SSLContextImpl.java:511)
        at javax.net.ssl.SSLContext.init(SSLContext.java:283)

To fix it, use a SSLContex associated with a specific protocol instead of using the default SSLContext. You can find all the SSLContext algorithm/protocol here.

For example

      SSLContext sc = SSLContext.getInstance("TLSv1.2"); 

-----------------------------------------------------------------------------------------------------------------
Watch the blessing and loving online channel: SupremeMasterTV live




If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book for free here.
  

java.security.KeyStoreException: Uninitialized keystore

The code below will generate the exception.

KeyStore ks = KeyStore.getInstance("JKS");
KeyManagerFactory kmf = KeyManagerFactory.getInstance(
      KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, "<keystore password>".toCharArray());

When you execute a program containing the above code segment, you will get the exception.

java.security.KeyStoreException: Uninitialized keystore
        at java.security.KeyStore.aliases(KeyStore.java:1002)
        at sun.security.ssl.SunX509KeyManagerImpl.<init>(SunX509KeyManagerImpl.java:125)
        at sun.security.ssl.KeyManagerFactoryImpl$SunX509.engineInit(KeyManagerFactoryImpl.java:68)
        at javax.net.ssl.KeyManagerFactory.init(KeyManagerFactory.java:259)

This is because the KeyStore used to initialize the KeyManagerFactory is not initialized itself. The following code will initialize the KeyStore.

KeyStore ks = KeyStore.getInstance("JKS");
InputStream readCert = new FileInputStream("<path>/<keystore name>");
 try {
        ks.load(readCert, "<keystore password>".toCharArray());
 } finally {
        readCert.close();
 }

-----------------------------------------------------------------------------------------------------------------
Watch the blessing and loving online channel: SupremeMasterTV live




If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book for free here.



javax.net.ssl.SSLHandshakeException: no cipher suites in common

When you are trying to connect your SSL client to your SSL server through SSL Socket connection, the following exception occurs.

javax.net.ssl.SSLHandshakeException: no cipher suites in common
        at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
        at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1884)
        at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:276)
        at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:266)
        at sun.security.ssl.ServerHandshaker.chooseCipherSuite(ServerHandshaker.java:894)
        at sun.security.ssl.ServerHandshaker.clientHello(ServerHandshaker.java:622)
        at sun.security.ssl.ServerHandshaker.processMessage(ServerHandshaker.java:167)
        at sun.security.ssl.Handshaker.processLoop(Handshaker.java:878)
        at sun.security.ssl.Handshaker.process_record(Handshaker.java:814)
        at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1016)
        at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1312)
        at sun.security.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:882)
        at sun.security.ssl.AppInputStream.read(AppInputStream.java:102)
        at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:283)
        at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:325)
        at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:177)
        at java.io.InputStreamReader.read(InputStreamReader.java:184)
        at java.io.BufferedReader.fill(BufferedReader.java:154)
        at java.io.BufferedReader.readLine(BufferedReader.java:317)
        at java.io.BufferedReader.readLine(BufferedReader.java:382)

The exception is thrown because the SSL server socket could not find the private key to use.

1. Ensure your keystore (the jks file used by the server) has the private key
    >keytool -list -keystore <path>/<keystore name>

2. Ensure the algorithm such as RSA used to generate the certificate is supported by your system.

3. Ensure the SSLContext is initialized correctly to use the keystore
3.1 Create a TrustManager that trust the certificate
    TrustManager[] trustManagers = new TrustManager[]{new X509TrustManager() {
           public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {}
           public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {}
           public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                 return null;
           }
     }};

3.2 Load the key store.
     KeyStore ks = KeyStore.getInstance("JKS");
     InputStream readCert = new FileInputStream("<path>/<keystore name>");
     try {
           ks.load(readCert, "<keystore password>".toCharArray());                  
      } finally {
           readCert.close();
      }

3.3 Initialize the KeyManagerFactory with the key store
      KeyManagerFactory kmf = KeyManagerFactory.getInstance(
             KeyManagerFactory.getDefaultAlgorithm());
      kmf.init(ks, "<keystore password>".toCharArray());

3.4 Initialize the SSLContext
     SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
     sslContext.init(kmf.getKeyManagers(), trustManagers, new SecureRandom());

-----------------------------------------------------------------------------------------------------------------
Watch the blessing and loving online channel: SupremeMasterTV live




If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book for free here.

Thursday, January 12, 2017

Windows: java SSL socket connections sample code

1. The SSL server socket

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.math.BigInteger;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;

public class SSLServer {

    public static void main(String args[]) {
        //set which keystore to use
        System.setProperty("javax.net.ssl.keyStore", "<path>/<keystore file name>");
        System.setProperty("javax.net.ssl.keyStorePassword", "<keystore password>");

        try {
            SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
            //create a server socket listening on a specified port.
            ServerSocket ss = ssf.createServerSocket(<port>);
            while (true) {
                //accept connections from client
                Socket s = ss.accept();
                //SSLSession session = ((SSLSocket) s).getSession();
                //Certificate[] cchain2 = session.getLocalCertificates();
               // for (int i = 0; i < cchain2.length; i++) {
                 //   System.out.println(((X509Certificate) cchain2[i]).getSubjectDN());
              //  }
               // System.out.println("Peer host is " + session.getPeerHost());
              //  System.out.println("Cipher is " + session.getCipherSuite());
               // System.out.println("Protocol is " + session.getProtocol());
               // System.out.println("ID is " + new BigInteger(session.getId()));
              //  System.out.println("Session created in " + session.getCreationTime());
              //  System.out.println("Session accessed in " + session.getLastAccessedTime());

                //the reader
                BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
                //the wirter
                PrintStream out = new PrintStream(s.getOutputStream());
                String message;
                while (!(message = in.readLine()).equals("end")) {
                      if (message.equals("Got it?")){
                            out.println("Yes, received.");
                      } else if (message.equals("Hello")) {
                            out.println("Hi");
                      } else if (message.equals("Thanks")){
                            out.println("end");
                      }
                }
                out.close();
                s.close();
            }
        } catch (IOException e) {
            e.printStackTrace(System.out);
        }
    }
}

2. SSL client socket

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.math.BigInteger;
import java.net.Socket;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

public class SSLClient {
    public static void main(String args[]) throws Exception {
          System.setProperty("javax.net.ssl.trustStore", "<path>/<truststore file name>");
          System.setProperty("javax.net.ssl.keyStorePassword", "<truststore password>");

          SSLSocketFactory ssf = (SSLSocketFactory) SSLSocketFactory.getDefault();
          Socket s = ssf.createSocket("<server IP address>", <port>);

         // SSLSession session = ((SSLSocket) s).getSession();
         // Certificate[] cchain = session.getPeerCertificates();
          //System.out.println("The Certificates used by peer");
          //for (int i = 0; i < cchain.length; i++) {
                //  System.out.println(((X509Certificate) cchain[i]).getSubjectDN());
         // }
         // System.out.println("Peer host is " + session.getPeerHost());
         // System.out.println("Cipher is " + session.getCipherSuite());
         // System.out.println("Protocol is " + session.getProtocol());
         // System.out.println("ID is " + new BigInteger(session.getId()));
          //System.out.println("Session created in " + session.getCreationTime());
        // System.out.println("Session accessed in " + session.getLastAccessedTime());

         PrintStream out = new PrintStream(s.getOutputStream());
         out.println("Hello");
         BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
         String x;
         while(!(x = in.readLine()).equals("end")){
               System.out.println(x);
               if (x.equals("Hi")){
                     out.println("Got it?");
               } else if (x.equals("Yes, received.")){
                     out.println("Thanks");
                }
          }
         out.println("end");
         in.close();
         out.close();
         s.close();
     }
}

---------------------------------------------------------------------------------------------------

                        


If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Reference:
1. Use SSLServerSocketFactory to create a SSL Server

keytool error java.io.FileNotFoundException: (Access is denied)

You launched the Command Prompt to create a keystore as below, and in the end the error occurred.

>keytool -genkey -alias mykeystore -keyalg RSA -keystore KeyStore.jks -keysize 2048

Enter keystore password:
Re-enter new password:
What is your first and last name?
      [Unknown]: joysu
What is the name of your organizational unit?
      [Unknown]: ps
What is the name of your organization?
      [Unknown]: ddw
What is the name of your City or Locality?
      [Unknown]: ocoee
What is the name of your state or province?
      [Unknown]: fl
What is the two-letter country code for this unit?
      [Unknown]: us
Is CN=joysu, OU=ps, O=ddw, L=ocoee, ST=fl, C=us correct?
      [No]: yes

Enter key password for ,jkskeystore.
                (RETURN if same as keystore password):

keytool error: java.io.FileNotFoundException: keystore.jks (Access is denied)

Do the following to fix it.

Change the directory and file access permission to allow you to access the file.

If change access permission does not solve the problem, launch the Command Prompt as an administrator. Right click on Command Prompt and select "Run as administer".

-----------------------------------------------------------------------------------------------------------------
Watch the blessing and loving online channel: SupremeMasterTV live




If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book for free here.

Create keystore, truststore, and self-signed certificate using java keytool



Keytool is a key and certificate management utility. It enables users to administer their own public/private key pairs and associated certificates for use in self-authentication. It also allows users to cache the public keys (in the form of certificates) of their communicating peers.
Keytool stores the keys and certificates in a keystore. The default keystore implementation implements the keystore as a file. It protects private keys with a password. A keystore contains private keys, and the certificates with their corresponding public keys. A keystore is a database of key material. Key material is used for a variety of purposes, including authentication and data integrity. There are various types of keystores available, including “PKCS12” and Sun’s “JKS.
The keytool is located in either your $JAVA_HOME/jre/bin directory or the directory in which you run the commands.
Right click on Command Prompt and select Run as administrator to launch the Command Prompt. If you don't have $JAVA_HOME/jre/bin on your PATH, change your location to that directory.

1. Create a new public/private key pair stored in a new keystore

Type the following command at the Command Prompt.

>keytool -genkeypair -alias mykeystore -keyalg RSA -keystore KeyStore.jks -storetype JKS -keysize 2048

Enter keystore password:
Re-enter new password:
What is your first and last name?
      [Unknown]: joysu
What is the name of your organizational unit?
      [Unknown]: ps
What is the name of your organization?
      [Unknown]: ddw
What is the name of your City or Locality?
      [Unknown]: ocoee
What is the name of your state or province?
      [Unknown]: fl
What is the two-letter country code for this unit?
      [Unknown]: us
Is CN=joysu, OU=ps, O=ddw, L=ocoee, ST=fl, C=us correct?
      [No]: yes

Enter key password for <mykeystore>.
                (RETURN if same as keystore password):

The new keystore created is KeyStore.jks. It's alias is mykeystore. By default the associated certificate is valid for 90 days. You can use the validity parameter to specify the days the certificate is valid. The above command will look like this if you want the certificate valid for 360 days.

      keytool -genkey -alias mykeystore -keyalg RSA -keystore KeyStore.jks -storetype JKS -validity 36500 -keysize 2048

To look at the information of the KeyStore.jks, type the command.

>keytool -list -keystore KeyStore.jks
Enter keystore password:

Output:
keystore type: JKS
keystore provider: SUN

Your keystore contains 1 entry

mykeystore, Jan 11, 2017, PrivateKeyEntry,
Certificate fingerprint (SHA1): 5D:6F:13:40:29:DA:BD:0B:5B:C1:12:90:27:C9:5D:1B:19:1C:3B:79

2. Get the certificate/Public key

If you need a certificate request file to order certificate from a CA such as VeriSign, run the following command to generate the CSR file.

>keytool -certreq -alias mykeystore -keystore KeyStore.jks -file mykeystore.csr

If you don't mind using a self-signed certificate, this command will export an self-signed X.509 certificate for you. Public key is exported in a form of certificate file which can be shared with another party.

>keytool -export -alias mykeystore -keystore KeyStore.jks -rfc -file X509_certificate.cer

Enter keystore password:
Certificate stored in file <x509_certificate.cer>

By default the certificate is in binary DER format. However, the -rfc option changes it to be in the BASE64 encoded PEM format.

You can use the following command to print the information of the certificate.

>keytool -printcert -file X509_certificate.cer

3. Create a TrustStore and Import X.509 Certificate as a Trusted Certificate


A truststore is a keystore which is used when making decisions about what to trust. An entry should only be added to a truststore if the user makes a decision to trust that entity. By either generating a keypair or by importing a certificate, the user has given trust to that entry, and thus any entry in the keystore is considered a trusted entry.

>keytool -import -alias mykeystore -file X509_certificate.cer -keystore truststore -storetype JKS
Enter keystore password:
Re-enter new password:
Owner: CN=joysu, OU=ps, O=ddw, L=ocoee, ST=fl, C=us 
Isuer: CN=joysu, OU=ps, O=ddw, L=ocoee, ST=fl, C=us
Serial number: 60557ff
valid from Wed Jan 11 13:04:03 ESt 2017 until: Tue Apr 11 14:04:03 EDT 2017
Certificate fingerprints:
MD5: 64:72:97:D6:C2:79:C4:39:22:B3:DB:1C:95:AB:20:22
SHA1: 5D:6F:13:40:29:DA:BD:0B:5B:C1:12:90:27:C9:5D:1B:19:1C:3B:79
   SHA256: E3:16:4B:01:DB:6E:D1:73:A3:DE:36:9E:94:E2:84:98:00:99:DC:1D:F2:76:48:F2:1D:0B:E6:06:D4:CD:14:32
   Signature algorithm name: SHA256withRSA
   version: 3

Extensions:
#1: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifiew [
0000: B3 26 1D 35 13 5F 59 4D    98 78 BD AF F0 51 CF FA   .&.5._YM.x...Q..
0010: AD D4 BB 66                      ...f
]
]

Trust this certificate? [no]: yes
Certificate was added to keystore 

Now you can use the KeyStore.jks and the keystore password to create SSLServerSocket, and use the truststore to create client SSLSocket.


-----------------------------------------------------------------------------------------------------------------
Watch the blessing and loving online channel: SupremeMasterTV live




If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book for free here.