Using Java Properties class


In this tutorial we will see about Java Properties class and how to use in our project to read property file values. Most of the time in our project we will be use configuration parameters like database connection details or other parameter related to project. Set the parameters in property file and read throughout the application using Java Properties.

Where here values can be easily modified or even we can add new parameters to the project through property file at run-time without reloading the context or editing any java file. 

project.properties


driver=org.postgresql.Driver
url=jdbc:postgresql://localhost/databasseName
user=postgres
password=postgres
maxconn=10
maxidle=0


import java.io.InputStream;
import java.util.Properties;

public class PropertiesTest {

 public static void main(String[] args) {
  
  String propertyFile = "project.properties";
  
  Properties property = new PropertiesTest().readPropertyFile(propertyFile);
  
  System.out.println("DRIVER   : "+property.getProperty("driver"));
  System.out.println("URL      : "+property.getProperty("url"));
  System.out.println("USER     : "+property.getProperty("user"));
  System.out.println("PASSWORD : "+property.getProperty("password"));
  System.out.println("MAX CONN : "+property.getProperty("maxconn"));
  System.out.println("MAX IDLE : "+property.getProperty("maxidle"));
 }
 
 public Properties readPropertyFile(String propertyFile){
  Properties properties = new Properties();
  InputStream inputstream = getClass().getResourceAsStream(propertyFile);
  try {
   properties.load(inputstream);
   System.out.println("NO OF PROPERTIES ::::: " + properties.size());   
  } catch (Exception e) {
   e.printStackTrace();
  }
  return properties;
 }
}


OUTPUT:


NO OF PROPERTIES ::::: 6
DRIVER   : org.postgresql.Driver
URL      : jdbc:postgresql://localhost/databasseName
USER     : postgres
PASSWORD : postgres
MAX CONN : 10
MAX IDLE : 0







Synchronization in Java

In multi-threading resources will be shared by each thread and they can change or modify the values accordingly. Suppose lets see simple example where 2 people are having joint account in a bank and both are withdrawing cash. 1st person from ATM and 2nd person from bank exactly on same time. In that case only 1 operation can permitted between different users(Multiple Threads) to withdraw cash.  

Synchronization can control the access of multiple threads on shared resources. Without synchronization, it is possible for one thread to modify or to change the shared object while another thread accessing the same object value. This often leads to error and application gets failed. So we can use Synchronization to handle these situations like accessing shared memory or objects. 

Synchronization can be implemented in 2 ways like applying Synchronization to complete method or making a single block to Synchronization. Very important that Synchronization will work only same objects, most of the developers will be misunderstanding with Synchronization on multiple Objects of same class. 

Best example which we have already implemented and tested in Singleton Pattern with Synchronization block. Also below we will see simple example for Synchronization block on Synchronization method.


Main class for both Synchronized method and block testing. 


public class SynchronizationMethod {
 public static void main(String[] args) {
  MyTestThreadClass obj = new MyTestThreadClass();
  for(int i=0;i<10;i++){
   // Same MyTestThreadClass class object passing
   Thread t = new Thread(obj);
   t.start();
  }
 }
}

Synchronized method:


public class MyTestThreadClass implements Runnable{
 
 int i = 0; 
 
 public void run() {
  try{
   incrementValue();
   System.out.println(Thread.currentThread().getName() + ": "+i);
  }catch (Exception e) {
   e.printStackTrace();
  }
 }
 
 private synchronized void incrementValue(){
  try{
   // Not allowing 'i' value to cross 6
   if(i <= 5){    
    // Making thread to sleep for few milliseconds
    Thread.sleep(new Random().nextInt(500));
    i++;
   }
  }catch (Exception e) {
   e.printStackTrace();
  }  
 }
}

OUTPUT:

Thread-0: 1
Thread-8: 2
Thread-9: 3
Thread-7: 4
Thread-5: 5
Thread-1: 6
Thread-6: 6
Thread-4: 6
Thread-2: 6
Thread-3: 6

We have used synchronized method in the above example and we can see the ouput that 'i' value didn't cross value 6. If we remove synchronized keyword in the method and if we test same code then we will get wrong output as like below 'i' value may get more than 6 even we place if condition.  


