Friday, July 11, 2014

Online Tools

INTRODUCTION

This post will give all the available online tools for various technologies. These web tools help the developers to develop the program without installing the software.

HTML EDITORS

CSS EDITORS

XML to JSON CONVERTERS

DATABASE TOOLS

UML DIAGRAM TOOLS

REGULAR EXPRESSION TOOLS

JAVASCRIPT TOOLS

DRAWING TOOLS

Unix Commands

GENERAL COMMANDS

1. Check all environment Variables
$ env
$ printenv
2. Grep Command
grep '2012-03-27' /path/tomcat/apache-tomcat-6/logs/catalina.out | grep '9927773'

SVN COMMANDS

1. Checkout a code base
$ svn checkout <checkout url>

OR
$ svn co <chekout url>
2. Update a code base
$ svn update
3. Check-in/Commit files
$ svn ci -m “commit message”
4. Check current svn check-in details
$ svn info

COPY COMMANDS

1. Copy file from one server to another
We have a file (/prod/myfile.zip) in Server 1 and needs to be copied to Server 2 (/data/test/)
Server 1 (ip: 10.5.55.20) - Source Server
  username: ranjith
  password: sekar   
Server 2 (ip: 10.3.33.90) - Destination Server
  username: anbu
  password: selvan
Now login to Server 1 and enter below command
$ scp /prod/myfile.zip anbu@10.3.33.90:/data/test/
$ <enter password: selvan>

DELETE COMMANDS

1. Delete a folder in current directory
$ rm -rd <folder>
2. Delete a folder and its sub folders
$ rm -rf <folder>

FILE MANIPULATION COMMANDS

1.View Content of a file (less command)
$ less <filename>

1.1 To traverse the file

$ spacebar => Next page
$ b => previous page
$ g => top of the page
$ shift + g -=> bottom of the page

1.2 To search a string

type /<string> and enter
2.Delete a content of file
cat /dev/null &gt; processLog.txt
3. Create shortcut for a file.
ln -fs /folder1/folder1-subfolder/index.html /folder2/folder2-subfolder/

Program to Interface not Implementation

INTRODUCTION

This article will is all about a design concept called “program to interface not implementation”. We could have heard question why "Always program to Interface not to the implementation" in many of the technical discussions.
Here I have tried to explain as clear as possible. It is basically helps to avoid tight coupling on the code.

USECASE

Reading data from various data sources.

IMPLEMENTATION - Program to Implementation

Consider your business requirement to read data from a flat file from the server and use the data for the further analysis.


The Initial Implementation might be below:

Create a program for reading data from flat file.
package com.jbr.generalconcepts.prog2impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class FlatFileDataReader {

 private StringBuilder builder;
 private Scanner scanner;

 public FlatFileDataReader(String fileName) throws FileNotFoundException {
   scanner = new Scanner(new File(fileName));
   builder = new StringBuilder();
 }

 public String read() {
   while (scanner.hasNext()) {
     builder.append(scanner.next());
   }
   return builder.toString();
 }
}

Write a client program to test it.
package com.jbr.generalconcepts.prog2impl;

import java.io.FileNotFoundException;

public class DataReaderMain {

 private FlatFileDataReader flatFileReader;
 private String fileName = "data.txt";

 DataReaderMain() throws FileNotFoundException {
   flatFileReader = new FlatFileDataReader(fileName);
 }

 private String getData() throws FileNotFoundException {
   return flatFileReader.read();
 }

 public static void main(String[] args) throws FileNotFoundException {
   DataReaderMain client = new DataReaderMain();
   System.out.println(client.getData());
 }
}

In any software application, change in the requirement is common. we can't escape from it.


Now, your client asks that your application should read data from the database as well and use it for analysis.


To accomplish this you have modify your DataReaderMain.java class since it will read only data from a Flat file.


Disadvantage with your current DataReaderMain.java class is tightly coupled with the FlatFileDataReader.java


To accomplish the new requirement with less code change would be done using "Program to Interface rather than Implementation".

IMPLEMENTATION - Program to Interface

Create an interface for reading data.
package com.jbr.generalconcepts.prog2interface;

public interface DataReader {
 String readData();
}

