Wednesday, February 17, 2021

Install Apache Tomcat mod_jk on CentOS

 How to install mod_jk module in Apache webserver on CentOS

Installing mod_jk on Apache (CentOs). 

Required software

  1. CentOS 7+
  2. Apache 2.4.x
  3. Tomcat Connectors 1.2.48

Installation

Thursday, September 29, 2016

String in Java (Why String is Immutable in Java)

String, which are widely used in any programming language as Java. String is a sequence of characters. In Java Strings are Object. As same as other object Strings instance will be created by new keyword, as follow:

     String s = new String();

This line of code will create new object of String and assign it to reference object “s”. String seems just like other object. Now let’s assign value to it:

     s = "Hello Java";

There are so many construction available for the String object, more efficient will be

     String s = new String("Hello Java");

And below is the more concise

     String s = "Hello Java";

String are Immutable Object


Once you assign value to String, that value can never been change – it’s Immutable. But although String is immutable, its reference variable is not. Confuse let see example, consider this using same above reference:

     s.concat("World"); //Append value "World" at the end of string "s"

Java Virtual Machine(JVM) took value of s (which was “Hello Java” ) and append it with “World” at the end of string “s”, end return as “Hello Java World”.

If you try to print value of reference variable value is still “Hello Java”. We have applied concat function on string but still value is not changed, so why this behaviour?

Since String is immutable JVM shouldn’t append this new string to old one, instead it created a new string “Hello Java World”. If you want to assign this new value to old reference variable you need to assign it back to “s” as shown below:

     s = s.concat("World");

Now reference variable s is contain value “Hello Java World”.

String is store in Heap but there is special segment or part assign to call “String Pool”, where all String value is reside. As shown in below figure:



As shown in figure there are total three string is created. Initially reference “s” is refer to string “Hello Java” in string pool.

After concat is function is applied to “s”, the original unchanged string containing “Hello Java” would still exist in memory, but it would be consider as “Lost”. No code in our program has any way to refer it – it is lost to us. 

Keep in mind, that the original string “Hello Java” didn’t changed, only the reference variable “s” was changed so that it would refer to a different new string in string pool, as shown in below figure (old reference is indicate with dotted line)

To make Java more memory efficient the JVM set this String Pool concept. When compiler encounter a String literal, it check the pool to see if an identical String is already exist. If match is found, the reference to new literal is directed to the existing String, and no new String literal object is created.

Now you can see that why making String object immutable is such a good idea. If several reference variable refer to the same String without even knowing it, it would be very bad if any of them could change String’s value.

You might think that what if someone override String class functionality, couldn’t that cause problem in pool? That’s one of the main reason why String class is marked final. Nobody can override the behaviour of any of the String methods, so you can assured that the String object to be immutable.


Important methods in String class

  • ·        charAt() – Return character located at the specified index
  • ·        concat() – Append one String to the end of another
  • ·        equalsIgnoreCase() – Determine the equality of the two string, ignoring case
  • ·        length() – Return the number of character in String
  • ·        replace() – Replace occurrences of a character with new character
  • ·        substring() – Return part of the String
  • ·        toLowerCase() – Return a String, with uppercase characters converted to lowercase
  • ·        toString() – Return the value of String
  • ·        toUpperCase() – Return a String, with lowercase characters converted to uppercase
  • ·        trim() – Removes whitespace from both ends of a string  

Thursday, September 10, 2015

How to convert JSON to / from Java Object (Pojo) using GSON


JSON is stand for JavaScript Object Notation. It is light wight interchange format used over network communication between client and server. It is easy for human to read and write because it is in simple Text format. JSON is completely language independent.

In this article i will show you how to convert Java Object into JSON notation using GSON Library.
You can Download Gson Library here Or you can add dependency in your pom.xml as show below
        <dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>1.7.1</version>
       </dependency>

JSON contain two types of structure

  1. A collection of the Key:Value pair which is referred as Json Object. For Example : {"Key":"Value"} 
  2. Collection of value in form of list which is referred as Json Array. For Example : {"Array":["1","2","3"]}
For this article we need to now only two function in GSON library
  1. toJson() - Convert your Java object into Json format.
  2. fromJson() - Convert your Json string to Java Object. 

