Wednesday, 22 October 2014

Java Composition Vs. Inheritance

What is Java Composition?

Java composition is a design technique using which we can reuse the java code.This is applicable when there is a has a relationship between two entity or classes.

eg. Student has an Address

Student.java
package com.nik.composition;
public class Student{

public void displayDetail(){
System.out.println("Student Detail is aaaa");
}
}


Address.java
package com.nik.composition;
public class Address{
Student stud; // Create Student instance variable as a data member of the Adderss class

public Address(){
stud=new Student();    //Initialize Student Object along with Address object
}
public void displayAddress()
{
System.out.println("Student Address is xxx");
}

public displayStudentCompleteDetail(){   // new method to access the Student method
stud.displayDetail();
 System.out.println("Student Address is xxx");
}
}

MainClass.java
public class MainClass{
public static void main(String[] arg) {
   Address addr=new Address();
   addr.displayStudentCompleteDetail(); // No need to create Student object
}
}

Advantage of using Java composition over Inheritance

1)Your code becomes loosely coupled and more flexible if you use composition.Changes in superclass  methods has no effect in their child classes overridden methods.
2)This approach more easily accommodates future requirements changes that would otherwise require a complete restructuring of business-domain classes in the inheritance model
3)Initial design is simplified by identifying system object behaviors in separate interfaces instead of creating a hierarchical relationship to distribute behaviors among business-domain classes via inheritance.


Friday, 25 April 2014

How to schedule a task in java

Here is an easy code to explain the TimerTask ...

Create a TimerTask by creating a class which will extend TimerTask..
The code is  given below

package com.nik.timer;

import java.util.TimerTask;

public class MyTimerTask extends TimerTask {

    int time;

    public void myTask() {
        System.out.println("This task is invoked after " + time + " minute");
    }

    public MyTimerTask(int time) {
        this.time = time;
    }

    @Override
    public void run() {
        myTask();
    }

}


 Another class to invoke the timer

 package com.nik.timer;

import java.util.Timer;

public class TimerDemo {
    public static void main(String args[]) throws InterruptedException {
        System.out.println("Timer started........");
        Timer myTimer = new Timer();
        myTimer.schedule(new MyTimerTask(1), 6000);
        Thread.sleep(6000);
        myTimer.cancel();
    }

}

Saturday, 7 December 2013

Get All System Properties

Simple but useful  ......


package com.nik;

import java.util.Iterator;
import java.util.Properties;


//Reference of Doc  http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html

//"file.separator"     Character that separates components of a file path. This is "/" on UNIX and "\" on Windows.
//"java.class.path"     Path used to find directories and JAR archives containing class files. Elements of the class path are separated by a platform-specific character specified in the path.separator property.
//"java.home"     Installation directory for Java Runtime Environment (JRE)
//"java.vendor"     JRE vendor name
//"java.vendor.url"     JRE vendor URL
//"java.version"     JRE version number
//"line.separator"     Sequence used by operating system to separate lines in text files
//"os.arch"     Operating system architecture
//"os.name"     Operating system name
//"os.version"     Operating system version
//"path.separator"     Path separator character used in java.class.path
//"user.dir"     User working directory
//"user.home"     User home directory
//"user.name"     User account name

public class ReadSystemProperties {
    public static void main(String arg[]){
        Properties properties=System.getProperties();
        Iterator<Object> sysProp=properties.keySet().iterator();
       
        while(sysProp.hasNext())
            System.out.println(sysProp.next().toString()+" --> "+properties.get(sysProp.next().toString()));
       
    }

}

Thursday, 7 November 2013

Convert Html To PDF for Simple and Special Char Using Java

Convert Html To PDF

import com.nik.pdf;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.clapper.util.html.HTMLUtil;
import org.xhtmlrenderer.pdf.ITextRenderer;

public class HtmlToPdf {

