Thursday, October 30, 2014

Factory Pattern


package com.exmpl.factoryPattern;

public interface Animal {
       void getVoice();
}
package com.exmpl.factoryPattern;

public class Dog implements Animal {

       @Override
       public void getVoice() {
              System.out.println("Dog voice --- Bark Bark Bark Bark Bark");
       }
}
package com.exmpl.factoryPattern;

public class Cat implements Animal {

       @Override
       public void getVoice() {
              System.out.println("Cat voice --- Meow Meow Meow Meow Meow");
       }
}
package com.exmpl.factoryPattern;

public class Tiger implements Animal {

       @Override
       public void getVoice() {
              System.out.println("Tiger voice --- Growl Growl Growl Growl Growl");
       }
}
package com.exmpl.factoryPattern;

/*This is the factory class, which create specific animal based on animal type supplied.*/
public class AnimalFactory {
       final static String TIGER = "tiger";
       final static String DOG = "dog";
       final static String CAT = "cat";

       public Animal getAnimal(String animalType) {
              Animal returnAnimal = null;
              if (animalType != null) {
                     if (animalType.equalsIgnoreCase(TIGER)) {
                           returnAnimal = new Tiger();
                     } else if (animalType.equalsIgnoreCase(DOG)) {
                           returnAnimal = new Dog();
                     } else if (animalType.equalsIgnoreCase(CAT)) {
                           returnAnimal = new Cat();
                     }
              }
              return returnAnimal;
       }
}
package com.exmpl.factoryPattern;

public class ClientClass {

       public static void main(String[] args) {
              AnimalFactory animalFactory = new AnimalFactory();

              // Get tiger object from AnimalFactory and check it's voice.
              Animal animal1 = animalFactory.getAnimal("tiger");
              animal1.getVoice();

              // Get dog object from AnimalFactory and check it's voice.
              Animal animal2 = animalFactory.getAnimal("dog");
              animal2.getVoice();

              // Get cat object from AnimalFactory and check it's voice.
              Animal animal3 = animalFactory.getAnimal("cat");
              animal3.getVoice();
       }
}
Output รจ
Tiger voice --- Growl Growl Growl Growl Growl
Dog voice --- Bark Bark Bark Bark Bark

Cat voice --- Meow Meow Meow Meow Meow

Singleton Pattern

package com.exmpl.singleton;

public class PatternClass {
       // 1. create an object of PatternClass.
       private static PatternClass instance = new PatternClass();

       // 2. Create a private constructor, so that this class can not be
       // instantiated.
       private PatternClass() {
              // No argument constructor.
       }

       // 3. Create a getter method of "instance" property, which return instance
       // of "PatternClass".
       public static PatternClass getInstance() {
              return instance;
       }

       // Normal method.
       public void displayMessage() {
              System.out.println("I am displayMessage() under PatternClass.");
       }
}
package com.exmpl.singleton;

public class ClientClass {

       public static void main(String[] args) {
              /*
               * We can not create an instance of "PatternClass" as below, because of
               * private constructor. The following line will shown an compilation
               * error.
               */
              // PatternClass patternClass = new PatternClass();

              /*
               * Get the instance of "PatternClass", by calling "getInstance()"
               * method.
               */
              PatternClass patternClass = PatternClass.getInstance();
              // Now calling "displayMessage()" method.
              patternClass.displayMessage();
       }
}

Output รจ I am displayMessage() under PatternClass.

Wednesday, October 29, 2014

