Thursday, 18 December 2014

Regular Expression in Java

         A Regular Expression defines a search pattern for strings.  The search pattern can be anything from a simple character, a fixed string or a complex expression containing special characters describing the pattern. The pattern defined by the Regular Expression may match one or several times or not at all for a given string.
         Regular expressions can be used to search, edit and manipulate text. A Regular Expression is also known as a regex or regexp.

         The java.util.regex package was added to Java SE 1.4. If you are running an older version of java than that you should really consider upgrading.

         Java Regular Expression classes are present in java.util.regex package that contains three classes: Pattern, Matcher and PatternSyntaxException.


1) Pattern object is the compiled version of the regular expression. It doesn’t have any public constructor and we use it’s public static method compile to create the pattern object by passing regular expression argument.

2. Matcher is the regex engine object that matches the input String pattern with the pattern object created. This class doesn’t have any public construtor and we get a Matcher object using pattern object matcher method that takes the input String as argument. We then use matches method that returns boolean result based on input String matches the regex pattern or not.

3) PatternSyntaxException is thrown if the regular expression syntax is not correct.


Java Regular Expression Metacharacters:-

          We have some metacharacters also in regular expression, it’s like shortcodes for common matching patterns.

^  indicates the beginning of line.
$  indicates the end of line.
 Regular Expression is in between ^ and $.

Following is the list of metacharacters which can be used in Regular Expressions.

      \d   -   Any digit, short for [0-9].
      \D  -   A non-digit, short for [^0-9].
      \s   -   A whitespace character.
      \S  -   A non-whitespace character.
      \w -   A word character, short for [a-zA-Z_0-9].
      \W -   A non-word character [^\w].
      \b  -   Matches a word boundary where a word character is [a-zA-Z0-9_].
      [..] -   Matches any single character in brackets.
   [^..] -   Matches any single character not in brackets.
      \t   -   Matches a tab (U+0009).
      \v  -   Matches a vertical tab (U+000B).
      +  -   Matches the preceding character 1 or more times. Equivalent to {1,}.
      *   -   Matches the preceding character 0 or more times. Equivalent to {0,}.
      ?   -   Matches the preceding character 0 or 1 time. Equivalent to {0,1}.
      .    -   (The decimal point) matches any single character except the newline character.

Examples:-
Valid Regular Expressions are ,
                                       ^\\d+$   -   Numerics,
                                       ^\\w$     -   AlphaNumerics,
                    ^[a-z0-9_-]{3,16}$      -   lowercase text with  numerics,underscore
                                                          or hyphen and length should be between  3
                                                           and 16.
                                     ^\\d{5}$/   -   5 digit Numerics,
^(\\d{1,2})-(\\d{1,2})-(\\d{4})$/  -   Date format dd-MM-yyyy .


Regular Expression Example:

           Regular expressions make it possible to find all instances of text that match a certain pattern, and return a Boolean value if the pattern is found/not found. (This can be used to validate input such as phone numbers, social security numbers, email addresses, web form input data, scrub data, decimals,Numerics,AlphaNumerics,Email and much more. Eg. If the pattern is found in a String, and the pattern matches a Numerics, then the string is an Numerics).

     import java.util.ArrayList;  
     import java.util.List; 
     public class ValidateDemo {  
            public static void main(String[] args)  {
                    List<String> input = new ArrayList<String>(); 
                    input.add("123");
                    input.add("98HT12");
                    input.add("345") ;
                    for (String numeric : input) { 
                             if (numeric.matches("^\\d+$")) { 
                                      System.out.println("Numerics : " + numeric);  
                             } 
                   } 
            }                
    }

output:
      Numerics : 123
      Numerics : 345
      
Syntax Error Validation in Java Using Pattern:

        public class RegularExpValidation {
                public static void main(String[] args){
                        String valid = RegExpValidation("^\\w{1,$");
                        if(valid != null ){
                               System.out.println(valid);
                        } 
               }

               public static String RegExpValidation(String regPattern){
                       String errorMessage = null;
                       try {
                               Pattern.compile(regPattern);
                       }
                       catch (PatternSyntaxException exception) {
                              errorMessage = exception.getDescription();
                       }
                       return errorMessage;
              }
       }
Output:
     Illegal repetition

Backslashes in Java with Regular Expressions:

           In literal Java strings the backslash is an escape character. The literal string "\\" is a single backslash. In regular  expressions, the backslash is also an escape character. The regular expression \\ matches a single backslash. This regular expression as a Java string, becomes "\\\\". That's right: 4 backslashes to match a single one.

