Wednesday, May 25, 2011

Spring Vs Struts

Differences between Struts and Springs


Springs:
·         Dependency Injection
·         Inversion of Control
·         Transaction Management
·         Aspect Oriented Programming
·         DB Connection Control
·         Model View Controller (this is small part that is somehow comparable with Struts)
·         Spring Web flow (define control flows).
·         Spring is made up of many components, main component being the core container (Beans, BeanFactory, Application Context, etc) that provide the Dependency injection via a lightweight container, and the rest of the components (e.g. AOP, Transaction Management, etc.) are built around it.

Apache Struts is an open-source web application framework for developing Java EE web applications. It uses and extends the Java Servlet API to encourage developers to adopt a model-view-controller (MVC) architecture.
Spring is much more than Struts. Web MVC is just a small subset of the capabilities that Spring provides.
Struts is one of the first web MVC frameworks based on servlets and JSPs
Spring is a Java EE application framework based on Inversion of Control (IoC) and aspect-oriented programming (AOP).
Spring has a web MVC module that's analogous to Struts.  Spring can also use Struts as its web MVC module.
Struts are basically a request based framework while spring is a component based framework. All the benefits of struts can be achieved through spring (Spring MVC). Spring has many modules which helps you develop enterprise application with different components like ORM, AOP, MVC, and Transaction management etc., With Spring 3.0 it has an inbuilt support for restful services too. Also spring portfolio has other project which seamlessly integrates with spring like spring security (Acegi security), osgi, spring web services and all. Over all spring offers more benefits than struts in developing a quality applications by enforcing good design and decoupled components




12 BENEFITS of Spring MVC over Struts

Spring is a powerful Java application framework, used in a wide range of Java applications. It provides enterprise services to Plain Old Java Objects (POJOs). Spring uses dependency injection to achieve simplification and increase testability.

1. Spring provides a very clean division between controllers, JavaBeans models, and views.

2. Spring’s MVC is very flexible. Unlike Struts, which forces your Action and Form objects into concrete inheritance (thus taking away your single shot at concrete inheritance in Java), Spring MVC is entirely based on interfaces. Furthermore, just about every part of the Spring MVC framework is configurable via plugging in your own interface. Of course we also provide convenience classes as an implementation option.

3. Spring, like WebWork, provides interceptors as well as controllers, making it easy to factor out behavior common to the handling of many requests.

4. Spring MVC is truly view-agnostic. You don’t get pushed to use JSP if you don’t want to; you can use Velocity, XLST or other view technologies. If you want to use a custom view mechanism 

– for example, your own templating language – you can easily implement the Spring View interface to integrate it.

5. Spring Controllers are configured via IoC like any other objects. This makes them easy to test, and beautifully integrated with other objects managed by Spring.

6. Spring MVC web tiers are typically easier to test than Struts web tiers, due to the avoidance of forced concrete inheritance and explicit dependence of controllers on the dispatcher servlet.

7. The web tier becomes a thin layer on top of a business object layer. This encourages good practice. Struts and other dedicated web frameworks leave you on your own in implementing your business objects; Spring provides an integrated framework for all tiers of your application.

8. No ActionForms. Bind directly to domain objects

9. More testable code (validation has no dependency on Servlet API)

10. Struts imposes dependencies on your Controllers (they must extend a Struts class), Spring doesn’t force you to do this although there are convenience Controller implementations that you can choose to extend.

11. Spring has a well defined interface to business layer

12. Spring offers better integration with view technologies other than JSP (Velocity / XSLT / Free Marker / XL etc.)

Tuesday, May 10, 2011

Collection FrameWork in Java


Concrete Collections
--------------------

Concrete Collection     Implements  description

HashSet       Set                     Hashtable
TreeSet        SortedSet           Balance binary Tree
ArrayList      List                    Re-sizable array
LinkedList    List                    LinkedList
Vector          List                    re-sizable array
HashMap     Map                   hashtable
TreeMap      SortedMap        balance binary tree
HashTable    Map                  hashtable