    public static void convertHtmlToPdf() {

        try {

            StringBuffer bufferForHtml = new StringBuffer();
            bufferForHtml
                    .append("<html>"
                            + "<head>"
                            + "<style language='text/css'>"
                            + ".c1{font-size:12px;font-family:\"Times New Roman\";}"
                            + ".pos_right{position:relative;left:20px;}"
                            + ".pos_top{position:relative;top:-50px;}"
                            + ".top_alignment{vertical-align:text-top;}"
                            + ".bottom_alignment{vertical-align:text-bottom;}"
                            + "table.layout1 {table-layout:auto;}"
                            + "table.layout2 {table-layout:fixed;}"
                            + "</style>"
                            + "</head>"
                            + "<body class='c1'>"
                            + "<p align=\"center\">This is a test PDF  by Nitesh  &copy;</p>"
                            + "<p>Few mathematical notations : &#8825;&#8904;&#8939; </p>"
                            + "</body></html>");
            String htmlConvert = HTMLUtil
                    .convertCharacterEntities(bufferForHtml.toString());
            DocumentBuilder builder = DocumentBuilderFactory.newInstance()
                    .newDocumentBuilder();
            org.w3c.dom.Document doc = builder.parse(new ByteArrayInputStream(
                    htmlConvert.getBytes("UTF-8")));
            ITextRenderer renderer = new ITextRenderer();
//For mathematical latin symbols use -->renderer.getFontResolver().addFont("E:\\ARIALUNI.TTF",BaseFont.IDENTITY_H, //BaseFont.NOT_EMBEDDED);
//Change  BaseFont for different type of Character encoding like BaseFont.CP152 for chinese char
            renderer.setDocument(doc, null);
            OutputStream outputFile = new FileOutputStream("E:\\test.pdf");
            renderer.layout();
            renderer.createPDF(outputFile);
            outputFile.close();
        }

        catch (Exception e) {
            System.out.println("catch me");
            throw new RuntimeException(e);

        }

    }

    public static void main(String[] arg) {
        convertHtmlToPdf();
    }

}

Friday, 19 July 2013

This code will help u to authenticate your web application using system credential

Java  Network HTTP Authentication :-


This code will help u to authenticate your web application using system credential.


If u want to set the authentication for network http authentication for your application U need to override the method of Authenticator Class and set your password
 static class CustomAuthenticator extends Authenticator {
   static final String userId="test";
static final String password="password";
        public PasswordAuthentication getPasswordAuthentication() {
                                  return (new PasswordAuthentication(userId,password.toCharArray()));
        }
    }

    public static void main(String[] args) throws Exception {
        Authenticator.setDefault(new CustomAuthenticator ());//set the custom default network login password
        PasswordAuthentication pswAuth=new CustomAuthenticator().getPasswordAuthentication();
        System.out.println("Default authentication User :"+pswAuth.getUserName());
        System.out.println("Default authentication Password :"+pswAuth.getPassword().toString());           }
}


Saturday, 4 May 2013

String argument in switch statement.. JDK 7 useful feature

String argument in switch statement
In the JDK 7 release, we can use a String object in the expression of a switch statement..
Example given below

class TestClass{
public integer getIntegerFromString(String stringFormat) {
     integer number;
     switch (stringFormat) {
         case "One":
            number=1;
             break;
         case "Two":number=2;break;
         case "Three":number=3;break;
         case "Four":number=4;break;
            
         case "Five": number=5;
             break;
         case "Six":number=6;break;
         case "Seven":
            number=7;break;
         case "Eight":
             number=8;break;
         case "Nine":
            number=9;break;
         case "Zero":
            number=0;break; 
   default:System.out.println("Not an integer value");
            
     }
     return number;
}
 
public static void main(String arg[])
{
          TestClass obj=new TestClass();
          System.out.println("Integer value of Three is "+obj.getIntegerFromString("Three") ;
 
} 
 
 
} 


The switch statement compares the String object in its expression with the expressions associated with each case label as if it were using the String.equals method; consequently, the comparison of String objects in switch statements is case sensitive. The Java compiler generates generally more efficient bytecode from switch statements that use String objects than from chained if-then-else statements

Tuesday, 16 April 2013

PKIX path building failed,Here is the solution

You have to created a trustServerCertificate() which basically trust the certificate of the requested server at runtime.
For that you should do the following step

1)Create a keystore and import the certificate into this keystore file (say test.keystore)
2)put it into your project class path
3)Write a method trustServerCertificate() which trust the keystore file

keystore.properties
KeyStoreLocation=/test.keystore


TrustClass.java

class TrustClass{
static Properties properties = new Properties();
void trustServerCertificate(){
try {
               
                properties.load(TrustClass.class.getClassLoader().getResourceAsStream("keystore.properties"));
                System.out.println("Properties loaded successfully");
            } catch (IOException e) {
                properties = null;
                System.out.println("Properties not loaded: " + e.getMessage());
                e.printStackTrace();
            }
            String keyStore = Util.class.getClassLoader().getResource(TrustClass.getProperties("KeyStoreLocation")).getFile();
            System.out.println("Keystore  path :" + keyStore);
            System.setProperty("javax.net.ssl.trustStore", keyStore);
            Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

}
 public static String getProperties(String key) {
            return properties.getProperty(key);
        }
public static void main(String arg[]){
TrustClass obj=new TrustClass();
obj. trustServerCertificate
}

}