Thread-3: 1
Thread-6: 2
Thread-0: 3
Thread-8: 4
Thread-7: 5
Thread-5: 6
Thread-4: 7
Thread-2: 8
Thread-9: 9
Thread-1: 10

Synchronized block:

Synchronized method is nothing but applying Synchronized keyword to a block of keywork as like below example. 


public class MyTestThreadClass implements Runnable{
 
 int i = 0; 
 
 public void run() {
  try{
   incrementValue();
   System.out.println(Thread.currentThread().getName() + ": "+i);
  }catch (Exception e) {
   e.printStackTrace();
  }
 }
 
 private void incrementValue(){
  try{
   synchronized (MyTestThreadClass.class) {
    if(i <= 5){    
     // Making thread to sleep for few milliseconds
     Thread.sleep(new Random().nextInt(500));
     i++;
    }
   }   
  }catch (Exception e) {
   e.printStackTrace();
  }  
 }
}

OUTPUT:

Thread-0: 1
Thread-7: 2
Thread-9: 3
Thread-8: 4
Thread-6: 5
Thread-4: 6
Thread-2: 6
Thread-1: 6
Thread-3: 6
Thread-5: 6










Serialization in Java


Serialization is a important topic in Java where we will use to Serialize the Object into a file or database or even in memory buffer and can transmitted across the network. Serialized Object can be de-serialized at any time and can get same state of original Object as same as cloning the Object. 

If we say in simple words Serialization is streaming Java object to a sequence of byte and restoring same objects from the stream. For example we need to save the state of Object at run-time we can use Serialization and store the Object state in a file. If same Object state need to be used in future then we can de-derialization and can make use of the Object.

Basically for implementing Serialization we need to implement java.io.Serializable interface in the class where the Objects get Serialized. In below example we have implemented in MySerializable class where this class Objects get Serialized. Serialization can't be used in various class where we use Threads, Socket etc.,

While we Serialize complete class variables will get Serialized. Suppose if we feel some variables should not be Serialized then we need to mark those variables as transient as like we have made in our below example. Those variables will not get serialized and will give null while when we de-serialize those variables. 

Below are the simple example for Serialization where we are serializing MySerializable class Object into a file and again de-serializing same Object back. Also we have used transient for "company" variable which won't get Serialized.



public class MySerializable implements Serializable {

 private static final long serialVersionUID = 1023;
 
 private int id;
 private String name;
 private String gender;
 transient private String company; // Variable will not to be Serialized
 
 public MySerializable(int id, String name, String gender, String company){
  this.id = id;
  this.name = name;
  this.gender = gender;
  this.company = company;
 }
 
 public int getId() {
  return id;
 }
 public String getName() {
  return name;
 }
 public String getGender() {
  return gender;
 }
 public String getCompany() {
  return company;
 }
 }




public class SerializationSample {

 public static void main(String args[])  {
  try{
   
   MySerializable serialB = new MySerializable(101, "Steve", "Male", "XYZ Inc.,");
   
   // Serializing the Object and storing in a file
   serialize("C:\\serial.out", serialB);
   System.out.println("Serialization completed...");
   
  }catch (Exception e) {
   e.printStackTrace();
  }
 }

 public static void serialize(String file, Object seriObj)
  throws IOException {
  FileOutputStream fos = new FileOutputStream(file);
  ObjectOutputStream oos = new ObjectOutputStream(fos);
  oos.writeObject(seriObj);
 } 
}


OUTPUT:

Serialization completed...




public class DeSerializableSample {
 
 public static void main(String[] args) {
  try{
   
   // De-serializing the Object from the file
   MySerializable obj = (MySerializable) deSerialize("C:\\serial.out");
   
   System.out.println("ID      : "+obj.getId());
   System.out.println("NAME    : "+obj.getName());
   System.out.println("GENDER  : "+obj.getGender());
   System.out.println("COMPANY : "+obj.getCompany());
   
  }catch (Exception e) {
   e.printStackTrace();
  }
  
 }
 