/**
 *
 */
package com.jit;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Vector;

/**
 * @author Vinay Guntaka
 * Factors of Collection Framework to be considered
 * API
 * Synchronization
 * Data growth
 * Usage patterns
 */
public class CollectionFrameWork {

    public static void main(String[] args) {
        getHashSet();
        getTreeSet();
        getArrayList();
        getLinkedList();
        getVectorList();
        getHashMap();
        getHashTable();
        getTreeMap();
       
    }
   
    /*
     * Unordered (A HashSet use the hash function to store the values)
     * No Duplicates
     * Allow Null
     */
   
    public static void getHashSet()
    {
        Set<String> hs = new HashSet<String>();
        hs.add("Vinay");
        hs.add("Vinay");
        hs.add("Kumar");
        hs.add("Guntaka");
        hs.add(null);
        System.out.println(hs);
    }
    /*  A TreeSet is more efficient in case of search element.
     *  null throws NullPointerException
     *  By Default Sorted
     *  No Duplicates
     */
    public static void getTreeSet()
    {
        Set<String> ts = new TreeSet<String>();
        ts.add("Vinay");
        ts.add("Vinay");
        ts.add("Kumar");
        ts.add("Guntaka");
        ts.add("");
        System.out.println(ts);
       
    }
   
    /**
     * If you need to support random access, without inserting or removing
     * elements from any place other than the end, then ArrayList offers the optimal collection.
       * If, however, you need to frequently add and remove elements from the middle of the list and
     * only access the list elements sequentially, then LinkedList offers the better implementation.
     *
     */
   
    /*
     * Ordered
     * Allows Null
     * Allows Duplicates
     * Iterating from To-And-Fro Directions
     * Not Synchronized
     */
   
    public static void getArrayList(){
        List<String> al= new ArrayList<String>();
        al.add("Vinay");
        al.add(null);
        al.add("Vinay");
        al.add("Guntaka");
        System.out.println(al);
        // Iterating from Back Side
        ListIterator<String> lsitr = al.listIterator(al.size());
        while(lsitr.hasPrevious()){
            System.out.println(lsitr.previous());
        }
        // Iterating from front Side
        while(lsitr.hasNext()){
            System.out.println(lsitr.next());
        }
        al.subList(0, 2).clear();
        System.out.println(al);
    }
    /**
     * In a LinkedList, each element is linked to its previous and next element making
     * it easier to delete or insert in the middle of the list
     */
   
    public static void getLinkedList(){
        List<String> ll= new LinkedList<String>();
        ll.add("Vinay");
        ll.add(null);
        ll.add("Vinay");
        ll.add("Guntaka");
        System.out.println(ll);
       
    }
   
    /*
     * Synchronized
     */
    public static void getVectorList(){
        Vector<String> v = new Vector<String>();
        v.add("Vinay");
        v.add("Kumar");
        v.add(null);
        v.add("Guntaka");
        v.add("Guntaka");
        System.out.println(v);
       
    }
    /*
     * Key Name should be Unique
     * Unidentified Order
     * UnSynchronized
     * The values can be null.
     */
   
    public static void getHashMap(){
        Map<String,String> hm = new HashMap<String, String>();
        hm.put("FName", "Vinay");
        hm.put("MName", "Kumar");
        hm.put("LName", "Guntaka");
        hm.put("MName", null);
        System.out.println(hm);
    }
    /*
     * Key Name should be Unique
     * Does not let you have null value for key.
     * Synchronized
     */
    public static void getHashTable(){
        Map<String,Integer> ht = new Hashtable<String, Integer>();
        ht.put("FName", 100);
        ht.put("MName", 99);
        ht.put("LName", 101);
        ht.put("Name", 152);
        System.out.println(ht);
    }
    /*
     * The values can be null. But the key should be unique
     * UnSynchronized
     */
    public static void getTreeMap(){
        Map<String,Integer> tm = new TreeMap<String, Integer>();
        tm.put("FName", 100);
        tm.put("MName", 99);
        tm.put("LName", 101);
        tm.put("Name", null);
        System.out.println(tm);
    }

}

