Friday, June 27, 2014

How to install Maven Plugin for Eclipse Indigo

This post will help you to install the Maven Plugin for Eclipse Indigo. Follow the below steps for successful installation.
  1. Open the eclipse and go to Help->Install New Software
  2. Select Indigo - http://download.eclipse.org/releases/indigo in “Work with” Text box and wait to load all the available plugins.
  3. Once loaded, type “m2e” in “type filter text” text box.
  4. Select 'm2e - Maven Integration for Eclipse' in General Purpose Tools
  5. Click Next and “Review the items to be installed.” if you want.
  6. Click Next and select the radio button “ I accept the terms of the license agreement”.
  7. Finally, Click Finish.

Singleton Design Pattern in Java

INTRODUCTION

Singleton design pattern is one of the popular design patterns in java.
The straightforward understanding from the singleton is the single instance. Yes, only one instance of any singleton class can be created throughout the application.

WHEN TO USE

  1. When the business requirement is to create only one instance for the application.
  2. If you want to avoid creating multiple objects for a class.
  3. Need to restrict the creating an object for your class.

HOW TO IMPLEMENT

Java access specifier actually makes the class singleton. How? make the constructor as private so that it can not be extended by other class.
Consider the below example.
public class Singleton {
 // Declare an instance of this class private static
 private static Singleton _singletonInstance;

 /**
  * Make the constructor as private, so that it can't be sub-classed
  */
 private Singleton() {
 }

 /**
  * Has the logic to create a new Instance for Singleton class. static keyword
  * helps to access this method directly. synchronized - helps to avoid
  * multiple instances created by the multiple threads in case.
  *
  * @return
  */
 public static synchronized Singleton getSingletonInstance() {

   if (null == _singletonInstance) {
     _singletonInstance = new Singleton();
   }

   return _singletonInstance;
 }
}


Also, It is marked as static to make method accessible directly using the class name, synchronized makes the method thread-safe so that no other thread can access this method and try to create multiple instances.

Also, I am having simple java class to create multiple instances and test the singleton feature.

public class SampleJava {
 public String getName() {
   return "Sample Java";
 }
}

Now time to test the singleton design pattern. Try to create 2 or more instances for the SampleJava class and check how many instances are actually created.

public class SingletonTest {

 public static void main(String[] args) {

   // Create a instance for the Singleton class
   Singleton s1 = Singleton.getSingletonInstance();

   // Create another instance
   Singleton s2 = Singleton.getSingletonInstance();

   System.out.println("Are s1 and s2 same? : " + (s1 == s2));

   SampleJava sj1 = new SampleJava();
   SampleJava sj2 = new SampleJava();

   System.out.println("Are sj1 and sj2 same? : " + (sj1 == sj2));
 }
}

OUTPUT


Are s1 and s2 same? : true
Are sj1 and sj2 same? : false
Hope this example clarifies the Singleton Design Pattern. Please share your thoughts in the comment box.
Happy Knowledge Sharing!!!

Thursday, June 26, 2014

Factory Method Design Pattern in Java

INTRODUCTION

  • Factory Method Design pattern is categorized under Creational Patterns.
  • It deals with the creation of object based on the input provided by a client.
  • At runtime, the object will be created.
  • A factory class will be responsible for calling appropriate sub-class and creates the required instance. i.e., it contains the logic to create and return the appropriate instance based on the parameter sent to it.
  • Almost all the Java application will have implemented with Factory Design Pattern, but it will be implemented based on the business requirements.

EXAMPLE

  1. One of the best examples of the Factory Pattern is Spring Framework’s org.springframework.beans.factory.BeanFactory class. Spring container only knows which object will be instantiated when the object is creation is requested.

WHEN TO USE?

The factory method design pattern can be used when
  1. Restrict the client to know about which concrete implementation will be called during runtime to complete the task. Hide object creation logic from the client.
  2. Make client loosely coupled with actual implementation.
  3. Need to define the clear separation of multiple types by creating a common interface.
  4. Delegate the object creation work to sub-classes so that tight coupling will be avoided.

USECASE

Consider different states in India, which are divided based on the language. Using the name of a state, get the required details.

PROBLEM

First, create an enum type (StateName.java) for different states.
public enum StateName {
 TAMILNADU, KERALA;
}

Create a class (Tamilnadu.java) which will provide all the details about the state Tamilnadu.
public class Tamilnadu {

 private String language = "tamil";
 private String population = "7 crores";
 private String capital = "Chennai";

 public void getDetails() {
   System.out.println(
       "State Name: TamilNadu \nLanguage: " + language
        + "\nPopulation: " + population + "\nCapital: " + capital);
 }
}

Create another class (Kerala.java) which will provide all the details about the state Kerala.
public class Kerala {

 private String language = "malayalam";
 private String population = "10 crores";
 private String capital = "Trivandram";

 public void getDetails() {
   System.out.println(
       "State Name: Kerala \nLanguage: " + language
       + "\nPopulation: " + population + "\nCapital: " + capital);
 }
}