 public static Object deSerialize(String seriObj)
  throws FileNotFoundException, IOException, ClassNotFoundException {
  FileInputStream fis = new FileInputStream(seriObj);
  ObjectInputStream ois = new ObjectInputStream(fis);
  return ois.readObject();
 }
}


OUTPUT:

ID      : 101
NAME    : Steve
GENDER  : Male
COMPANY : null






How to create executable jar file using eclipse

 

In most of the projects and applications we will use jar files. It can be 3rd party or even internal organization jar files. JAR files are nothing but Java ARchive which will be wrapped with the bundle of .class files, Java files, images, audio or video are any file formats. Its nothing but same as ZIP file which we used in our daily practice. 

By using any unzipping tools we can unwrap JAR files to get files inside. Since mainly its used for .class files and by using obfuscate developers can protect their code and implementation from other users.  

JAR files will be of 2 formats. 
1. Non executable JAR file
2. Executable JAR file

In this tutorial we will how to create executable jar using Eclipse and how to run in Windows. Important for creating executable jar file we need to have at-least single main() method in our project which will be executable. 


STEP - 1: Create new project which we need to implement our functionality  In this demo just we will add 2 numbers as like below. We have created Java Project called AddNumbers and we have class called Add2Numbers and we have implemented our code. Run and test the program once we have implemented. 


creating executable jar file using eclipse


STEP - 2: Right click on Project -> Export -> Java -> Runnable JAR file


creating executable jar file using eclipse


STEP - 3: Click Next and select Project and Class name under Launch configuration: <Add2Numbers - AddNumbers>

 Also enter the folder path and name to save the JAR file in Export destination: D:\\test\AddNubers.jar and click Finish. 

creating executable jar file using eclipse


STEP - 4: Next test your executable jar file from command prompt.


creating executable jar file using eclipse






Simple Web Service using SOAP


In one of our earlier tutorial we have seen Web Services in Java and we have discussed about SOAP Web Service and RESTful Web Services along with their differences. As further we will see a simple example for how to create Web Service server and client using SOAP. For this we will use eclipse J2EE IDE and Apache Tomcat as web server.

First we will create simple Server which will take 2 numbers as input and returns the addition of the program. Here by using Eclipse its very simple to create a service and to deploy and publish a service. Everything we can do it just by clicks rather than doing it lot manually. And also using IDE's will make life more easy than manually.

Server Program:

STEP - 1 : Create a Dynamic Web Project (File -> New -> Dynamic Web Project). Create your project by setting your Target run-time server to installed Apache Tomcat web server. In demo I have used Apache Tomcat 7.0 and you can decide your version according to your need. 

Simple Web Service using SOAP


STEP - 2 : Create a new class file under Java Resource by giving package and class name. Then implement the server side method to publish.  

Simple Web Service using SOAP


STEP - 3 : After finishing the server side method implementation, select New -> Others and type "web" in Wizards, where you can see Web Service under Web Services list. 

Simple Web Service using SOAP


STEP - 4 : Click next and select the class which you implemented the method to publish under Service implementation drop down box. As already we are ready with Develop service, so we have to
Assemble service
Deploy service
Install service
Start service 
Test service

to make Web Service server ready with publishing the service which we have implemented. So that just passing the WSDL (Web Services Description Language) to client they can understand the server implementation and can consume our service easily. Basically its XML which used to describe the functionality offered or published by a web service. For more details on WSDL you can refer to WSDL wiki.

Simple Web Service using SOAP


STEP - 5 : Our Web Service server created successfully and we are ready to test our service. In next screen you can see SOAP Binding and service created with WSDL. You can pass input parameter and can test the service as below 

Simple Web Service using SOAP


And also we can see SOAP request and response by switching from form to source in result tab as below. 

Simple Web Service using SOAP


STEP - 6 : Next you can check your WSDL file have created correctly or not in your web browser by passing. http://localhost:8080/MyServer/services/MyClass?wsdl

Simple Web Service using SOAP



We have done with server implementation by creating the service and publishing with the help of Eclipse of IDE. Next important that we are going to localhost as our web server so we should not stop the server which running. In real-time we will deploy our service in some web servers and we will access our service through internet. Where as for our demo we are localhost for both server and client. 