Saturday, 6 April 2013

Measure runtime memory used by your code

Measure runtime memory used by your code:

//Start
------
-------
YourAPIClass object=new  YourAPIClass();

Runtime runtime = Runtime.getRuntime();

object.someMethod()//call your api methods whose memory usage u want to know

runtime.gc(); // Run garbage collector

long usedMemory = runtime.totalMemory() - runtime.freeMemory(); // Used memory Evaluation In bytes


System.out.println("Memory used by someMetod is = " usedMemory +" bytes");


--------
--------
//end

Tuesday, 26 February 2013

How to run tomcat over ssl

 How to run tomcat  over ssl..........


Do the following step
1)Go to the $JAVA_HOME/bin and Create a keystore file(say test.keystore) using the keytool command

keytool -genkey -alias testtomcat -keyalg RSA -keystore /root/nikapps/test.keystore

2)Configure the  server.xml file of tomcat server u r using
 <Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol" SSLEnabled="true"
           maxThreads="150"  keystoreFile="/root/nikapps/test.keystore" keystorePass="changeit" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" />

3)start the tomcat server and open the browser type https://localhost:8443

Thursday, 31 January 2013

How to check SSL certificate valid or not Using java code:


try{
URL url = new URL("https://www.google.com");
            URLConnection mycon = url.openConnection();
            //causes the VM to display a dialog when connecting to untrusted servers
            mycon.setAllowUserInteraction(true);
            mycon.getInputStream();
}catch(Exception e){e.printStackTrace();}

Thursday, 22 November 2012

Introductio with Collection Framework

Introductio with Collection Framework:

Collection is an Interface ... which provide us a well defined set of interfaces and classes to handle  and manipulate a group or collection of objects.

List and Set  are Interfaces and  both of them extends the Collection Interface.

List : --List is an ordered collection of objects which has the indexing property  and allows  duplicates...
The methods includedin it are given in the table bellow....
        
void
add(int index, Object element)
Inserts the specified element at the specified position in this list (optional operation).
 boolean
add(Object o)
Appends the specified element to the end of this list (optional operation).
 boolean
addAll(Collection c)
Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator (optional operation).
 boolean
addAll(int index, Collection c)
Inserts all of the elements in the specified collection into this list at the specified position (optional operation).
 void
clear()
Removes all of the elements from this list (optional operation).
 boolean
contains(Object o)
          Returns true if this list contains the specified element.
 boolean
containsAll(Collection c)
Returns true if this list contains all of the elements of the specified collection.
 boolean
equals(Object o)
Compares the specified object with this list for equality.
 Object
get(int index)
Returns the element at the specified position in this list.
 int
hashCode()
Returns the hash code value for this list.
 int
indexOf(Object o)
Returns the index in this list of the first occurrence of the specified element, or -1 if this list does not contain this element.
 boolean
isEmpty()
Returns true if this list contains no elements.
 Iterator
iterator()
Returns an iterator over the elements in this list in proper sequence.
 int
lastIndexOf(Object o)
Returns the index in this list of the last occurrence of the specified element, or -1 if this list does not contain this element.
 ListIterator
listIterator()
Returns a list iterator of the elements in this list (in proper sequence).
 ListIterator
listIterator(int index)
Returns a list iterator of the elements in this list (in proper sequence), starting at the specified position in this list.
 Object
remove(int index)
Removes the element at the specified position in this list (optional operation).
 boolean
remove(Object o)
Removes the first occurrence in this list of the specified element (optional operation).
 boolean
removeAll(Collection c)
Removes from this list all the elements that are contained in the specified collection (optional operation).
 boolean
retainAll(Collection c)
Retains only the elements in this list that are contained in the specified collection (optional operation).
 Object
set(int index, Object element)
Replaces the element at the specified position in this list with the specified element (optional operation).
 int
size()
Returns the number of elements in this list.
 List
subList(int fromIndex, int toIndex)
Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.
 Object[]
toArray()
Returns an array containing all of the elements in this list in proper sequence.
 Object[]
toArray(Object[] a)
Returns an array containing all of the elements in this list in proper sequence; the runtime type of the returned array is that of the specified array.

Class which impelements List...are ArrayList and LinkedList

Set :-- Set is  a collection of unique objects which forbids  duplicate objects..

the methods included in Set are given in the table below...


boolean
add (Object o)
Ensures that this collection contains the specified element (optional operation).
 boolean
