Sunday, 31 July 2016

Velocity Template Example in Java

Velocity is a simple to use, open source web framework designed to be used as the view component of an MVC architecture. 
..
The main advantage of using Velocity over JSP is that Velocity is simple to use. The Velocity Template Language (VTL) is so constrained in its capabilities that it helps to enforce separation of business logic from the view.  You won't see any Java classes in a Velocity template (an HTML document with some Velocity placeholders). 

.
Add Three Jars : apache-commons-lang.jar , apache-velocity-velocity-1.5.jar , org.apache.commons.collections.jar




/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package jaxb;

import java.io.StringWriter;

import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

/**
 *
 * @author ananddw
 */
public class EmailDemo {

    public static void main(String[] args)
            throws Exception {
        /*
         *   first, get and initialize an engine
         */

        VelocityEngine ve = new VelocityEngine();
        ve.init();

        /*
         *   organize our data
         */
        ArrayList list = new ArrayList();
        Map map = new HashMap();

        map.put("name", "Anand");
        map.put("salary", "100.00");
        list.add(map);

        map = new HashMap();
        map.put("name", "Antrish");
        map.put("salary", "600.40");
        list.add(map);

        map = new HashMap();
        map.put("name", "Ajeet");
        map.put("salary", "500.00");
        list.add(map);

        /*
         *  add that list to a VelocityContext
         */
        VelocityContext context = new VelocityContext();
        context.put("emplist", list);

        /*
         *   get the Template 
         */
        Template t = ve.getTemplate("test_html.vm");

        /*
         *  now render the template into a Writer, here
         *  a StringWriter
         */
        StringWriter writer = new StringWriter();

        t.merge(context, writer);

        /*
         *  use the output in the body of your emails
         */
        System.out.println(writer.toString());
    }
}


==============test_html.vm=====


  <HTML>
    <HEAD>
      <TITLE>Employee details</TITLE>
    </HEAD>


    <BODY>
      <CENTER>
      <B>$emplist.size() Employee</B>
     
      <BR/>
      This is an email generated by velocity
      <BR/>
      This month only, choose from :
   
      #set( $count = 1 ) 
      <TABLE>
        #foreach( $list in $emplist )
          <TR>
            <TD>$count</TD>
            <TD>$list.name</TD>
            <TD>$list.salary</TD>
          </TR>
          #set( $count = $count + 1 )
        #end
      </TABLE>
     
   
      </CENTER>

    </BODY>
  </HTML>
 

Thursday, 14 July 2016

What is difference between Vector and ArrayList in Java?

  • One of the important interview question in java specially from Experience candidate
Vector :-

         /*
         * Vector is synchronized and thread-safe.
         * Performance wise slower then ArrayList.
         * One Thread is running at a time.
         * Once thread got completed it gives lock to other thread
         * Thread Safe
         */


 ArrayList :-
       /*
         * ArrayList is not synchronized nor thread-safe.
         * Performance wise faster then Vector.
         * multiple Threads is running at a time.
         * Not Thread Safe
         */


Programme



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package highleveljava;

import java.util.*;

/**
 *
 * @author Admin
 */
public class ArrayListandVector {

    public Vector vector;
    public List list;
    public String fname = "Ajeet";
    public String tname = "Antrish";
    public String lname = "Anand";

    public void compareALVC() {
        vector = new Vector();
        /*
         Add Some Data into Vector
         */

        vector.add(fname);
        vector.add(tname);
        vector.add(lname);

        System.out.println("Vector data is " + vector);

        /*
         * Vector is synchronized and thread-safe.
         * Performance wise slower then ArrayList.
         * One Thread is running at a time.
         * Once thread got completed it gives lock to other thread
         * Thread Safe
         */
        list = new ArrayList();
        /*
         Add Some Data into ArrayList
         */
        list.add(fname);
        list.add(tname);
        list.add(lname);

        System.out.println("List data is " + list);


        /*
         * ArrayList is not synchronized nor thread-safe.
         * Performance wise faster then Vector.
         * multiple Threads is running at a time.
         * Not Thread Safe
         */
    }

    public static void main(String[] args) {

        ArrayListandVector classobject = new ArrayListandVector();
        classobject.compareALVC();
    }

}
 

How to Add and Fetch Class Data from List in Java

  • One of the most concept which is used in interview question as well as in program level . because if we add object into list and print the reference it will print whole data not referece
  • But if we add Class level data it will print reference so we need to perform type casting so easily we can fetch the record and print it 
programme:-



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package highleveljava;

import java.util.*;

/**
 *
 * @author Admin
 */
public class GenericType {
    /*
     Global Variable
     */

    public static String customername;
    public static String customerid;
    public static String customerlocation;

    /*
     Setter and getter
     */
    public static String getCustomername() {
        return customername;
    }

    public static void setCustomername(String customername) {
        GenericType.customername = customername;
    }

    public static String getCustomerid() {
        return customerid;
    }

    public static void setCustomerid(String customerid) {
        GenericType.customerid = customerid;
    }

    public static String getCustomerlocation() {
        return customerlocation;
    }