The regex \w matches a word character. As a Java string, this is written as "\\w".

Saturday, 8 November 2014

Postgresql Trigger Example(Appending Dynamic Column Name):-

Postgresql Trigger Example(Appending Dynamic Column Name):-


            In this example there are two tables REGISTRATION_PREFERENCES & PATIENT_HEADER_PREFERENCES.
            In registration_preferences there are 28 columns. out of this 28 , 19 column names are custom_field1_label,custom_field2_label,....,custom_field19_label other 9 columns are also samething. It start with custom_list1_name,custom_list2_name ,.....,custom_list9_name.
           In patient_header_preferences there is only one column i.e field_desc. This column value can contains all column value of registration_preferences. Mean field_desc column having 28 rows.

Question:-    When you update the registration_preferences table then we should update the field_desc column of the patient_header_preferences table.

           In registration_preferences out 0f 28, 19 column names are same except 1 to 19. appending 1 to 19 in function using while loop. other 9 columns are also samething. It start with custom_list1_name,custom_list2_name ,.....,custom_list9_name. Here also appended 1 to 9 in function using another while loop.

   First create function modify_patient_header_pref that you can call it in trigger.

DROP FUNCTION IF EXISTS modify_patient_header_pref() CASCADE;
CREATE FUNCTION modify_patient_header_pref() RETURNS TRIGGER AS $$
DECLARE
    i integer;
    pcolName character varying;
    regFieldName character varying;
    regColName character varying;
    defaultValue character varying;
BEGIN
   i:=1;
   while(i<20)
    loop
         regColName := 'custom_field' || i::text || '_label';
         pcolName := 'custom_field'|| i::text;
         regFieldName := '(' || quote_literal(NEW) || '::' || TG_RELID::regclass || ').' || regColName;
         defaultValue := 'Custom Field ' || i::text;

          EXECUTE $SomeTag$UPDATE patient_header_preferences SET field_desc=CASE WHEN ($SomeTag$ || regFieldName || $SomeTag$ !='') THEN $SomeTag$ || regFieldName || $SomeTag$ ELSE '$SomeTag$|| defaultValue || $SomeTag$' END WHERE field_name = '$SomeTag$ || pcolName || $SomeTag$'$SomeTag$;
         i:=i+1;
   END loop;

   i := 1;
   while(i<10)
     loop
        regColName := 'custom_list' || i::text || '_name';
        pcolName := 'custom_list' || i::text ||'_value';
        regFieldName := '(' || quote_literal(NEW) || '::' || TG_RELID::regclass || ').' || regColName;
        defaultValue := 'Custom List ' || i::text;

          EXECUTE $SomeTag$UPDATE patient_header_preferences SET field_desc=CASE WHEN ($SomeTag$ || regFieldName || $SomeTag$ !='') THEN $SomeTag$ || regFieldName || $SomeTag$ ELSE '$SomeTag$|| defaultValue || $SomeTag$' END WHERE field_name = '$SomeTag$ || pcolName || $SomeTag$'$SomeTag$;
        i:=i+1;
     END loop;

RETURN NEW;
END;
$$ language plpgsql;

DROP TRIGGER IF EXISTS update_patient_header_preferences ON registration_preferences;
CREATE TRIGGER update_patient_header_preferences after UPDATE ON registration_preferences FOR each row EXECUTE PROCEDURE modify_patient_header_pref();

Sunday, 17 August 2014

Java Date and Calendar Examples

 Date Examples and Conversions:--


             In this post shows you how to work with java.util.Date() and java.util.Calendar examples and also to conversions.
            Date is sufficient if you need only a current timestamp in your application, and you do not need to operate on dates, e.g., one-week later. You can further use SimpleDateFormat to control the date/time display format.

If you want to display the current system date using the Date() class is as follows,

                 java.util.Date date = new java.util.Date();

                 System.out.println(date);

In this code you will get output:- Sun Aug 10 00:59:22 IST 2014.
Here you will get Week,Month,Day,Time,Region and Year.

 Some common date and time patterns used in the java.text.SimpleDateFormat are

       d      -       indicates day 1 to 31,
      dd     -       indicates day in two digits including zero e.g 01 to 31.
       E     -       Day name in week e.g Monday,Tuesday and so on.
       M    -       indicates Month e.g 1 to 12,MM indicates month in two digits like 01 to 12
                               MMM  -   indicates month in words e.g Jan,Feb,Mar and so on
                               MMMM - indicates month in full words e.g Janaury,February and so..
       y        -     indicates Year e.g 2014
       a        -     am/pm Marker e.g AM/PM.
       H       -     hour in day e.g 0-23.
       h        -     hour in am/pm e.g 1-12.
       m       -     minute in hour 0-60.
       s         -    second in minute 0-60.

