Page Count

Wednesday, December 16, 2015

Project or Build Version Numbers

In Software world, every project/product release has one version number associated with it to identify on which version of code base it has.

Usually every project/product release has its version as follows.

(Major).(Minor).(Maintenance/Enhancements).(Build Number)

Major - If the release has Major changes in Project/Product then we need to increment this number by 1
Minor -   If the release has Minor changes in Project/Product then we need to increment this number by 1
Maintenance - If the release has Bug fixes or Small Enhancements then we need to increase this number by 1.

Build Number :  Every time when we deliver build (latest code) to the QA to test, then we need to increase by 1.

Partial Builds: If only some of the modules in the project modified and if those modules only delivered to QA means, it is called as partial builds. And this will be noted as build number along with alphabets.


E.G of Build Numbers.

Current Version of Project is 4.0.0.0 (4 Major Releases)
If Minor Project got released in next release. then it would be 4.1.0.0

After 4.1, some bug fixes got released, then it would be 4.1.1

For doing above we have delivered 4 builds to QA before Production  release then
version would be

4.1.1.1
4.1.1.2
4.1.1.3
4.1.1.4

Final release would be 4.1.1

E.G of Partial Build Numbers:

4.1.1.1
4.1.1.1a
4.1.1.1b
4.1.1.1c

4.1.1.2
4.1.1.2a

4.1.1.3
4.1.1.3a
4.1.1.3b

4.1.1.4






 

Linux Useful Commands with examples

To know the IP address
-----------
hostname -i (ip addres)
hostname -s (short name)
hostname -d (domain name)
hostname -v (host name with domain name)


To know the port number and running processes
netstat -ano | findstr 80

If the file is huge in size and to see the file content we can use
less <file name>
e.g. less service.log

Searching  matching pattern in file
grep '<matching text>' <file name>
e.g. grep 'Exception' service.log

To grep the text from .gz files
gzgrep '<matching text>' <gz file name>
e.g. gzgrep 'Exception' service.log.gz

ps -eaf | grep java
ps aus | grep java

tail -f <file Name> (auto updated last few lines)
tail -100 logfile.log  (last 100 lines)

ls -a  (hidden files)
ls -lrt (Sort the files by time stamp)

kill -9 <Process ID>   (get Process ID using ps -eaf | grep <process name>)
e.g. kill -9 30102

ClassNotFoundException vs NoClassDefFoundError

Both ClassNotFoundException and NoClassDefFoundError errors will be occurred  when the required Class not present in the Class path.
   
ClassNotFoundException
   
ClassNotFoundException is an Exception got arized when trying load class using
forName() method in class Class.
findSystemClass method in class ClassLoader .
loadClass method in class ClassLoader.

e.g. Class.forName("oracle.jdbc.driver.OracleDriver")
if the OracleDriver class file is not present in the Class path, then we will end up with this ClassNotFounException

NoClassDefFoundError

NoClassDefFoundError is an Error thrown at Runtime, when the Class is present during the compile time and not present during Runtime of the Code, then we will end up with this NoClassDefFoundError.

1. When required Class is not available at Runtime available only in compile time.
2.Since NoClassDefFoundError error is an Subclass of LinkageError, it will occur when one of the     Dependent of the jar not present in class path.
3. When the Static initialization of Class failed then it triggers java.lang.ExceptionInInitializerError
 which also leads to this Error.

e.g.  Exception in thread "main" java.lang.NoClassDefFoundError

Tuesday, December 15, 2015

Content Extracting From 'CLOB' type Columns in SQL Querries

Extracting XML node value from CLOB  column in data base.

Syntax

ExtractValue(xml_fragment, xpath_expression)

Query Syntax

Select Extractvalue(XMLtype('<column name>'),'<XML node path>')
From <table list>
Where <conditions>

Example

Select Extractvalue(Xmltype(emp_xml), '/employees/empployee/emp_number')
From employee 
where  Status='A';

Updating a XML node value from CLOB  column in data base.

Syntax


UpdateXML(xml_target, xpath_expr, new_xml)

Query Syntax

Update table_name Set column_name=Updatexml(Xmltype('<column name>'),'<XML node path>','<Replacing XMLvalue'>).getclobval
From <table list>
Where <conditions>;

Example

Initial value /employees/empployee/emp_name/text() = Bhargava

Update employe Set emp_name = Updatexml(Xmltype(emp_xml), '/employees/empployee/emp_name/text()','Bhargava Surimenu')
where  emp_no=1207;

