Thursday, 18 December 2014

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.

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.

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;

publicclassValidateDemo{

publicstaticvoid 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 : 123Numerics : 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):-

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.

Sunday, 17 August 2014

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 2014a - 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 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

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

Calendar Examples:--

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)

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

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

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).

HashMap does not guarantee that the order of the map will remain constant over time.

HashMap is non synchronized whereas Hashtable is synchronized.

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

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.

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.

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.

Saturday, 28 June 2014

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 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 IOCscenario, 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,

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.

<beanid="classBean"class="com.adnjava.ClassBean"><constructor-arg><refbean="studentBean"/></constructor-arg><!--OR you can use <constructor-arg ref="yetAnotherBean"/>--></bean><beanid="studentBean"class="com.adnjava.StudentBean"/>

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 BeanNameAwareinterface, the factory calls setBeanName() passing the bean’s ID.
4) If the bean implements the BeanFactoryAwareinterface, the factory calls setBeanFactory(), passing an instance of itself.
5) If there are any BeanPostProcessorsassociated 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

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

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.

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

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.

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.

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.