If you want to display only specific Date format then use SimpleDateFormat,

             SimpleDateFormat  sdf = new SimpleDateFormat("dd/MM/yyyy");

             String date = sdf.format(new java.util.Date());
             System.out.println(date);

The output- 05/10/2014.

    Date with time example,

            SimpleDateFormat  sdf = new SimpleDateFormat("dd/MM/yyyy  hh:mm:ss");
            String date = sdf.format(new java.util.Date());
            System.out.println(date);

The output- 05/10/2014 01:10:29

            The above example is to converting the Date into String. Next see how to convert the String into Date Format using  SimpleDateFormat,

            String date = "20/07/2014";
            SimpleDateFormat  sdf = new SimpleDateFormat("dd/MM/yyyy");
            System.out.println(sdf.parse(date));           //parse method can convert string to date

The output-Sun Jul 20 00:00:00 IST 2014.

    The above sdf.parse(date) returns the Date object with specified date format.

Summary of Date class:
  •  Date  class is sufficient if you just need a simple timestamp.                                                                  
  • You could use SimpleDateFormat to control the date/time display format.
        Use java.text.DateFormat to format a Date (form Date to text) and parse a date string (from text to Date). SimpleDateFormat is a subclass of DateFormat.

      Date is legacy class, which does not support internationalization. Calendar and DateFormat support locale (you need to consider locale only if you program is to be run in many countries concurrently).

         Use java.util.Calendar class if you need to extract year, month, day, hour, minute, and second, or manipulating these field (e.g., 7 days later, 3 weeks earlier).  Next we can discuss Calendar examples.


DateFormat Examples:

 

          java.text.DateFormat is an abstract class for formats (from date to text) and parses (from text to date) date/time in a text-language-independent manner. SimpleDateFormat is an implementation subclass. Date formatter operates on Date object.

      To use the date formatter, first create a DateFormat object for the desired date/time format, and then use the format() method to produce a date/time string. 

To use the DateFormat, use one of these static factory method to create an instance:  

    DateFormat.getDateTimeInstance(): use the default style and locale to format date and time.                 DateFormat.getDateTimeInstance(int dateStyle, int timeStyle, Locale aLocale): style  include 
                                            DateFormat.FULL, LONG, MEDIUM, and SHORT.
    DateFormat.getInstance():     uses SHORT style for date and time.
    DateFormat.getDateInstance(), DateFormat.getDateInstance(int style, Locale aLocale):  date only.
    DateFormat.getTimeInstance(), DateFormat.getTimeInstance(int style, Locale aLocale):   time only.

Example:
                 import java.util.Date;
                 import java.text.DateFormat;
                 import java.text.SimpleDateFormat;
                 import java.util.Locale;
                
                 public class DateFormatExample{
                         public static void main(String[] args) {

                                  Date date = new Date();
                                                   // Use DateFormat
                                  DateFormat formatter = DateFormat.getInstance(); // Date and time
                                  String dateStr = formatter.format(date);
                                  System.out.println(dateStr);
                                  formatter = DateFormat.getTimeInstance();        // time only
                                  System.out.println(formatter.format(date));
                                                    // Use locale
                                  formatter = DateFormat.getDateTimeInstance(DateFormat.FULL,                                                                         DateFormat.FULL, Locale.ENGLISH);
                                  System.out.println(formatter.format(date));
 
                         }
                 }

    Output--
                                         8/17/14 10:58 PM
                                         10:59:19 PM
                                         Sunday, August 17, 2014 11:01:27 PM IST

Calendar Examples:--

 The Calendar class provides support for:

    1) maintaining a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR ,                                                                             MINUTE, SECOND, MILLISECOND; and

    2)  manipulating these calendar fields, such as getting the date of the previous week,next week,next 
         month and so on.

Calendar provides internationalization support.

            Calendar is a abstract class, and you cannot use the constructor to create an instance. Instead, you use the static method Calendar.getInstance() to instantiate an implementation sub-class.

     Calendar.getInstance(): return a Calendar instance based on the current time in the default time zone with the default locale.
    Calendar.getInstance(TimeZone zone)
    Calendar.getInstance(Locale aLocale)
    Calendar.getInstance(TimeZone zone, Locale aLocale)