Saturday, May 7, 2011

Google Maps on Android Mobile / Simulator


Loading the Google Maps on Android Mobile / Simulator

Follow the following link to generate the map key

http://code.google.com/android/add-ons/google-apis/mapkey.html


Command to load the debug.keystore

C:\Java\jre\bin>keytool.exe -list -alias androiddebugkey -keystore "C:\Documents and Settings\jit\.android\debug.keystore" -storepass android -keypass android

on Enter you will get a privateKeyEntry with Certficate FingerPrint (MD5)


Once the MD5 finger print is generated

Registering the Certificate Fingerprint with the Google Maps Service
http://code.google.com/android/maps-api-signup.html

Note: Make sure the simluator is set to Google 2.X API


Program to Load Google MAP on Android


--------------------------------------
main.xml
--------------------------------------

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<com.google.android.maps.MapView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/webview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:clickable="true"
        android:enabled="true"
        android:apiKey="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    />
</LinearLayout>

----------------------------------------
AndroidManifest.xml
----------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.jit"
      android:versionCode="1"
      android:versionName="1.0">


    <application android:icon="@drawable/icon" android:label="@string/app_name">
     <uses-library android:name="com.google.android.maps" />
        <activity android:name=".GMap"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
   
 <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
 
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS"></uses-permission>

</manifest>

------------------------------------------------
GMAP.Java
-------------------------------------------------

package com.jit;
/*
 * @author: Vinay Guntaka
 */
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;

public class GMap extends com.google.android.maps.MapActivity{
    MapController mMapController;
    MapView mMapView;
    GeoPoint p;
 
   
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mMapView = (MapView) findViewById(R.id.webview);
        mMapView.setBuiltInZoomControls(true);
     
        mMapView.setSatellite(true);
     
        mMapController = mMapView.getController();
        mMapController.setZoom(15);
        //mMapView.setSatellite(true);
        mMapView.setStreetView(true);
        String coordinates[] = {"1.352566007", "103.78921587"};
        double lat = Double.parseDouble(coordinates[0]);
        double lng = Double.parseDouble(coordinates[1]);

        p = new GeoPoint(
            (int) (lat * 1E6),
            (int) (lng * 1E6));

        mMapController.animateTo(p);
        mMapController.setZoom(17);
        mMapView.invalidate();


       /* MyOverlays myOverlays = new MyOverlays(this.getResources().getDrawable(R.drawable.icon), this);
     
        OverlayItem tempOverlayItem = new OverlayItem(new GeoPoint(17000000,78000000), "NewActivity", "Welcome to New Activity");
        tempOverlayItem.setMarker(this.getResources().getDrawable(R.drawable.icon));
     
        myOverlays.addOverlay(tempOverlayItem);
     
        mMapView.getOverlays().add(myOverlays);*/
     
     

    }
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        Toast.makeText(this, "Ooops! I am touched", Toast.LENGTH_LONG).show();
        return super.onTouchEvent(event);
    }

    @Override
    protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;
    }
 
}

------------------------------------------

Ajax Programming setup instructions


Ajax Programming :

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
  <TITLE> New Document </TITLE>
  <META NAME="Generator" CONTENT="EditPlus">
  <META NAME="Author" CONTENT="">
  <META NAME="Keywords" CONTENT="">
  <META NAME="Description" CONTENT="">
 </HEAD>