Next go-head and create the client and consume the service which we have published above. For that we need to create the client application given below. 


Client Program:

STEP - 7 :  Create a Dynamic Web Project (File -> New -> Dynamic Web Project).

Simple Web Service using SOAP


STEP - 8 : Next we need to create stub from WSDL file. For this server where we have published need to be running and as discussed above we haven't stopped the server which we have started while creating our server. 
For creating Web Service Client we need to select New -> Other and type "web" in the Wizards as given below and select the Web Service Client under Web Services tab.

Simple Web Service using SOAP


STEP - 9 : Click Next and pass the WSDL url in Service definition text box and set as Test client and click Finish which will read the WSDL file and generate the java stub code. 

Simple Web Service using SOAP


Once you finished we can see the Java stub created along with Service and Proxy classes. Next we can see the list of method(s) published by server. By selecting the method we can test directly from eclipse by giving inputs as below image.

Simple Web Service using SOAP


STEP - 10 : Next we need to write a client program to invoke the remote method using SOAP Web Services. Create new class called MyClient as below image.

Simple Web Service using SOAP


STEP - 11 : Just implement the client by using endpoint URL and service instance and test your Web Service using SOAP.

Simple Web Service using SOAP







Deep Copy in Java


Deep Copy in Java
In our earlier tutorial we have seen about Shallow copy and how we can implement and how its works in Java. Same way we will see about Deep copy in this tutorial.

Deep copy - by name itself we can identify as its copy complete Object in-depth while cloning any instance. In Shallow copy we have seen that Object which holds another Object will not be copied and only holds the address reference. Where as in Deep copy it copies those Objects also and creates the instance for those Objects. Apart from this difference Deep copy is same as Shallow copy like, explicitly we need to type cast to our class and Constructors will not be called in our cloning class, but Object which contains other Object class constructors will be called while cloning from clone() method instance creation. 


We will see same example which we have seen in Shallow copy and make changes only in our clone() method to implement Deep Copy.


public class Subject{
 
 String name;
 
 public Subject(){
  System.out.println("Inside Default Constructor");
 }
 
 public Subject(String name){
  System.out.println("\nInside Constructor");
  this.name = name;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 } 
}



public class Student implements Cloneable{

 String name;
 Subject sub;
 
 public Student(String name, String sub){
  this.name = name;
  this.sub = new Subject(sub);
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public Subject getSub() {
  return sub;
 }
 public void setSub(Subject sub) {
  this.sub = sub;
 } 
 
 @Override
 protected Object clone() throws CloneNotSupportedException {
  return new Student(name, sub.getName());
 }
}



public class DeepCopy {

 public static void main(String[] args) throws CloneNotSupportedException {
  
  Student stu = new Student("Raj", "Hindi");
  
  System.out.println("\nOriginal Student Name: "+stu.getName());
  System.out.println("Original Student Sub : "+stu.getSub().getName());
  
  // Cloning the original Object and Explicitly type casting 
  Student stu1 = (Student)stu.clone();
  
  System.out.println("\nClone Student Name: "+stu1.getName());
  System.out.println("Clone Student Sub : "+stu1.getSub().getName());
  
  stu1.setName("David");
  
  
  /*
   * In Deep copy cloned Object will hold complete copy of original Object
   */
  stu1.getSub().setName("Tamil");
  
  System.out.println("\nOriginal Student Name: "+stu.getName());
  System.out.println("Original Student Sub : "+stu.getSub().getName());
  
  System.out.println("\nClone Student Name: "+stu1.getName());
  System.out.println("Clone Student Sub : "+stu1.getSub().getName());
 }
}


OUTPUT:


Inside Constructor

Original Student Name: Raj
Original Student Sub : Hindi

Inside Constructor

Clone Student Name: Raj
Clone Student Sub : Hindi

Original Student Name: Raj
Original Student Sub : Hindi

Clone Student Name: David
Clone Student Sub : Tamil



In above output we can see Subject name ("Tamil") has changed only for the cloned Object, where as in Shallow copy it holds the address of Object.