Java Pojo Class
             
Here is my Java Bean class with construction which is used to initialize value to my bean class object later this class will be used to convert into JSON format.

package com.java.gson;
import java.util.List;

public class MyBeanClass
{
       int srNo;
       String name;
       List<String> list;
      
       public MyBeanClass(int srNo,String name,List<String> list) {
             this.srNo = srNo;
             this.name = name;
             this.list = list;
       }
      
       public int getSrNo() {
             return srNo;
       }
       public void setSrNo(int srNo) {
             this.srNo = srNo;
       }
       public String getName() {
             return name;
       }
       public void setName(String name) {
             this.name = name;
       }

       public List<String> getList() {
             return list;
       }

       public void setList(List<String> list) {
             this.list = list;
       }
     
      @Override
       public String toString() {
             return "Data : [srno : "+srNo+", name : "+name+", list : "+list+"]";
       }
}

toJson() Example 

In this example we will see that how java object will be converted into JSON string. You may store or save this into file or passed this string across network. 

package com.java.gson;

import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;

public class JsonExample
{
       public static void main(String[] args)
       {
             List<String> list = new ArrayList<String>();
             try
             {
                    list.add("Json");
                    list.add("Gson");

                    MyBeanClass myBean = new MyBeanClass(1, "Java",list);

                    Gson json = new Gson();
                    String jsonStr = json.toJson(myBean);

                    System.out.println(jsonStr);
             }
             catch(Exception ex)
             {
                    ex.printStackTrace();
             }
       }
}

In above example json.toJson(myBean) is used to convert your Java bean class to Json format string.

Output : 

         {"srNo":1,"name":"Java","list":["Json","Gson"]}


fromJson() Example 

You can convert your JSON string to Java Object using this function. There is some rules to convert your Json String to Java Object.
  1. Properties in Java Object will match with the Key or properties name in Json String.
  2. If Json string contain property that is not present in Java bean class than its value will not be reflected in Java Bean. 

package com.java.gson;

import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;

public class JsonExample
{
       public static void main(String[] args)
       {
             String str = "{\"srNo\":1,\"name\":\"Java\",\"list\":[\"Json\",\"Gson\"]}";
             try
             {
                    Gson json = new Gson();
                    MyBeanClass bean = json.fromJson(str, MyBeanClass.class);

                    System.out.println(bean);
             }
             catch(Exception ex)
             {
                    ex.printStackTrace();
             }
       }
}

You may used .fromJson() function with FileReader or BufferedReader or InputStreamReader 
to directly read from network or from file where you have save Json string.


Reference
  1. Google Gson -  https://github.com/google/gson
  2. Gson User Guide - https://sites.google.com/site/gson/gson-user-guide#TOC-Goals-for-Gson
  3. Json Wiki - https://en.wikipedia.org/wiki/JSON
  4. Json Official Website - http://json.org/




Tuesday, June 30, 2015

How to import SSL certificate in Java

In this article we see that how to add certificate authority (CA or PFX) certificate to the Java CA certificate (cacerts) store. Here I will show you how to add .pfx certificate that is generated from the IIS server to automatically authenticate while making connection to server. This is normally used for the client authentication and termed as the two way SSL Authentication 

You cannot directly use .pfx file and import it to java keystore, you need to convert it into PKCS12 (.p12) and load dynamically using java code. Java keytool is capable of doing this using some keytool import command show in below although it is only available from JDK 1.6 or later

You can learn more about keytool documentation at Java Doc here.