Create an implementation for Flat file reader.
package com.jbr.generalconcepts.prog2interface;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class FlatFileDataReader implements DataReader {
 private StringBuilder builder;
 private Scanner scanner;

 public FlatFileDataReader(String fileName) throws FileNotFoundException {
   scanner = new Scanner(new File(fileName));
   builder = new StringBuilder();
 }

 @Override
 public String readData() {
   while (scanner.hasNext()) {
     builder.append(scanner.next());
   }

   return builder.toString();
 }
}

Create an implementation for database data reader.
package com.jbr.generalconcepts.prog2interface;

public class DataDataReader implements DataReader {
 private StringBuilder builder;

 public DataDataReader() throws Exception {
   builder = new StringBuilder();
 }

 @Override
 public String readData() {

   // Code to read database data
   return null;
 }
}

Create a client program to test it.
package com.jbr.generalconcepts.prog2interface;

public class DataReaderMain {

 DataReader fileReader;

 DataReaderMain(DataReader fileReader) {
   this.fileReader = fileReader;
 }

 public String getData() {
   return fileReader.readData();
 }

 public static void main(String[] args) throws Exception {
   DataReaderMain flatFileData = new DataReaderMain(new FlatFileDataReader("data.txt"));
   System.out.println(flatFileData.getData());
   
   DataReaderMain databaseData = new DataReaderMain(new DatabaseDataReader());
   System.out.println(databaseData.getData());
 }
}

Now your new DataReaderMain.java is more flexible and can have only less code change if there are any further business requirement changes.

SUMMARY

  1. Program to interface will avoid tight coupling between multiple implementations
  2. Easy to add new implementations.

Different ways to create object

The below example provides different ways to create object in java

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;

public class ObjectCreation {
  public static void main(String[] args) throws ClassNotFoundException, CloneNotSupportedException,
      InstantiationException, IllegalAccessException, IOException {
    // Way1 - Using new keyword
    ObjectCreation newOperator = new ObjectCreation();
    System.out.println("New Operator: " + newOperator.hashCode());

    // Way2 - Using Class.forName()
    Class classDotForName = Class.forName("javas.ObjectCreation");
    System.out.println("Class Dot For Name: " + classDotForName.hashCode());

    // Way3 - Using clone()
    ObjectCreation anotherObject = new ObjectCreation();
    System.out.println("anotherObject: " + anotherObject.hashCode());
    ObjectCreation clone = (ObjectCreation) anotherObject.clone();
    System.out.println("clone: " + clone.hashCode());

    // Way4 - Using object deserialization
    ObjectInputStream inStream = new ObjectInputStream(null);
    ObjectCreation object = (ObjectCreation) inStream.readObject();

    newOperator.createMethod();

  }

  public void createMethod() throws InstantiationException, IllegalAccessException, ClassNotFoundException {
    // Way5 - using class loader
    ObjectCreation classLoader = (ObjectCreation) this.getClass().getClassLoader().loadClass("javas.ObjectCreation")
        .newInstance();
    System.out.println("classLoader: " + classLoader.hashCode());
  }
}

StringBuffer Vs StringBuilder

The below example provides the performance comparision between StringBuffer & StringBuilder class.


public class StringBufferVsStringBuilder {

  static String dontOptimiseAway = null;
  static String[] words = new String[100000];

  public static void main(String... args) {
    for (int i = 0; i < words.length; i++)
      words[i] = Integer.toString(i);

    for (int i = 0; i < 10; i++) {
      dontOptimiseAway = testStringBuffer();
      dontOptimiseAway = testStringBuilder();
    }

  }

  private static String testStringBuffer() {
    long start = System.nanoTime();
    StringBuffer sb = new StringBuffer();

    for (String word : words) {
      sb.append(word).append(',');
    }

    String s = sb.substring(0, sb.length() - 1);
    long time = System.nanoTime() - start;
    System.out.printf("StringBuffer: took %d ns per word%n", time / words.length);
    return s;

  }