Some of the usefull calendar fields are as follows,

        Calendar.YEAR                      -  Identifies the year.
        Calendar.MONTH                   - Identifies the month.
        Calendar.DAY_OF_MONTH  - Identifies the day.
        Calendar.HOUR                       - Identifies the hour.
        Calendar.MINUTE                   - Identifies the minute.
        Calendar.SECOND                  - Identify the second.

Example:-
                    import java.text.SimpleDateFormat;
                    import java.util.Calendar;

                    public class CalendarExample {
                           public static void main(String[] args) {
                                     // Get an instance of a Calendar, using the current time.
                                  SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd                                                                                                               HH:mm:ss");
                                  Calendar calendar = Calendar.getInstance();
                                  System.out.println(dateFormat.format(calendar.getTime()));
                                       // Printing some information...
                                  System.out.println("ERA: " + calendar.get(Calendar.ERA));
                                  System.out.println("YEAR: " + calendar.get(Calendar.YEAR));
                                  System.out.println("MONTH: " + calendar.get(Calendar.MONTH));                
                                  System.out.println("WEEK_OF_YEAR: "+
                                                                  calendar.get(Calendar.WEEK_OF_YEAR));
                                  System.out.println("WEEK_OF_MONTH: " +                   
                                                                  calendar.get(Calendar.WEEK_OF_MONTH));
                                  System.out.println("DATE: " + calendar.get(Calendar.DATE));
                                  System.out.println("DAY_OF_MONTH: " 
                                                                        +calendar.get(Calendar.DAY_OF_MONTH));
                                  System.out.println("DAY_OF_YEAR: " + 
                                                                 calendar.get(Calendar.DAY_OF_YEAR));
                                  System.out.println("DAY_OF_WEEK: " +    
                                                                 calendar.get(Calendar.DAY_OF_WEEK));
                                  System.out.println("DAY_OF_WEEK_IN_MONTH: " +  
                                                                 calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH));
                                  System.out.println("AM_PM: " + calendar.get(Calendar.AM_PM));
                                  System.out.println("HOUR: " + calendar.get(Calendar.HOUR));
                                  System.out.println("HOUR_OF_DAY: " + 
                                                                 calendar.get(Calendar.HOUR_OF_DAY));
                                  System.out.println("MINUTE: " + calendar.get(Calendar.MINUTE));
                                  System.out.println("SECOND: " + calendar.get(Calendar.SECOND));
                                  System.out.println("MILLISECOND: " +   
                                                                         calendar.get(Calendar.MILLISECOND));
                        }
              }

A sample execution is shown below:

2014-02-06 17:33:40
ERA: 1
YEAR: 2014
MONTH: 1
WEEK_OF_YEAR: 6
WEEK_OF_MONTH: 2
DATE: 6
DAY_OF_MONTH: 6
DAY_OF_YEAR: 37
DAY_OF_WEEK: 5
DAY_OF_WEEK_IN_MONTH: 1
AM_PM: 1
HOUR: 5
HOUR_OF_DAY: 17
MINUTE: 33
SECOND: 40
MILLISECOND: 692

Manipulating the Calendar dates:

         If you want to add or substract the days from the existing calendar then,

                       Calendar cal = Calendar.getInstance();
                       System.out.println("The current date is: "+cal.getTime());
                       cal.add(Calendar.DATE, 2);                                  //added two days
                       System.out.println("After adding 2 days: "+cal.getTime());
                       cal.add(Calendar.Date,-8);
                       System.out.println("After substracting 8 days: "+cal.getTime());

output--
                      The current date is: Wed Aug 27 15:00:56 IST 2014
                      After adding 2 days: Fri Aug 29 15:00:56 IST 2014
                      After substracting 8 days: Thu Aug 21 15:28:50 IST 2014

        If you want to add or substract the month from the existing calendar then,

                      Calendar cal = Calendar.getInstance();
                      System.out.println("The current date is: "+cal.getTime());
                      cal.add(Calendar.MONTH, 4);                //After 4 months
                      System.out.println("After 4 months : "+cal.getTime());
                      cal.add(Calendar.MONTH, -6)                //6 months ago
                      System.out.println("6 months ago : "+cal.getTime());