Design Patterns

  • 1     Creational Patterns รจ This type of pattern is responsible to create objects without instantiate objects directly using “new” operator.

                                 i.            Singleton Pattern
                               ii.            Factory Pattern
                              iii.            Abstract Factory Pattern
                             iv.            Builder Pattern
                               v.            Prototype Pattern
  • 2       Structural Pattern รจ This type of pattern is responsible to describe how objects and classes will be combined to create a large structure.  Here, Inheritance (class and subclass concept) is use to compose Interface.

                                 i.            Adapter Pattern
                               ii.            Bridge Pattern
                              iii.            Composite Pattern
                             iv.            Decorator Pattern
                               v.            Faรงade Pattern
                             vi.            Flyweight Pattern
                            vii.            Proxy Pattern
  • 3      Behavioral Patterns รจ This pattern describes interaction between objects. This pattern is used to describe the interaction between objects in such a way, so that objects will interact with each other in a loosely coupled manner.

                                 i.            Chain of Responsibility Pattern
                               ii.            Command Pattern 
                              iii.            Interpreter Pattern
                             iv.            Iterator Pattern
                               v.            Mediator Pattern
                             vi.            Momento Pattern
                            vii.            Observer Pattern
                          viii.            State Pattern
                             ix.            Strategy Pattern
                               x.            Template Pattern

                             xi.            Visitor Pattern

   4. Architectural Pattern ==>
            i. MVC

Saturday, August 3, 2013

Log4j example in java


  1. Download “log4j-x.x.x.jar” file.
  2. Create a java project in eclipse.
  3. Open project’s properties and click on “Java Build Path” and then go to “Libraries” tab and add this jar by click on “Add External Jars..” tab.

Friday, July 12, 2013

Comparator interface to sort java object based on it's parameter.

Sort list of Employee object based on it's name parameter.

1.Bean class:
package com.collection.javacodepractices;

public class Employee {
      private int rollNo;
      private String name;

      public int getRollNo() {
            return rollNo;
      }

      public void setRollNo(int rollNo) {
            this.rollNo = rollNo;
      }

      public String getName() {
            return name;
      }

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

      @Override
      public String toString() {
            return "Employee [rollNo=" + rollNo + ", name=" + name + "]";
      }


}

2.Comparable class:
package com.collection.javacodepractices;

import java.util.Comparator;

public class EmployeeComparable implements Comparator<Employee>{

      @Override
      public int compare(Employee empOne, Employee empTwo) {
            return (empOne.getName().compareToIgnoreCase(empTwo.getName())<0?-1:                                                   (empOne.getName().equalsIgnoreCase(empTwo.getName())?0:1));
      }

}

3.Client class:
package com.collection.javacodepractices;

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

public class Client {
      public static void main(String args[]) {
            List<Employee> empList = new ArrayList<Employee>();

            // 1. employee setting.
            Employee emp1 = new Employee();
            emp1.setRollNo(1);
            emp1.setName("Bijoy");
            // 2. employee setting.
            Employee emp2 = new Employee();
            emp2.setRollNo(2);
            emp2.setName("Bappa");
            // 3. employee setting.
            Employee emp3 = new Employee();
            emp3.setRollNo(3);
            emp3.setName("Chintu");
            // 4. employee setting.
            Employee emp4 = new Employee();
            emp4.setRollNo(4);
            emp4.setName("Rahul");
            // 5. employee setting.
            Employee emp5 = new Employee();
            emp5.setRollNo(5);
            emp5.setName("Ajoy");
           
            //Add employee object to list.
            empList.add(emp1);
            empList.add(emp2);
            empList.add(emp3);
            empList.add(emp4);
            empList.add(emp5);
           
            //sorting employee based on name using comparator interface.
            Collections.sort(empList, new EmployeeComparable());
           
            //Print Employee object.
            for(Employee emp:empList){
                  System.out.println(emp.toString());
            }
      }
}

OUTPUT:
Employee [rollNo=5, name=Ajoy]
Employee [rollNo=2, name=Bappa]
Employee [rollNo=1, name=Bijoy]
Employee [rollNo=3, name=Chintu]
Employee [rollNo=4, name=Rahul]

Monday, June 10, 2013

Send mail using java (Exchange Server)


External jar needs to be added is "mail.jar".
========================================================
package com.myExample.mail;