addAll(Collection c)
Adds all of the elements in the specified collection to this collection (optional operation).
 void
clear()
Removes all of the elements from this collection (optional operation).
 boolean
contains(Object o)
Returns true if this collection contains the specified element.
 boolean
containsAll(Collection c)
Returns true if this collection contains all of the elements in the specified collection.
 boolean
equals(Object o)
Compares the specified object with this collection for equality.
 int
hashCode()
Returns the hash code value for this collection.
 boolean
isEmpty()
Returns true if this collection contains no elements.
 Iterator
iterator()
Returns an iterator over the elements in this collection.
 boolean
remove(Object o)
Removes a single instance of the specified element from this collection, if it is present (optional operation).
 boolean
removeAll(Collection c)
Removes all this collection's elements that are also contained in the specified collection (optional operation).
 boolean
retainAll(Collection c)
Retains only the elements in this collection that are contained in the specified collection (optional operation).
 int
size()
Returns the number of elements in this collection.
 Object[]
toArray()
Returns an array containing all of the elements in this collection.
 Object[]
toArray(Object[] a)
Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array.


Class which impelements set...Hashset and TreeSet.
Vector :--  A Vector is an historical collection class that acts like a growable array, but can store heterogeneous data elements.It is synchronized and thread safe.

Map :--  Map is  also an interface but not extends the Collection Interface.It is a key-value association of objects with unique key .

Class Which Implements Map ... Hashmap and TreeMap.... 


Introduction with comperator and comperable

Introduction with comperator and comperable:

Comperator and comperable are interfaces used for compairing objects .

Implementation of Comparator and Comperable Interfaces

class Student implements Comparator<Student>{
   private String name;
   private int age;
   Student(){   }

   Student(String stdName, int stdAge){
      name = stdName;
      age = stdAge;
   }

   public String getName(){
      return name;
   }

   public int getAge(){
      return age;
   }

   
   // Overriding the compare method to sort the age 
   public int compare(Student s1, Student s2){
      return s1.age - s2.age;
   }
}
 
public class Member implements comperable<Member>{
   private String name;
   private int age;
    Member(){
   }

   Student(String memName, int mebAge){
      name = mebName;
      age = mebAge;
   } 

 
 
 // Overriding the compareTo method
   public int compareTo(Member mem){
      return (this.name).compareTo(mem.name);
   }
}
 public class MainClass{
   public static void main(String args[]){
     
      List<Student> list = new ArrayList<Student>();

      list.add(new Student("Roma",20));
      list.add(new Student("Rama",12));
      list.add(new Student("Froger",10));
      list.add(new Student("Raghav",14));
      list.add(new Student("Nammy",11));
      Collections.sort(list);// Sorts the array list

      for(Student a: list)//printing the sorted list of names
         System.out.print(a.getName() + ", ");

      // Sorts the array list using comparator
      Collections.sort(list, new Student());
      System.out.println(" ");
      for(Student a: list)//printing the sorted list of ages
         System.out.print(a.getName() +"  : "+
   a.getAge() + ", ");
   }
}

Thursday, 8 November 2012

Vector Vs ArrayList which is preferable

Vector Vs ArrayList

We can compare this two based on some parameters....like Synchronization, DataSize

1)Vector is synchronized while Arraylist is not synchronized.Synchronization always pay for efficiency,so it is better to use ArrayList if we don't need thread safe data acces,Other wise go for Vector.

2)The size always matters,--Both vector and ArrayList are resizable(dynamic for their size),
but when size increase..Vector increase it's size by double and on the other hand ArrayList increases it's size by half of  its previous size.So it is better to use ArrayList wrt size.

3)Arraylist are faster and speedup the execution while vector are less efficient than ArrayList.

4)Vector is threadsafe while ArrayList is not threadsafe.

Wednesday, 7 November 2012


JSF Core Tags




Tag Description
view Creates the top-level view
subview Creates a subview of a view
facet Adds a facet to a component
attribute Adds an attribute (key/value) to a component
param Adds a parameter to a component
actionListener Adds an action listener to a component
valueChangeListener Adds a valuechange listener to a component/>
convertDateTimeAdds a datetime converter to a component
convertNumber
Adds a number converter to a component
validator
Adds a validator to a component
validateDoubleRange
Validates a double range for a component’s value
validateLength
Validates the length of a component’s value
validateLongRange
Validates a long range for a component’s value
loadBundle
Loads a resource bundle, stores properties as a Map
selectitems
Specifies items for a select one or select many
selectitem
Specifies an item for a select one or select many component
verbatim
Adds markup to a JSF page