Comparator Vs Comarable

Comparable Interface

Comparable is an interface in java, which has only comparTo (Object Obj) method in it.
This is used to sort the user defined objects on specific member field.


When Comparable is preferred.

1. Having provision of modifying the User defined object to implement the Comparable interface. (Third party jar class objects doesn't have provision to modify).
2. Have a requirement to sort the User defined object by one Member field in their natural sorting order.
3. Comparable provides only one Sorting for an Object.

Our String and Wrapper Classes like Integer, Double, Long, BigDecimal etc. are override this compareTo method by implementing the Comparable Interface.


For example,
To sort the Bank Accounts  based on the amount it contains.

1. Create Account pojo with all the member fields including amount.
2. Implement the Account pojo with Comparable interface.
3. Override the compareTo(Object obj) method from Comparable interface. (Refer following code snippet)

Account POJO

package com.sbs.sort;

import java.math.BigDecimal;

public class Account implements Comparable<Account>{

    private BigDecimal ammount;
    private Long accountNumber;
    private String accountHolderName;
   
    public Account(BigDecimal ammount, Long accountNumber,
            String accountHolderName) {
        super();
        this.ammount = ammount;
        this.accountNumber = accountNumber;
        this.accountHolderName = accountHolderName;
    }

    public BigDecimal getAmmount() {
        return ammount;
    }

    public void setAmmount(BigDecimal ammount) {
        this.ammount = ammount;
    }

    public Long getAccountNumber() {
        return accountNumber;
    }

    public void setAccountNumber(Long accountNumber) {
        this.accountNumber = accountNumber;
    }

    public String getAccountHolderName() {
        return accountHolderName;
    }

    public void setAccountHolderName(String accountHolderName) {
        this.accountHolderName = accountHolderName;
    }

    @Override
    public int compareTo(Account o) {
        return this.ammount.compareTo(o.getAmmount());
    }
}

ComparableSortTest 

package com.sbs.sort;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ComparableSortTest {

    public ComparableSortTest() {
    }
    public static List<Account> accountsList = new ArrayList<Account>();
   
    static
    {
        accountsList.add(new Account(new BigDecimal("200000"),10010l,"Bhargava Surimenu"));
        accountsList.add(new Account(new BigDecimal("20000"),100102l,"Satya Surimenu"));
        accountsList.add(new Account(new BigDecimal("100000"),100104l,"Hemachandra Surimenu"));
        accountsList.add(new Account(new BigDecimal("600000"),100106l,"Neha Surimenu"));
        accountsList.add(new Account(new BigDecimal("30000"),100108l,"Veeru Surimenu"));
        accountsList.add(new Account(new BigDecimal("700000"),100109l,"Venky Surimenu"));
    }
   
    public static void main(String[] args) {
       
        System.out.println("----- Accounts List Before Sort ------");
        System.out.println("Account   "+"Ammount");
        for(Account account:accountsList)
            System.out.println(account.getAccountNumber()+"   "+
                    account.getAmmount());
       
        //Sort
        Collections.sort(accountsList);
       
        System.out.println("----- Accounts List After Sorting ------");
       
        System.out.println("Account   "+"Ammount");
            for(Account sAccount:accountsList)
                System.out.println(sAccount.getAccountNumber()+"   "+
                        sAccount.getAmmount());
    }
}



Comparator Interface

Comparator is an interface in java, which has only compare(Object Obj) method in it.
This is used to sort the user defined objects on specific member field.


When Comparator is preferred.

1. Having no provision of modifying the User defined object
(Third party jar class objects doesn't have provision to modify).
2. Have a requirement to sort the User defined objects by various member fields in their natural sorting order.
3. Comparator interface provides multiple comparators (Sortings)for an Object.


For example,
To sort the Employee based on the employee number it contains.

1. Create Employee pojo with all the member fields including amount.
2. Create a Employe Comparator and Implement the with Comparator interface.
3. Override the compare(Object obj) method from Comparator interface. (Refer following code snippet).
4. Pass the employee Comparator as argument to the Sort method.

Employee 

package com.sbs.sort;

import java.math.BigDecimal;


public class Employee {

    public Employee() {
       
    }

   
    public Employee(String name,String number, BigDecimal salary) {
        super();
        this.name = name;
        this.number = number;
        this.salary = salary;
    }


    private String name;
    private String number;
    private BigDecimal salary;
   
   
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
   
    public String getNumber() {
        return number;
    }
    public void setNumber(String number) {
        this.number = number;
    }
    public BigDecimal getSalary() {
        return salary;
    }
    public void setSalary(BigDecimal salary) {
        this.salary = salary;
    }
   
   
}

EmpComparator 

package com.sbs.sort;

import java.util.Comparator;

public class EmpComparator implements Comparator<Employee>{

     public EmpComparator() {
       
    }

    @Override
    public int compare(Employee emp1, Employee emp2) {
        return (emp1).getNumber().compareTo(emp2.getNumber());
    }
}


ComparatorSortTest
 
package com.sbs.sort;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ComparatorSortTest {

    public ComparatorSortTest() {
       
    }
   
    public static List<Employee> employeeList = new ArrayList<Employee>();
    static
    {   
       
        employeeList.add(new Employee("Bhargava Surimenu","SBS101",new BigDecimal("1000")));
        employeeList.add(new Employee("Satya Surimenu","SBS108",new BigDecimal("2000")));
        employeeList.add(new Employee("Hemachandra Surimenu","SBS106",new BigDecimal("6000")));
        employeeList.add(new Employee("Satya Surimenu","SBS105",new BigDecimal("7000")));
        employeeList.add(new Employee("Neha Surimenu","SBS107",new BigDecimal("8000")));
        employeeList.add(new Employee("Veeru Surimenu","SBS102",new BigDecimal("3000")));
        employeeList.add(new Employee("Venky Surimenu","SBS104",new BigDecimal("1000")));
       
    }
   
    public static void main(String[] args) {
       
        System.out.println("----- Employees List Before Sort ------");
        System.out.println("Number   "+"Name");
        for(Employee emp:employeeList)
            System.out.println(emp.getNumber()+"   "+
                    emp.getName());
       
        //Passing EmpComparator as argument
        Collections.sort(employeeList,new EmpComparator());
       
        System.out.println("----- Employees List After Sorting ------");
       
        System.out.println("Number   "+"Name");
        for(Employee emp:employeeList)
            System.out.println(emp.getNumber()+"   "+
                    emp.getName());
    }
}

Thursday, December 3, 2015

"immutability" Nature of an Object

Immutability.

A Java object is considered to be immutable when its state (properties and contents) cannot change after it is created.

Use of immutable objects is widely accepted as a sound strategy for creating simple, reliable code. Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state. java.lang.String and java.lang.Integer classes are the Examples of immutable

Immutable objects are simple to use test and construct.
Immutable objects are thread-safe by default.
Immutable objects are good Map keys and Set elements (Since state of these objects must not change while stored in a collection). This is the reason most of the times we prefer String objects as Key in many Map Collection objects.
Immutable objects do not require an implementation of clone.
Immutable objects allow hashCode to use lazy initialization, and to cache its return value.


To create a object immutable

Need to make the class final and all its member final so that once objects gets crated no one can modify its state.
Or
By making member as non final but private and not modifying them except in constructor. Also its NOT necessary to have all the properties final since you can achieve same functionality by making member as non final but private and not modifying them except in constructor.

Monday, November 30, 2015

Insertion Sort With Time Complexity

package com.sbs.sort;

/**
 * @author Bhargava
 *
 * Time Complexity of Insertion Sort is O(n power 2) Worst Case  O(n) best case

 * Recommended for Smallest array of elements.

 * If you observe Array.sort() method in java.util api, if the array length is smaller than 7 our api is following     * insertion sort.


 */
public class InsertionSort {

    /**
     * @param args
     */
    public static void main(String[] args) {

        long intialTime = System.currentTimeMillis();
        int[] array = { 24, 13, 9, 64, 7, 23, 34, 47 };
      
        System.out.print(" Befor Sorting [ ");
        for (int j = 0; j < array.length; j++) {
            System.out.print(array[j] + " ");
        }
      
        for (int i = 1; i < array.length; i++) {
            int j = i - 1;
            int temp = 0;
            while (j >= 0) {
                if (array[j + 1] < array[j]) {
                    temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                }
                j--;
            }

        }

        System.out.print(" After Sorting [ ");
        for (int j = 0; j < array.length; j++) {
            System.out.print(array[j] + " ");
        }
        System.out.print("]");

        System.out.println(" Time Lapse :"
                + (System.currentTimeMillis() - intialTime) + " ms ");
    }

}

String Pool Vs String Definition (Using 'new' Operator)

Strings can be defined in Java in two ways.

1. String Literals
2  Traditional way(using 'new' operator)

String Literals

If a String is created by using String literal notation, memory will be allocated directly in string pool.
String pool is subset of Heap memory (Where objects will be created).

e.g. String companyName = "Surimenus";
     String empName= "Bhargav";
     
Using 'New' Operator

If a String is created using new operator, memory will be allocated in Heap Memory not in String pool.

e.g.

String companyName = new String("Surimenus");
String empName= new String("Bhargav");


String Pool vs Using 'new' Operator

String which are created in String pool will re-reference by reference which contains the same content.


For example consider the following.

String cn1 = "Surimenu";
String cn2 = "Surimenu";

In the above scenario cn1 and cn2 references having the same content and these are created in String Pool. So for only one Object memory will be allocated for the two references (cn1 and cn2)


For suppose if you create String Objects as follows.

String cn1 = new String("Surimenu");
String cn2 = new String("Surimenu");

In the above scenario cn1 and cn2 references having the same content and these are created in Heap memory. So memory will be allocated for two Objects for two references (cn1 and cn2).



















Sunday, November 29, 2015

Self Signed Certificates Vs Signed Certificates (CA Certificates)

Certificates

Certificates basically two categories.
Self Signed Certificates  - will create by self
CA Certificates  - will be  provided by Third party vendor with robust algorithms

Depends on the location of installing the certificate these are two types
1. Public Key Certificates (Client Side)
2. Private Key Certificates (Server Side)

Self Signed Certificates

 
If any one is using self signed certificates in their applications
they have to make sure both server side and client side certificates are in sync.
Other wise we should be ready to face SSLHandShake Exceptions. These will be preferable mostly for lower environments not for production.

CA certificates 


If you install CA certificates on server side, client side certificates are installed automatically whenever they access the server. So in production for CA certificates there is no need to install the client side certificates.

We can generate a Self Signed Certificate using Java Key tool
JAVA_HOME/bin/keytool.exe








Connection Time out Vs Socket Time out

Time out
Any client(or source) which is unable to connect to the server (or Destination) in a specified time, then requests will automatically gets time outs.

Port
Port numbers allow different applications on the same computer to utilize network resources without interfering with each other. Port numbers most commonly appear in network programming, particularly socket programming. Sometimes, though, port numbers are made visible to the casual user. For example, some Web sites a person visits on the Internet use a URL like the following:

http://www.appdomain.in:80/ In this example, the number 80 refers to the port number used by the Web browser to connect to the Web server. Normally, a Web site uses port number 80 and this number need not be included with the URL (although it can be).

Port 80 is the default port for HTTP

Socket
Each and every communication from one application to another application should happen through sockets. Socket is gateway to send/receive information from one application to another.

A TCP socket is not a connection, it is the endpoint of a specific connection.
Every connection between a client and server requires a unique socket.
Applications can create multiple sockets for communicating with each other.
Sockets are bidirectional, meaning that either side of the connection is capable of both sending and receiving data

A socket contains following parameters

    An IP address
    A transport protocol
    A port number

A socket = Transport protocol + IP Address + a port (numeric address)   


   
Connection Time out Vs Socket Time out

Connection time outs will occur when requests are not able to reach remote machine on the specified
Host name/IP on specified port number under specified time.

So this Connection time outs can occur or can be simulated
1.By providing the incorrect host names or Port numbers.
2.By providing the time out period which is less than the actually it takes.
  This has to set at the code level while we creating the connection.

Socket time out will occur when requests are not able to reach the application which is running in local or remote machines.

So this socket time outs
1. By providing the time out period which is less than the requests actually takes.
2. Shut down the application which client is trying to connect.

Monday, October 26, 2015

Date Utility Class in Java

/**
 * Date Util might be useful in your daily activities.
 */
package com.sbs.dateutil;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @author bhargav
 *
 */
public class DateUtil {

    /**
     *
     */
    private DateUtil() {

    }

    /**
     * @param args
     */
    public static void main(String[] args) {

        //Date date = new Date();
        //Another way to get the current date from Calender object is
        Date utilDate = Calendar.getInstance().getTime();
       
        System.out.println("Default Util Curent Date and time :" + utilDate);
        SimpleDateFormat DATE_FORMAT = null;

        DATE_FORMAT = new SimpleDateFormat("dd-MM-YYYY");
        System.out.println("dd-MM-YYYY Formatted Date " + DATE_FORMAT.format(utilDate));

        DATE_FORMAT = new SimpleDateFormat("dd-MM-YY");
        System.out.println("dd-MM-YY Formatted Date " + DATE_FORMAT.format(utilDate));
       
           //Capital HH denotes hours in 24 hours format where as
          //Small 'hh' denotes 12 hours format in 'am' and 'pm'
        DATE_FORMAT = new SimpleDateFormat("dd-MM-yyyy:HH:mm:SS");
        System.out.println("dd-MM-yy:HH:mm:SS Formatted Date  " +                     DATE_FORMAT.format(utilDate));

        //HH denotes hours in 24 hours format where as 'hh' denotes 12 hours format in 'am' and 'pm'
        DATE_FORMAT = new SimpleDateFormat("dd-MM-yyyy:HH:mm:SS Z");
        System.out.println("dd-MM-yy:HH:mm:SS Z Formatted Date  " + DATE_FORMAT.format(utilDate));

        DATE_FORMAT = new SimpleDateFormat("MM/dd/yyyy");
        System.out.println("MM/dd/yyyy Formatted Date " + DATE_FORMAT.format(utilDate));
       
        //Default SQL Date
        java.sql.Date sqlDate = new java.sql.Date(new Date().getTime());
        System.out.println(" java.util.Date into java.sql.Date --> "+sqlDate);
       
        //SQL Date in YYY-MM-dd format
        System.out.println("Default Util Date :" + new SimpleDateFormat("YYY-MM-dd").format(utilDate));
       
       
        //Be always remember that Converting java.util.Date to java.sql.Date will lose the hours,minutes and seconds
        //converting Util Date to Sql Date
        java.sql.Date sqlDate1 = getSqlFromUtilDate(utilDate);
        System.out.println(" java.util.Date into java.sql.Date --> "+sqlDate1);
       
        //converting Sql Date to Util Date to
        java.sql.Date sqlDate2 = new java.sql.Date(Calendar.getInstance().getTime().getTime());
        System.out.println("Converion of sql Date into util Date: "+geUtilFromSqlDate(sqlDate2));
       
    }
   
   
    /**
     * @param date
     * @return
     */
    public static java.sql.Date getSqlFromUtilDate(java.util.Date date) {
        java.sql.Date sqlDate = new java.sql.Date(date.getTime());
        return  sqlDate;
    }
   
    /**
     * @param date
     * @return
     */
    public static java.util.Date geUtilFromSqlDate(java.sql.Date date) {
        Date utilDate = new Date(date.getTime());
        return utilDate;
    }


}


  LocalDate date = LocalDate.now();
  DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MM dd");
  String text = date.format(formatter);
  LocalDate parsedDate = LocalDate.parse(text, formatter);
 
All letters 'A' to 'Z' and 'a' to 'z' are reserved as pattern letters. The following pattern letters are defined:
  Symbol  Meaning                     Presentation      Examples
  ------  -------                     ------------      -------
   G       era                         text              AD; Anno Domini; A
   u       year                        year              2004; 04
   y       year-of-era                 year              2004; 04
   D       day-of-year                 number            189
   M/L     month-of-year               number/text       7; 07; Jul; July; J
   d       day-of-month                number            10

   Q/q     quarter-of-year             number/text       3; 03; Q3; 3rd quarter
   Y       week-based-year             year              1996; 96
   w       week-of-week-based-year     number            27
   W       week-of-month               number            4
   E       day-of-week                 text              Tue; Tuesday; T
   e/c     localized day-of-week       number/text       2; 02; Tue; Tuesday; T
   F       week-of-month               number            3

   a       am-pm-of-day                text              PM
   h       clock-hour-of-am-pm (1-12)  number            12
   K       hour-of-am-pm (0-11)        number            0
   k       clock-hour-of-am-pm (1-24)  number            0

   H       hour-of-day (0-23)          number            0
   m       minute-of-hour              number            30
   s       second-of-minute            number            55
   S       fraction-of-second          fraction          978
   A       milli-of-day                number            1234
   n       nano-of-second              number            987654321
   N       nano-of-day                 number            1234000000

   V       time-zone ID                zone-id           America/Los_Angeles; Z; -08:30
   z       time-zone name              zone-name         Pacific Standard Time; PST
   O       localized zone-offset       offset-O          GMT+8; GMT+08:00; UTC-08:00;
   X       zone-offset 'Z' for zero    offset-X          Z; -08; -0830; -08:30; -083015; -08:30:15;
   x       zone-offset                 offset-x          +0000; -08; -0830; -08:30; -083015; -08:30:15;
   Z       zone-offset                 offset-Z          +0000; -0800; -08:00;