Now create a client (FactoryPatternClient.java) who will access the different state details by its name.

import jbr.factorypattern.common.StateName;

public class FactoryPatternClient {

 public static void main(String[] args) {

   StateName state = StateName.TAMILNADU;
   switch (state) {
   case TAMILNADU:
     Tamilnadu tamilnadu = new Tamilnadu();
     tamilnadu.getDetails();
     break;

   case KERALA:
     Kerala kerala = new Kerala();
     kerala.getDetails();
     break;

   default:
     break;
   }
 }
}

Can you identify what is the problem with the above implementation?
  1. The Client has the knowledge of which object is getting created for different object creation.
  2. The Client is tightly coupled with State object.
  3. There is no clear separation of different State objects.

SOLUTION

We will try to solve the problem with the above implementation step by step.

Step 1

First, create an interface(State.java) which defines different behaviors of the State Object. Here, State.java can be defined with following methods.
  1. getAllDetails() - all the details about the state
  2. getLanguage() - official language of the state.
  3. getPopulation() - current population of the state.
  4. getCapital() - current capital city of the state.

public interface State {

 String getAllDetails();

 String getLanguage();

 String getPopulation();

 String getCapital();
}

Step 2

  1. Create Tamilnadu.java & Kerala.java which will implement the above State.java interface.
  2. Write the implementation of all the methods.
public class Tamilnadu implements State {
 private String language = "tamil";
 private String population = "7 crores";
 private String capital = "Chennai";

 @Override
 public String getAllDetails() {
   return "Name: TamilNadu \nLanguage: " + language
          + "\nPopulation: " + population + "\nCapital: " + capital;
 }

 @Override
 public String getLanguage() {
   return this.language;
 }

 @Override
 public String getPopulation() {
   return this.population;
 }

 @Override
 public String getCapital() {
   return this.capital;
 }
}


public class Kerala implements State {

 private String language = "malayalam";
 private String population = "10 crores";
 private String capital = "Trivandram";

 public String getAllDetails() {
   return "Name: Kerala \nLanguage: " + language
   + "\nPopulation: " + population + "\nCapital: " + capital;
 }

 @Override
 public String getLanguage() {
   return this.language;
 }

 @Override
 public String getPopulation() {
   return this.population;
 }

 @Override
 public String getCapital() {
   return this.capital;
 }
}

Step 3

Now we will eliminate the tight coupling between the client and objection creation logic by introducing another class called Factory(StateFactory.java). The Factory will have the actual logic to call and create the object based on the input provided by a client.
import jbr.factorypattern.common.StateName;

public class StateFactory {

 public State getState(StateName state) {
   State result = null;
   switch (state) {
   case TAMILNADU:
     result = new Tamilnadu();
     break;

   case KERALA:
     result = new Kerala();
     break;

   default:
     break;
   }
   return result;
 }
}

Step 4

Now our new client (FactoryPatternClient.java) code will be lighter and loosely coupled.
import jbr.factorypattern.common.StateName;

public class FactoryPatternClient {

 public static void main(String[] args) {
   StateFactory stateFactory = new StateFactory();

   State tamilnadu = stateFactory.getState(StateName.TAMILNADU);
   System.out.println(tamilnadu.getAllDetails());

   State kearla = stateFactory.getState(StateName.KERALA);
   System.out.println("\n" + kearla.getAllDetails());
 }
}

OUTPUT


Name: TamilNadu
Language: tamil
Population: 7 crores
Capital: Chennai

Name: Kerala
Language: malayalam
Population: 10 crores
Capital: Trivandram
Hope this example clarifies the Factory Method Design Pattern. Please share your comments and suggestions below.
Happy Knowledge Sharing!!!

Oracle System Queries

INTRODUCTION

This tutorial will help get the oracle database details.

1. Find the Version


select * from v$version;

2. Find the Tables Spaces

select * from dba_tablespaces;

3. Find the Tables

select TABLE_NAME, OWNER from SYS.ALL_TABLES order by OWNER, TABLE_NAME;

4. Find Schemas

select USERNAME from SYS.ALL_USERS order by USERNAME;

5. Find Views

select VIEW_NAME, OWNER from SYS.ALL_VIEWS order by OWNER, VIEW_NAME;

6. Find Packages

select OBJECT_NAME, OWNER from SYS.ALL_OBJECTS where UPPER(OBJECT_TYPE) = 'PACKAGE' order by OWNER, OBJECT_NAME;

7. Find Procedures

select OBJECT_NAME, OWNER from SYS.ALL_OBJECTS where upper(OBJECT_TYPE) = upper('PROCEDURE') order by OWNER, OBJECT_NAME;

8. Find Procedure Columns

select OWNER, OBJECT_NAME, ARGUMENT_NAME, DATA_TYPE, IN_OUT from SYS.ALL_ARGUMENTS order by OWNER, OBJECT_NAME, SEQUENCE;

9. Find Functions

select OBJECT_NAME, OWNER from SYS.ALL_OBJECTS where upper(OBJECT_TYPE) = upper('FUNCTION') order by OWNER, OBJECT_NAME;