<script type="text/javascript" language="javascript">
  // function to create an XMLHttpClient in a cross-browser manner
  function getAJAXRequest() {
      var xmlhttp=null;;  
      try {
          // Mozilla / Safari / IE7
          xmlhttp = new XMLHttpRequest();
      } catch (e) {
           // IE
           var XMLHTTP_IDS = new Array('MSXML2.XMLHTTP.5.0',
                                     'MSXML2.XMLHTTP.4.0',
                                     'MSXML2.XMLHTTP.3.0',
                                     'MSXML2.XMLHTTP',
                                     'Microsoft.XMLHTTP' );
          var success = false;
          for (var i=0;i < XMLHTTP_IDS.length && !success; i++) {
              try {
                   xmlhttp = new ActiveXObject(XMLHTTP_IDS[i]);
                   success = true;
                   break;
                } catch (e) {}
          }
          if (!success) {
              return null;
          }
     }
     return xmlhttp;
 }

 function loadAjaxCall(){
   
    var http_request=getAJAXRequest();
    //open(method,url,async)    
    //Specifies the type of request, the URL, and if the request should be handled asynchronously or not.
    //method: the type of request: GET or POST
    //url: the location of the file on the server
    //async: true (asynchronous) or false (synchronous)

    var parameters="one="+FristVal+"&sec="+SecVal;

    //Note: When you use async=false, do NOT write an onreadystatechange function - just put the code after the send() statement:
    //Note: When using async=true, specify a function to execute when the response is ready in the onreadystatechange event:

    http_request.open('POST', "/projectName/SomeAction.do", false);
    http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http_request.setRequestHeader("Content-length", parameters.length);
    http_request.setRequestHeader("Connection", "close");
    http_request.send(parameters);
   
    // here the state is synch
    // getting the response as responseText or responseXML
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

    /*
     * Suppose if Asynch we are have to set the readyState
        // here the response is in ready state
         xmlhttp.onreadystatechange=function()
             {
                 if (xmlhttp.readyState==4 && xmlhttp.status==200)
                    {
                         document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
                     }
            }
     *
     */
// onreadystatechange     Stores a function (or the name of a function) to be called automatically each time the readyState property changes
//readyState :-
//Holds the status of the XMLHttpRequest. Changes from 0 to 4:

//0: request not initialized
//1: server connection established
//2: request received
//3: processing request
//4: request finished and response is ready

//status:-
//200: "OK"
//404: Page not found

 }

</script>

 <BODY>
   
 </BODY>
</HTML>

Captcha Programming

Captcha Programming in Java



package com.jit;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Vinay Guntaka
 * Servlet implementation class CaptchaServlet
 */