  private static String testStringBuilder() {
    long start = System.nanoTime();
    StringBuilder sb = new StringBuilder();

    for (String word : words) {
      sb.append(word).append(',');
    }

    String s = sb.substring(0, sb.length() - 1);
    long time = System.nanoTime() - start;
    System.out.printf("StringBuilder: took %d ns per word%n", time / words.length);
    return s;
  }

}

OUTPUT

StringBuffer: took 214 ns per word
StringBuilder: took 273 ns per word
StringBuffer: took 199 ns per word
StringBuilder: took 71 ns per word
StringBuffer: took 3740 ns per word
StringBuilder: took 134 ns per word
StringBuffer: took 134 ns per word
StringBuilder: took 61 ns per word
StringBuffer: took 250 ns per word
StringBuilder: took 52 ns per word
StringBuffer: took 65 ns per word
StringBuilder: took 35 ns per word
StringBuffer: took 188 ns per word
StringBuilder: took 43 ns per word
StringBuffer: took 64 ns per word
StringBuilder: took 36 ns per word
StringBuffer: took 213 ns per word
StringBuilder: took 50 ns per word
StringBuffer: took 69 ns per word
StringBuilder: took 38 ns per word

Wednesday, July 9, 2014

Facade Design Pattern

INTRODUCTION

In real life, we always look for an easy way to do our job by finding someone who can take care of our work.

USECASE

Applying for PASSPORT in India. We look for any agency instead we directly go the concerned office and apply with our details.

And we also what are all the process has been carried out and how they can perform to validate our person details to give the passport. Simply we are submitting the details and look for the delivery of the Passport hard-copy to our address.

The passport office does all the verification process for us and finally approves our passport by some verification.

Here the verification process is acting as an Interface, between me & passport office, which accepts my details and finally returns the result (Passport) what I have required.
Very importantly, the Person will not aware of the back-end process.

IMPLEMENTATION

Lets us create Model Class - Person.
public class Person {

 private String name;
 private String address;
 private String phone;
 private String dob;

 public String getDob() {
   return dob;
 }

 public void setDob(String dob) {
   this.dob = dob;
 }

 public String getName() {
   return name;
 }

 public void setName(String name) {
   this.name = name;
 }

 public String getAddress() {
   return address;
 }

 public void setAddress(String address) {
   this.address = address;
 }

 public String getPhone() {
   return phone;
 }

 public void setPhone(String phone) {
   this.phone = phone;
 }
}


Create an interface for the background verification process.

public interface Verification {
 boolean verify(String personDetail);
}

Now verify the person’s phone number.

public class PhoneNumberVerification implements Verification {
 @Override
 public boolean verify(String phone) {
   return true;
 }
}

Verify the address.

public class AddressVerification implements Verification {
 @Override
 public boolean verify(String address) {
   return true;
 }
}

Verify the Date of Birth Certificate.

public class DateOfBirthVerification implements Verification {
 @Override
 public boolean verify(String personDetail) {
   return true;
 }
}


Check whether the person involved in any criminal activity by checking with concerned police station to check about any case filed on him.

public class PoliceCaseVerification implements Verification {
 @Override
 public boolean verify(String personDetail) {    
   return true;
 }
}

Now the passport has to verify all the details one by one and finally approve or disapprove the passport.

public class PassportProcess {

 public static boolean verify(Person person) {
   Verification phoneNumber = new PhoneNumberVerification();
   Verification address = new AddressVerification();
   Verification dob = new DateOfBirthVerification();
   Verification policeCase = new PoliceCaseVerification();

   return phoneNumber.verify(person.getPhone())
       && address.verify(person.getAddress())
       && dob.verify(person.getDob())
       && policeCase.verify(person.getName());
 }
}

Now time to test the facade pattern.

public class PassportOffice {

 public static void main(String[] args) {

   // Person Details
   Person person = new Person();
   person.setName("Ranjith");
   person.setAddress("#5, Gandhi Street, T.Nagar, Chennai");
   person.setPhone("9898989898");

   // Validate the person by calling the facade.
   System.out.println(PassportProcess.verify(person) ? "Passport Approved" : "Passport Rejected");
 }
}

OUTPUT


Passport Approved

Hope this example clarifies the Facade Design Pattern. Please share your thoughts in the comment box.
Happy Knowledge Sharing!!!