public class Client {
      public static void main(String[] args) {
            String To = "abc1@xyz.com; abc2@xyz.com ; abc3@xyz.com ";
            String CC = " abc4@xyz.com; abc5@xyz.com ; abc6@xyz.com ";
            String BCC = "abc@xyz.com";
            String From = "myExmp@ddd.com";
            String Subject = "Test subject line.";
            String Body = "Test mail Body.";
            MailExample obj = new MailExample();
            obj.sendAMail(To, CC, BCC, From, Body, Subject);
      }
}

=========================================================
package com.myExample.mail;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

public class MailExample {
                public void sendAMail(String To, String CC, String BCC, String From,
                                                String Body, String Subject) {
                                try {
                                                Sendmail(To, CC, BCC, From, Body, Subject);
                                } catch (MessagingException ex) {
                                                Logger.getLogger(MailExample.class.getName()).log(Level.SEVERE,
                                                                                null, ex);
                                }
                }

                public void Sendmail(String To, String CC, String BCC, String From,
                                                String Body, String Subject) throws MessagingException {
                                Message message = new MimeMessage(getSession());
                                if (To != null && To.trim().length() > 0) {
                                                //Separate "To" mail address based on ";" separator and set it into mail "To" address.
                                                Iterator<String> ToIterator=this.getAddressList(To).iterator();
                                                while(ToIterator.hasNext()){
                                                                message.addRecipient(RecipientType.TO, new InternetAddress(ToIterator.next()));
                                                }
                                               
                                                if (CC != null && CC.trim().length() > 0){
                                                                //Separate "CC" mail address based on ";" separator and set it into mail "CC" address.
                                                                Iterator<String> CCIterator=this.getAddressList(CC).iterator();
                                                                while(CCIterator.hasNext()){
                                                                                message.addRecipient(RecipientType.CC, new InternetAddress(CCIterator.next()));
                                                                }
                                                }
                                                               
                                                if (BCC != null && BCC.trim().length() > 0){
                                                                //Separate "BCC" mail address based on ";" separator and set it into mail "BCC" address.
                                                                Iterator<String> BCCIterator=this.getAddressList(BCC).iterator();
                                                                while(BCCIterator.hasNext()){
                                                                                message.addRecipient(RecipientType.BCC, new InternetAddress(BCCIterator.next()));
                                                                }
                                                }
                                               
                                                if (From != null && From.trim().length() > 0)
                                                                message.addFrom(new InternetAddress[] { new InternetAddress(
                                                                                                From) });

                                                message.setSubject(Subject);
                                                message.setContent(Body, "text/plain");
                                }
                                System.out.println("Sending mail .............................");
                                Transport.send(message);
                                System.out.println("Mail sent .............................");
                }

                private Session getSession() {
                                Authenticator authenticator = new Authenticator();

                                Properties properties = new Properties();
                                properties.setProperty("mail.smtp.submitter", authenticator
                                                                .getPasswordAuthentication().getUserName());
                                properties.setProperty("mail.smtp.auth", "true");

                                properties.setProperty("mail.smtp.host", "172.16.16.99");
                                properties.setProperty("mail.smtp.port", "25");

                                return Session.getInstance(properties, authenticator);
                }

                private class Authenticator extends javax.mail.Authenticator {
                                private PasswordAuthentication authentication;

                                public Authenticator() {
                                                String username = "username";
                                                String password = password";
                                                authentication = new PasswordAuthentication(username, password);
                                }

                                protected PasswordAuthentication getPasswordAuthentication() {
                                                return authentication;
                                }
                }
               
                //Separate string using ';' separator.
                private List<String> getAddressList(String address){
                                String mailAddress=address;
                                List<String> mailAddressList = null;
                                if(mailAddress != null && mailAddress.trim().length()>0){
                                                mailAddressList = new ArrayList<String>();
                                                if(mailAddress.contains(";")){
                                                                mailAddressList=Arrays.asList(mailAddress.split(";"));
                                                }else{
                                                                mailAddressList.add(mailAddress.trim());
                                                }
                                }
                                return mailAddressList;
                }
}