output-
                     The current date is: Wed Aug 27 15:00:56 IST 2014
                    After 4 months : Sat Dec 27 15:37:02 IST 2014
                    6 months ago :Fri Jun 27 15:37:02 IST 2014

Samething follow for other calendar fields like year,day,day of week and so on.

Converting Date Object to Calendar Object :-

                 SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
                 String dateStr = "10/10/2014";
                 Date date = sf.parse(dateStr);
                 Calendar cal = Calendar.getInstance();
                 cal.setTime(date);
                 System.out.println(cal.getTime());

Setting the Calendar fields:-

                  Calendar cal = Calendar.getInstance();
                  System.out.println("The current date is: "cal.getTime());
                  cal.set(Calendar.MINUTE, 25);
                  cal.set(Calendar.DAY_OF_MONTH, 10);
                  cal.set(Calendar.YEAR, 2013);
                  System.out.println("After setting: "cal.getTime());
output-
                 The current date is: Wed Aug 27 16:04:21 IST 2014
                 After setting: Sat Aug 10 16:25:21 IST 2013

 

java.util.GregorianCalendar:-


                   The calendar that we use today, called Gregorian calendar, came into effect in October 15, 1582 in some countries and later in other countries. It replaces the Julian calendar. 10 days were removed from the calendar, i.e., October 4, 1582 (Julian) was followed by October 15, 1582 (Gregorian). The only difference between the Gregorian and the Julian calendar is the "leap-year rule". In Julian calendar, every four years is a leap year. In Gregorian calendar, a leap year is a year that is divisible by 4 but not divisible by 100, or it is divisible by 400, i.e., the Gregorian calendar omits century years which are not divisible by 400 (removing 3 leap years (or 3 days) for every 400 years). Furthermore, Julian calendar considers the first day of the year as march 25th, instead of January 1st.

                    java.util.Calendar is an abstract class. Calendar.getInstance() returns an implementation class java.util.GregorianCalendar (except locales of "th" and "jp"). In Java, this GregorianCalendar handles both the Gregorian calendar as well as the Julian calendar, including the cut over.               

Sunday, 20 July 2014

What are the Implicit Objects in JSP?

             JSP Implicit Objects are the Java objects that the JSP Container makes available to developers in each page and developer can call them directly without being explicitly declared. JSP Implicit Objects are also called pre-defined variables.

    JSP supports nine Implicit Objects which are listed below:

 1) request :
            This is the HttpServletRequest object associated with the request.

 2) response :
           This is the HttpServletResponse object associated with the response to the client.

 3) out :
         This is the PrintWriter object used to write any data to buffer.

 4) session :
         This is the HttpSession object associated with the request.

  5) application :
         This is the ServletContext object associated with application context.

  6) config :
         This is the ServletConfig object associated with the page.

  7) pageContext :
        This encapsulates use of server-specific features like higher performance JspWriters.

  8) page :
       This is simply a synonym for this, and is used to call the methods defined by the
      translated servlet  class.

  9) Exception :
         The Exception object allows the exception data to be accessed by designated JSP.

Sunday, 13 July 2014

Difference between HashMap and Hashtable in collection in Java



There are several differences between HashMap and Hashtable in Java:
  1. The HashMap class is roughly equivalent to Hashtable, except that it is non synchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn't allow nulls).   
  2.  HashMap does not guarantee that the order of the map will remain constant over time.
  3. HashMap is non synchronized whereas Hashtable is synchronized.
  4. Iterator in the HashMap is fail-safe while the enumerator for the Hashtable is not and throw ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except Iterator's own remove() method. But this is not a guaranteed behavior and will be done by JVM on best effort.
Note on Some Important Terms
  1. Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.
  2. Fail-safe is relevant from the context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object "structurally", a concurrent modification exception will be thrown. It is possible for other threads though to invoke "set" method since it doesn't modify the collection "structurally". However, if prior to calling "set", the collection has been modified structurally, "IllegalArgumentException" will be thrown.
  3. Structurally modification means deleting or inserting element which could effectively change the structure of map.
HashMap can be synchronized by
Map m = Collections.synchronizeMap(hashMap);

            Map provides Collection views instead of direct support for iteration via Enumeration objects. Collection views greatly enhance the expressiveness of the interface, as discussed later in this section. Map allows you to iterate over keys, values, or key-value pairs; Hashtable does not provide the third option. Map provides a safe way to remove entries in the midst of iteration; Hashtable did not. Finally, Map fixes a minor deficiency in the Hashtable interface. Hashtable has a method called contains, which returns true if the Hashtable contains a given value. Given its name, you'd expect this method to return true if the Hashtable contained a given key, because the key is the primary access mechanism for a Hashtable. The Map interface eliminates this source of confusion by renaming the method containsValue. Also, this improves the interface's consistency — containsValue parallels containsKey.