    public static void setCustomerlocation(String customerlocation) {
        GenericType.customerlocation = customerlocation;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        /*
         set the variable value
         */
        GenericType classobject = new GenericType();
        classobject.setCustomername("Anand");
        classobject.setCustomerid("101");
        classobject.setCustomerlocation("Bangalore");
        /*
         Add Class reference into list
         */
        List<GenericType> list = new ArrayList<GenericType>();
        list.add(classobject);
    
        /*
         Fetch class level data
         */
        customername = ((GenericType) list.get(0)).getCustomername();
        customerid = ((GenericType) list.get(0)).getCustomerid();
        customerlocation = ((GenericType) list.get(0)).getCustomerlocation();

        /*
         Lets Print the data
         */
        System.out.println("\t" + customername + "\t" + customerid + "\t" + customerlocation);
    }

}



Thanks  for More Details Comment here !  

Monday, 11 July 2016

Nested while loop in java

Placing one while loop with in the body of another while is called Nested while loop in java programm.


CODE

public class NestedWhileExample
{
    public static void main(String arg[])
    {
        int outer = 1;
        while(outer < 3)
        {
            int inner = 5; 
            while(inner < 8)
            {
                System.out.println(outer + "  " + inner);
                inner++;
            }
            outer++;
        }
    
    }
}


Output :
1 5
1 6
1 7
2 5
2 6
2 7



DESCRIPTION
Here outer loop is executed for values going from 1 till less than 3 i.e. 1 and 2. Similarly inner loop is executed from 5 till less than 8 i.e. 5, 6 and 7. So when outer is 1, inner will become 5, 6, and 7 and when outer is 2, then also inner will become 5, 6, and 7.

Saturday, 9 July 2016

How to wait on file creation in Java

Here are some steps that we can remember while move in to coding part
  1. Iterate the (!file.exist()) blog till this block becomes as a false . so for that we can use Thread class and do Thread.sleep(10). that will wait for 10ns  and once time has been expire again it start same loop . means every 10 ns it will check on directory whether file is exist or not . if not then iterate.
  2.  once it got the file on directory then while loop iteration will stop and terminate the execution of while block  
Programme to wait on file creation in Java



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.*;

/**
 *
 * @author Anand
 */
public class FileOperation {

    public void ProcessFile() {
        File statText = new File("statsTest1.txt");// Check for this file
        while (!statText.exists()) {
            try {
                Thread.sleep(10);//wait for 10 ns
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println("Finally got the =>"+statText.getName());

    }

    public static void main(String[] args) {
        FileOperation write = new FileOperation();
        write.ProcessFile();
    }
}

For any query Ask Here . happy Coding

Anand

Null Pointer Exception Class Implementation in Java

Here is the implementation of NullPointerException class in Java : -

  1   /*
    2    * Copyright (c) 1994, 2011, Oracle and/or its affiliates. All rights reserved.
    3    * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    4    *
    5    * This code is free software; you can redistribute it and/or modify it
    6    * under the terms of the GNU General Public License version 2 only, as
    7    * published by the Free Software Foundation.  Oracle designates this
    8    * particular file as subject to the "Classpath" exception as provided
    9    * by Oracle in the LICENSE file that accompanied this code.
   10    *
   11    * This code is distributed in the hope that it will be useful, but WITHOUT
   12    * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   13    * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   14    * version 2 for more details (a copy is included in the LICENSE file that
   15    * accompanied this code).
   16    *
   17    * You should have received a copy of the GNU General Public License version
   18    * 2 along with this work; if not, write to the Free Software Foundation,
   19    * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   20    *
   21    * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
   22    * or visit www.oracle.com if you need additional information or have any
   23    * questions.
   24    */
   25  
   26   package java.lang;
   27  
   28   /**
   29    * Thrown when an application attempts to use {@code null} in a
   30    * case where an object is required. These include:
   31    * <ul>
   32    * <li>Calling the instance method of a {@code null} object.
   33    * <li>Accessing or modifying the field of a {@code null} object.
   34    * <li>Taking the length of {@code null} as if it were an array.
   35    * <li>Accessing or modifying the slots of {@code null} as if it
   36    *     were an array.
   37    * <li>Throwing {@code null} as if it were a {@code Throwable}
   38    *     value.
   39    * </ul>
   40    * <p>
   41    * Applications should throw instances of this class to indicate
   42    * other illegal uses of the {@code null} object.
   43    *
   44    * {@code NullPointerException} objects may be constructed by the
   45    * virtual machine as if {@linkplain Throwable#Throwable(String,
   46    * Throwable, boolean, boolean) suppression were disabled and/or the
   47    * stack trace was not writable}.
   48    *
   49    * @author  unascribed
   50    * @since   JDK1.0
   51    */
   52   public
   53   class NullPointerException extends RuntimeException {
   54       private static final long serialVersionUID = 5162710183389028792L;
   55  
   56       /**
   57        * Constructs a {@code NullPointerException} with no detail message.
   58        */
   59       public NullPointerException() {
   60           super();
   61       }
   62  
   63       /**
   64        * Constructs a {@code NullPointerException} with the specified
   65        * detail message.
   66        *
   67        * @param   s   the detail message.
   68        */
   69       public NullPointerException(String s) {
   70           super(s);
   71       }
   72   }



  • you could fine Same thing when you click on NullPointerException from any IDE like Eclipse or netbeans 


Thanks 

Map class field to map

 import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; public class AutogeneratedClassMapper {     public static M...