10. Find Triggers

select TRIGGER_NAME, OWNER from SYS.ALL_TRIGGERS order by OWNER, TRIGGER_NAME;

11. Find Indexes

select INDEX_NAME, TABLE_NAME, TABLE_OWNER from SYS.ALL_INDEXES order by TABLE_OWNER, TABLE_NAME, INDEX_NAME;

Oracle Tutorial

INTRODUCTION

This tutorial will cover the basics of oracle database operations with sample queries.

I will cover the below topics

  1. DDL (Data Definition Language) Operations
  2. DML (Data Manipulation Language) Operations
  3. DCL (Data Control Language) Operations
  4. DATE Columns Operations
  5. TIMESTAMP Columns Operations
  6. CREATE New User
  7. Find Operations

1. DDL OPERATIONS

1.1 CREATE

1.2 ALTER

1.3 DROP

1.4 TRUNCATE

1.5 RENAME

  1. Rename Table
ALTER TABLE <OldTableName> RENAME TO <NewTableName>;

     in case, if you are running on above statement in Stored Procedure, then
EXECUTE IMMEDIATE 'ALTER TABLE <OldTableName>RENAME TO <NewTableName>';

  1. Rename Index
ALTER INDEX <OldIndexName> RENAME TO <NewIndexName>;

in case, if you are running on above statement in Stored Procedure, then
EXECUTE IMMEDIATE 'ALTER INDEX <OldIndexName> RENAME TO <NewIndexName>';

  1. Rename Constraints
ALTER TABLE <TableName> RENAME CONSTRAINT <OldConstraintName> TO <NewConstraintName>;

in case, if you are running on above statement in Stored Procedure, then
EXECUTE IMMEDIATE 'ALTER TABLE <TableName> RENAME CONSTRAINT <OldConstraintName> TO <NewConstraintName>'

2. DML OPERATIONS

2.1 SELECT

  1. How to select Multiple Rows with Multiple Values?

select case 'TEST' when 'X' then '123' when 'Y' then '456' when 'TEST' then 'success' else 'exit' end from dual select decode('TEST','X','123','Y','456','TEST','Success','exit') from dual;

2.2 INSERT

2.3 UPDATE

  1. Normal Update.

UPDATE <TABLENAME> SET COLUMN=<VALUE> WHERE COLUMN=<SOME VALUE>;

  1. Update a particular text on the field value

Consider a table MYEMPLOYEE with Columns: EMPID, NAME, ADDRESS
When inserting the data, if any value entered wrongly as below
and want to update a particular text in it, we can use the below query.
UPDATE myemployee set address = replace(address, 'gandhi', 'nehru') where address like '%gandhi%';
and the result would be upon select query is

2.4 DELETE

2.5 MERGE

3. DCL OPERATIONS

3.1 GRANT

3.2 REVOKE

4. DATE COLUMN OPERATIONS

4.1 SELECT

SELECT * from employee where to_char(dob, 'mmddyyyy') = 03262012;

4.2 UPDATE

UPDATE employee set dob=to_date('20120117', 'yyyymmdd') where id = 1004;

5. TIMESTAMP COLUMN OPERATIONS

5.1 UPDATE

UPDATE employee SET dob = TO_TIMESTAMP('17-Jan-2012 12:00:00.000000 PM') where id=1004;

6. CREATE NEW USER

  1. Find the tablespaces (Default & Temporary tablespace)

select * from dba_tablespaces;

if tablespace not found then create it.

create tablespace lob_data datafile 'lob_data' size 200M;
create tablespace user_data datafile 'user_data' size 100M;
create tablespace index_data datafile 'index_data' size 100;

  1. Create new user
CREATE USER RANJITH IDENTIFIED BY RANJITH DEFAULT TABLESPACE "USER_DATA" TEMPORARY TABLESPACE "TEMP";
ALTER USER RANJITH QUOTA UNLIMITED ON LOB_DATA;
ALTER USER RANJITH QUOTA UNLIMITED ON INDEX_DATA;
ALTER USER RANJITH QUOTA UNLIMITED ON USER_DATA;
GRANT UNLIMITED TABLESPACE TO RANJITH;
GRANT ALL PRIVILEGES to RANJITH;

  1. Grant Permissions
grant create session, connect, resource to RANJITH;

  1. Simple admin tasks to Resize datafile in case of out of space
These command should be run from sysdba user
ALTER DATABASE DATAFILE 'lob_data' RESIZE 1G;
ALTER DATABASE DATAFILE 'user_data' RESIZE 500M;
ALTER DATABASE DATAFILE 'index_data' RESIZE 300M;

7. FIND OPERATIONS

  1. How to find duplicate data in a table in Oracle?

SELECT columnName, COUNT(columnName)
FROM tableName
GROUP BY columnName
HAVING COUNT (columnName) > 1;

(OR)

SELECT columnName, COUNT(*)
FROM tableName
GROUP BY columnName
HAVING COUNT (*) > 1;