Related Post:
 1) Collection Interview Qusetions and Answers
 2) How HashMap works internally in java?

Saturday, 28 June 2014

What is dependency Injection in Spring? give me types and advantages with examples

             Spring uses inversion of control to satisfy dependencies between objects. Traditional approach before Spring framework was to hard code the dependencies and this creates tightly coupled code and there was no easy way to change that. People used to minimize this tight coupling, by resorting to ” programming to an interface and not to an implementation”, but even with that approach, the actual creation of the dependent object was the responsibility of the calling piece of code. Of course there were custom frameworks being developed by various individuals to create some form of  inversion of control to achieve dependency injection ( DI). 

            The basic concept of the Inversion of Control pattern (also known as Dependency Injection (DI) ) is that you do not create your objects but describe how they should be created. You don't directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up. In a typical IOC scenario, the container creates all the objects, wires them together by setting the necessary properties, and determines when methods will be invoked.  
    
        There are two types of DI,
1) Setter Injection
2) Constructor Injection
                                        
                                         Setter Injection:
  Spring framework will inject the dependency via a setter method.
XML configuration for setter Dependency Injection is below.

                               <bean id="classBean" class="com.adnjava.ClassBean">
                                       <!-- setter injection using the nested <ref/> element -->
                                       <property name="studentBean"><ref bean="studentBean"/></property>
                                </bean>
                                <bean id="studentBean" class="com.adnjava.StudentBean"/> 

         The ClassBean java POJO class is as below,
                                    
                               package com.adnjava;
                               public class ClassBean {
                                      private StudentBean studentBean;
                                      public void setStudentBean(StudentBean studentBean){
                                             this.studentBean=studentBean;
                                     }
                                     public void getStudentBean(){
                                            return studentBean;
                                     }
                            }
             
                                 Constructor Injection:

         Here Spring uses the  Constructor and the arguments passed to it to determine the dependency. Rest all is same as setter injection.
     
      XML configuration for
Constructor Dependency Injection is below.
                               <bean id="classBean" class="com.adnjava.ClassBean">
                                        <constructor-arg><ref bean="studentBean"/></constructor-arg>
                                        <!--OR you can use <constructor-arg ref="yetAnotherBean"/>-->
                                </bean>
                                <bean id="studentBean" class="com.adnjava.StudentBean"/> 

         The ClassBean java POJO class is as below,
                                    
                               package com.adnjava;
                               public class ClassBean {
                                       private StudentBean studentBean;
                                       public ClassBean(StudentBean studentBean){
                                               this.studentBean=studentBean;
                                       }
                                       public void getStudentBean(){
                                              return studentBean;
                                      }
                            }

    Interface Injection:

                      This is not implemented in Spring currently, but by Avalon. It’s a different type of DI that involves mapping items to inject to specific interfaces.

                   Advantages Of Dependency Injection:
  • Loosely couple code
  • Separation of responsibility
  • Configuration and code is separate.

Friday, 27 June 2014

Explain bean life cycle in Spring


         Spring framework is based on IOC(Inversion Of Control) so we call it as IOC container also So Spring beans reside inside the IOC container. Spring beans are nothing but Plain Old Java Object (POJO).
 
Following steps explain their life cycle inside the container.
    
1 Container will look the bean definition inside configuration file (e.g. bean.xml).
     
2)  Using Reflection API container will create the object and if any property is defined inside the bean definition then it will also be set.
   
3 If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the bean’s ID.

4 If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself.


5 If there are any BeanPostProcessors associated with the bean, their post- ProcessBeforeInitialization() methods will be called before the properties for the Bean are set.

    
6 If an init() method is specified for the bean, it will be called.

7 If the Bean class implements the DisposableBean interface, then the method destroy() will be called when the Application no longer needs the bean reference.

     
8 If the Bean definition in the Configuration file contains a 'destroy-method' attribute, then the corresponding method definition in the Bean class will be called.

Sunday, 22 June 2014