To add a certificate to the cacerts KeyStore or Java Keystore


  1. Go to the directory where your .pfx file is present. I hope that you have set JAVA_HOME environment variable so that you can directly execute keytool command ( to check it execute “java –version “ command from command prompt)
  2. Convert .pfx file to .jks file using “keytool –import “ command. Go to folder where your file is located and execute following command :
          keytool -importkeystore -srckeystore mykey.pfx -srcstoretype pkcs12 -destkeystore clientcert.jks -deststoretype JKS
           
          Attribute Details:- 
          -importkeystore – Imports a single entry or all entries from a source keystore to a destination keystore.
          -srckeystore – Source file path 
        -srcstoretype – Source file key store type  
  -destkeystore – Destination file path
          -deststoretype – Destination file key store type

     3. Now next step is to convert your .jks file to .p12 file which is used by java to add it to keystore.
        To do this below is command to execute

            keytool -importkeystore -srckeystore clientcert.jks -destkeystore KEYSTORE.p12 -srcstoretype JKS -deststoretype PKCS12 -srcstorepass srcstorekeypassowrd -deststorepass deststorekeypassowrd -srcalias srcaliasname -destalias myalias -srckeypass srcstorekeypassowrd -destkeypass deststorekeypassowrd –noprompt

           In above command you need to pass source key password which you will get from the key provider or where your .pfx file is generated. 
           
           Source alias is alias name present in the key file you can find it by below command

           keytool -list -storetype pkcs12 -keystore mykey.pfx -v | grep Alias
        4. Now your .p12 file is ready to include it in Java Keystore by below command

            keytool -importcert -trustcacerts -alias myalias -file KEYSTORE.p12 -keystore /usr/local/java7.45/jre/lib/security/cacerts -storepass changeit
            
             java keystore path is path where your java is install. “cacerts” is file present in java where all your certificate are store, and to add new certificate it has default password “changeit”

Include certificate in Java code

           Now you need to include this certificate .p12 to every request made from java code to remote server. Sample program for this is given below.

       public void callWebservice(String webserviceUrl, String requestData)
       {     
          HttpsURLConnection con = null;   
          String certificateFilePath,certificatePassword;
          Gson gson = new Gson();
          OutputStreamWriter dos = null;
          InputStreamReader dis = null;
          try
          {            
             certificateFilePath = "WEBSERVICE_CERTIFICATE_FILE_PATH"//Certificate file path
             certificatePassword = "WEBSERVICE_CERTIFICATE_PASSWORD";   //Certificate keystore password
                   
             //Load your certificate in keystore
             char[] passw = certificatePassword.toCharArray();
             KeyStore ks = KeyStore.getInstance("PKCS12");
             InputStream keyInput = new FileInputStream( certificateFilePath);

             ks.load(keyInput, passw );
             keyInput.close();

             //Add your certificate in trustmanager factory
             KeyManagerFactory kmf =                                                                  KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
             kmf.init(ks, passw);

             //Include your certificate in SSL request
             SSLContext sclx = SSLContext.getInstance("SSL");
             sclx.init( kmf.getKeyManagers(), null, new SecureRandom());
             SSLContext.setDefault(sclx);
                                                                                                        HttpsURLConnection.setDefaultSSLSocketFactory(sclx.getSocketFactory());

             URL url = new URL(webserviceUrl);
             con = (HttpsURLConnection)url.openConnection();

             if(con!=null)
             {
                con.setRequestProperty("Content-Type","application/json;charset=utf-8");
                con.setRequestProperty("Accept", "application/json");
                con.setRequestProperty("Accept-Charset", "UTF-8");
                con.setDoOutput(true);
                con.setDoInput(true);
                con.setUseCaches(false);
                con.setDefaultUseCaches(false);
                con.setRequestMethod("POST");
                con.connect();
             
                dos = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
                dos.write(requestData);
                dos.flush();

                dis = new InputStreamReader(con.getInputStream(),"UTF-8");

                 if (null != dis)
                 {                         
                    BufferedReader reader = new BufferedReader(dis);
                    String line,strbuf = null;
                    if((line = reader.readLine()) != null) {
                        strbuf = line;
                    }
                    System.out.println(strbuf);
                    reader.close();                         
                  }
                }
           }
           catch(IOException ioex)
           {            
               System.out.println("IO Exception "+ioex.getMessage());
               ioex.printStackTrace();
           }
           catch(Exception ex){
               System.out.println(" Exception "+ex.getMessage());
               ex.printStackTrace();            
           }
           finally{
              try{
                   if(dos != null) {
                        dos.close();
                   }
                   if(dis != null) {
                       dis.close();
                   }
                 }
              catch(Exception ex)
              {
                 System.out.println("Exception in close IO stream"+ex.getMessage());
                 ex.printStackTrace();     
              }
          }
    }
Above example will send your request with certificate include using SSL configuration.


Please let me know if you have any query regarding this. You may write your question in comment section i will tried to give answer as soon as possible.