public class CaptchaServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
     
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CaptchaServlet() {
        super();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        createCatcha(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        createCatcha(request, response);
    }
    @SuppressWarnings("unchecked")
    protected void createCatcha(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {

        response.setContentType("image/jpg");

         try {
            Color textColor = Color.white;
            Font textFont = new Font("Georgia", Font.PLAIN, 18);
            int charsToPrint = 6;
            int width = 125;
            int height = 28;
            float horizMargin = 20.0f;
            float imageQuality = 0.95f; // max is 1.0 (this is for jpeg)
            double rotationRange = 0.7; // this is radians
            BufferedImage bufferedImage = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);

            Graphics2D g = (Graphics2D) bufferedImage.getGraphics();

            // Draw an oval
            g.setColor(new Color(255, 153, 0));
            g.fillRect(0, 0, width, height);
            g.setColor(textColor);
            g.setFont(textFont);

            FontMetrics fontMetrics = g.getFontMetrics();
            int maxAdvance = fontMetrics.getMaxAdvance();
            int fontHeight = fontMetrics.getHeight();

            // i removed 1 and l and i because there are confusing to users...
            // Z, z, and N also get confusing when rotated
            // 0, O, and o are also confusing...
            // lowercase G looks a lot like a 9 so i killed it
            // this should ideally be done for every language...
            // i like controlling the characters though because it helps prevent
            // confusion
            String elegibleChars = "ABCDEFGHJKLMPQRSTUVWXYabcdefhjkmnpqrstuvwxy23456789";
            char[] chars = elegibleChars.toCharArray();

            float spaceForLetters = -horizMargin * 2 + width;
            float spacePerChar = spaceForLetters / (charsToPrint - 1.0f);
            StringBuffer finalString = new StringBuffer();

            for (int i = 0; i < charsToPrint; i++) {
                double randomValue = Math.random();
                int randomIndex = (int) Math.round(randomValue*(chars.length - 1));
                char characterToShow = chars[randomIndex];
                finalString.append(characterToShow);
                int charWidth = fontMetrics.charWidth(characterToShow);
                int charDim = Math.max(maxAdvance, fontHeight);
                int halfCharDim = (int) (charDim / 2);

                BufferedImage charImage = new BufferedImage(charDim, charDim,BufferedImage.TYPE_INT_ARGB);
                Graphics2D charGraphics = charImage.createGraphics();
                charGraphics.translate(halfCharDim, halfCharDim);
                double angle = (Math.random() - 0.5) * rotationRange;
                charGraphics.transform(AffineTransform.getRotateInstance(angle));
                charGraphics.translate(-halfCharDim, -halfCharDim);
                charGraphics.setColor(textColor);
                charGraphics.setFont(textFont);

                int charX = (int) (0.5 * charDim - 0.5 * charWidth);
                charGraphics.drawString("" + characterToShow,charX,
                                (int) ((charDim - fontMetrics.getAscent()) / 2 + fontMetrics
                                        .getAscent()));

                float x = horizMargin + spacePerChar * (i) - charDim / 2.0f;
                int y = (int) ((height - charDim) / 2);
                g.drawImage(charImage, (int) x, y, charDim, charDim,null, null);

                charGraphics.dispose();
            }

            // Write the image as a jpg
            Iterator iter = ImageIO.getImageWritersByFormatName("JPG");
            if (iter.hasNext()) {
                ImageWriter writer = (ImageWriter) iter.next();
                ImageWriteParam iwp = writer.getDefaultWriteParam();
                iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                iwp.setCompressionQuality(imageQuality);
                writer.setOutput(ImageIO.createImageOutputStream(response.getOutputStream()));
                IIOImage imageIO = new IIOImage(bufferedImage, null, null);
                writer.write(null, imageIO, iwp);
            } else {
                throw new RuntimeException("no encoder found for jsp");
            }

            // let's stick the final string in the session
            request.getSession().setAttribute("captcha", finalString.toString());
            g.dispose();

        } catch (IOException ioe) {
            throw new RuntimeException("Unable to build image", ioe);
        }

    }

}

----------------------------------
Captcha.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Captcha</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<center>
<form method="post">
<table cellspacing="15">
<tr>
<td>Are you human?</td>
<td><input type="text" name="code"></td>
</tr>

</table>

<br>
<img src="CaptchaServlet">

<br><br>
<input type="submit" value="submit">

</form>
<br><br>
<%
  String captcha = (String) session.getAttribute("captcha");
  String code = (String) request.getParameter("code");

  if (captcha != null && code != null) {

      System.out.println("Captcha Code:"+captcha);
      System.out.println("Code:"+code);

    if (captcha.equals(code)) {
      out.print("<p class='alert'>Correct</p>");
    } else {
          out.print("<p class='alert'>Incorrect</p>");
    }
  }
%>
</center>
</body>
</html>

--------------------------------
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>Captcha</display-name>
  <welcome-file-list>
    <welcome-file>captcha.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>CaptchaServlet</display-name>
    <servlet-name>CaptchaServlet</servlet-name>
    <servlet-class>com.jit.CaptchaServlet</servlet-class>;
  </servlet>
  <servlet-mapping>
    <servlet-name>CaptchaServlet</servlet-name>
    <url-pattern>/CaptchaServlet</url-pattern>
  </servlet-mapping>
</web-app>