Why Map interface doesn't extend Collection interface?

        Although Map interface and it’s implementations are part of Collections Framework, Map are not collections and collections are not Map. Hence it doesn’t make sense for Map to extend Collection or vice versa.

          If Map extends Collection interface, then where are the elements? Map contains key-value pairs and it provides methods to retrieve list of Keys or values as Collection but it doesn’t fit into the “group of elements” paradigm.


Saturday, 21 June 2014

Singleton Design Pattern in java with example

       I have attended some interviews recently. Some interviewer asked "do you know any design pattern"? I answered Singleton Design Pattern because even java beginners should know this pattern.
       Here we will learn about Singleton design pattern principles, different ways to implement Singleton and some of the best practices for it’s usage.

     Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine. The singleton class must provide a global access point to get the instance of the class. 

          Singleton pattern is used for logging, drivers objects, caching and thread pool. Singleton design pattern is also used in other design patterns like Abstract Factory, Builder, Prototype, Facade etc.

   To implement the Singleton Design Pattern,you do the following the things,
  1) private constructor - no other class can instantiate a new object.
  2) private reference - no external modification.
  3) public static method is the only place that can get an object.

 Next,we will learn the different approaches of Singleton pattern implementation and design.

Eager initialization

           In eager initialization, the instance of Singleton Class is created at the time of class loading, this is the easiest method to create a singleton class but it has a drawback that instance is created even though client application might not be using it.

Here is the implementation of static initialization singleton class.
   
            public class EagerInitializer{
                     private static final EagerInitializer instance = new EagerInitializer();
                             //private constructor to avoid client applications to use constructor.
                     private  EagerInitializer(){
                     }
                     public static EagerInitializer getInstance(){
                                 return instance;
                    }
           }

           If your singleton class is not using a lot of resources, this is the approach to use. But in most of the scenarios, Singleton classes are created for resources such as File System, Database connections etc and we should avoid the instantiation until unless client calls the getInstance method. Also this method doesn’t provide any options for exception handling.

Static block initialization

           Static block initialization implementation is similar to eager initialization, except that instance of class is created in the static block that provides option for exception handling

.              public class StaticInitializer{
                        private static StaticInitializer instance ;
                             //private constructor to avoid client applications to use constructor.
                        private  StaticInitializer(){
                        }
                        static {
                                try{
                                       instance=new StaticInitializer();
                                }
                                catch(Exception e){
                                        throw new RuntimeException("Exception in static block");
                                }
                        }
                        public static StaticInitializer getInstance(){
                                return instance;
                       }
             }

         Both eager initialization and static block initialization creates the instance even before it’s being used and that is not the best practice to use. So in further sections, we will learn how to create Singleton class that supports lazy initialization.

Lazy Initialization

           Lazy initialization method to implement Singleton pattern creates the instance in the global access method. Here is the sample code for creating Singleton class with this approach.

              public class LazyInitializer{
                      private static LazyInitializer instance;
                            //private constructor to avoid client applications to use constructor.
                      private  LazyInitializer(){
                      }
                      public static LazyInitializer getInstance(){
                              if(instance == null){
                                      instance = new LazyInitializer();
                              }
                              return instance;
                     }
           }


       The above implementation works fine incase of single threaded environment but when it comes to multithreaded systems, it can cause issues if multiple threads are inside the if loop at the same time. It will destroy the singleton pattern and both threads will get the different instances of singleton class. In next section, we will see different ways to create a thread-safe singleton class.

Thread Safe Singleton

       The easier way to create a thread-safe singleton class is to make the global access method synchronized, so that only one thread can execute this method at a time. General implementation of this approach is like the below class.

           public class ThreadSafe{
                    private static ThreadSafe instance ;
                        //private constructor to avoid client applications to use constructor.
                    private  ThreadSafe(){
                    }
                    public static synchronized ThreadSafe getInstance(){
                            if(instance == null){
                                     instance = new ThreadSafe();
                            }
                            return instance;
                   }
         }

        Above implementation works fine and provides thread-safety but it reduces the performance because of cost associated with the synchronized method, although we need it only for the first few threads who might create the separate instances (Read: Java Synchronization). To avoid this extra overhead every time, double checked locking principle is used. In this approach, the synchronized block is used inside the if condition with an additional check to ensure that only one instance of singleton class is created.

           Below code snippet provides the double checked locking implementation

                 public static ThreadSafe getInstance(){
                          if(instance == null){
                                    synchonized(ThreadSafe.class){
                                             if(instance == null ){
                                                      instance = new ThreadSafe();
                                             }
                                     }
                           }
                           return instance;
                 }


                      Real time Examples for Singleton Design Pattern:---

JDBC Example using Singleton Design pattern:--

         We write a class (ConnectionFactory) which implements singleton pattern defining database connection configuration statements and methods to make connection to the database. Reason for making this class as singleton is, we can create one object of this class and can create many Connection objects (one factory, many objects).
package com.adnjavainterview;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionFactory {
           //static reference to itself
         private static ConnectionFactory instance = new ConnectionFactory();
         public static final String URL = "jdbc:mysql://localhost/jdbcdb";
         public static final String USER = "YOUR_DATABASE_USERNAME";
         public static final String PASSWORD = " YOUR_DATABASE_PASSWORD";
         public static final String DRIVER_CLASS = "com.mysql.jdbc.Driver";
              //private constructor
         private ConnectionFactory() {
                 try {
                        Class.forName(DRIVER_CLASS);
                  }
                  catch (ClassNotFoundException e) {
                        e.printStackTrace();
                  }
         }
    
         private Connection createConnection() {
                   Connection connection = null;
                   try {
                          connection = DriverManager.getConnection(URL, USER, PASSWORD);
                   }
                   catch (SQLException e) {
                           System.out.println("ERROR: Unable to Connect to Database.");
                   }
                   return connection;
         } 
    
         public static Connection getConnection() {
                 return instance.createConnection();
         }
 }
Transfer Object (TO) design pattern:

Transfer Object pattern encapsulates business data. To implement this pattern, we write a class with properties defining the table attributes. For example, to implement Employee TO class, we write the following code;

package com.adnjavainterview;

import java.util.Date;

public class Employee {
         private int empId;
         private String empName;
         private Date dob;
         private double salary;
         private int deptId;
          //getters and setters omitted for brevity
}
Data Access Object design pattern:

  DAO classes implements Data Access Object (DAO) pattern which encapsulates access to the data source.
       This class defines methods for each query, where we first create connection object using ConnectionFactory (by calling ConnectionFactory.getConnection()). Using this connection object we create statement and execute queries.
   
package com.adnjavainterview;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.adnjavainterview.ConnectionFactory;
import com.adnjavainterview.DbUtil;
import com.adnjavainterview.Employee;

public class EmployeeDAO {
        private Connection connection;
        private Statement statement;

        public EmployeeDAO() { }
    
        public Employee getEmployee(int employeeId) throws SQLException {
                 String query = "SELECT * FROM employee WHERE emp_id=" + employeeId;
                 ResultSet rs = null;
                 Employee employee = null;
                 try {
                       connection = ConnectionFactory.getConnection();
                       statement = connection.createStatement();
                       rs = statement.executeQuery(query);
                       . . . .
                       . . . .
                 } finally {
                         DbUtil.close(rs);
                         DbUtil.close(statement);
                         DbUtil.close(connection);
                  }
                  return employee;
       }
Closing database connection:
   Safe method to close database ResultSet, Statement and Connection is to write a finally block and release all the resources. We check for non-null reference before calling the close() instance method to avoid NullPointerException.
   
     finally {
            if (connection != null) {
                  try {
                        connection.close();
                  } catch (SQLException e) {
                        /* Ignore */
                  }
            }
            if (statement != null) {
                    . . .
            }
            if (resultSet != null) {
                   . . .
            }
      }

Instead of repeating these statements in all methods, we write a helper class (DbUtil.java) with methods to close these resources.
   
package com.adnjavainterview;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DbUtil {

         public static void close(Connection connection) {
                 if (connection != null) {
                       try {
                             connection.close();
                       } catch (SQLException e) {
                          /*log or print or ignore*/
                      }
                }
         }

        public static void close(Statement statement) {
                 if (statement != null) {
                       try {
                              statement.close();
                       } catch (SQLException e) {
                           /*log or print or ignore*/
                      }
               }
       }

        public static void close(ResultSet resultSet) {
                if (resultSet != null) {
                       try {
                              resultSet.close();
                       } catch (SQLException e) {
                             /*log or print or ignore*/
                       }
               }
        }
 }

These methods can be called from finally block.
   
          try {
                   connection = ConnectionFactory.getConnection();
                   statement = connection.createStatement();
                   rs = statement.executeQuery(query);
          } finally {
                   DbUtil.close(rs);
                   DbUtil.close(statement);
                  DbUtil.close(connection);
          }


Related Post:--