Wednesday, February 23, 2011

Web MVC framework-Controllers

Controllers in Web MVC framework, interpret user inputs and transform such input in to a view that is to be viewed by the user. Spring has implemented several controllers in a very abstractive way. They are form-specific controllers, command-based controllers and controllers that execute wizard-style logic. Spring's basic for the controllers is the org.springframework.web.servlet.mvc.Controller  interface.

public interface Controller {
    ModelAndView handleRequest(
        HttpServletRequest request,
        HttpServletResponse response) throws Exception;
}

handleRequest method is responsible for handling a request and returning an appropriate modelandview.

AbstractController - Spring controllers inherit the AbstractController to get a basic infrastructure. Then we have to override the method handleRequestInternal(HttpServletRequest, HttpServletResponse). Here is an example.

public class MyController extends AbstractController {

    public ModelAndView handleRequestInternal(
        HttpServletRequest request,
        HttpServletResponse response) throws Exception {

        ModelAndView mav = new ModelAndView("hello");
        mav.addObject("message", "Hello World!");
        return mav;       
    }
}

ParameterizableViewController - This is same as the AbstractController except we can specify the view name that it will return in the web application context.

UrlFilenameViewController - This checks the URL and retrieves the file name of the file request and uses that as the view name.

MultiActionController - This allows the aggregation of multiple request handling methods to one controller.

Command Controllers

Command controllers allow to interact with data objects and dynamically bind the parameters from the HttpServletRequest to the data object specified.

AbstractCommandController - This is a command controller that is capable of binding request parameters to a data object. This controller does not provide form functionality.

AbstractFormController - Provides the form submission support.

SimpleFormController - A form controller that provides even more support when creating a form with a corresponding command object.

Tuesday, February 1, 2011

Data binding in Spring MVC

Property editors can be used to bind String to various data types in Spring MVC. Here, enum, int and Date bindings are described.

  • Enum Type

EnumEditor:

import java.beans.PropertyEditorSupport;

@SuppressWarnings("unchecked")
public class EnumEditor extends PropertyEditorSupport {
 private Class clazz;

 public EnumEditor(Class clazz) {
  this.clazz = clazz;
 };

 public String getAsText() {
  return (getValue() == null ? "" : ((Enum) getValue()).name());
 }

 public void setAsText(String text) throws IllegalArgumentException {
  setValue(Enum.valueOf(clazz, text));
 }

EnumClass:

public enum EnumClass{
    RED, GREEN, BLUE
}

Register in controller:

@InitBinder
 public void initBinder(WebDataBinder binder) {
 
  binder.registerCustomEditor(EnumClass.class,
    new EnumEditor(EnumClass.class));
 }

  • Int Type
IntEditor:

import java.beans.PropertyEditorSupport;
@SuppressWarnings("unchecked")
public class IntEditor extends PropertyEditorSupport {

    private Class clazz;

       public IntEditor(Class clazz) {
           this.clazz = clazz;
       }

    public String getAsText() {
        Integer value = (Integer) getValue();
        if (value.intValue() == 0) {
            return "";
        } else {
            return value.toString();
        }
    }

    public void setAsText(String value) {
        if (value != null && value.length() > 0) {
            setValue(Integer.parseInt(value));
        } else {
            setValue(0);
        }
    }

Register in controller:

@InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(int.class, new IntEditor(int.class));
    }

  • Date Type
DateEditor:

@SuppressWarnings("rawtypes")
public class DateEditor extends PropertyEditorSupport {
    private Class clazz;

    public DateEditor(Class clazz) {
        this.clazz = clazz;
    }

    public void setAsText(String value) {
        try {
          setValue(new SimpleDateFormat("yyyy-MM-dd").parse(value));
           
        } catch (ParseException e) {
            setValue(null);
        }
    }

    public String getAsText() {
        return new SimpleDateFormat("yyyy-MM-dd hh:mm a").format((Date) getValue());
    }

    public void setClazz(Class clazz) {
        this.clazz = clazz;
    }

    public Class getClazz() {
        return clazz;
    }
}

Register in controller:

@InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, new DateEditor(Date.class));
       
    }

Tuesday, January 11, 2011

VI Editor in Brief

Introduction

    * Screen-based editor
    * Case sensitive
    * Two modes
          o Command mode- perform administrative tasks such as saving files, executing commands, moving the cursor, cutting (yanking) and pasting lines or words, and finding and replacing.
          o Insert mode- insert text into the file

Starting the vi Editor

vi filename- creates a new file or open an existing file

vi -R filename- opens an existing file in read only mode

view filename- opens an existing file in read only mode


Inserting text

vi always opens in command mode.

i- insert text before the current cursor location

Esc – back into command mode.

I - Inserts text at the beginning of current line

a - Inserts text after current cursor location

A - Inserts text at the end of current line

o - Creates a new line for text entry below cursor location

O - Creates a new line for text entry above cursor location


Getting out of vi

:q -quit without saving

:wq / ZZ- quite while saving

:w- save the file

:w filename2- save the file by another name

:q!- enforce to quit without saving


Moving cursor in command mode

k – up one line

j - down one line

h - to the left one character one position

l- to the right one character one position

0/| -beginning of line

$ - end of line

:x – to the line number x


Deleting characters

x -Deletes the character under the cursor location

X - Deletes the character before the cursor location

dd- Deletes the line the cursor is on

2dd-Deletes 2 lines

D - Deletes from the cursor position to the end of the current line


Change commands

cc - Removes contents of the line, leaving you in insert mode

r - Replaces the character under the cursor. vi returns to command mode after the replacement is entered

s - Replaces the current character with the character you type. Afterward, you are left in insert mode


Copy and Paste Commands

yy- Copies the current line

p- Puts the copied text after the cursor

P- Puts the yanked text before the cursor



Advanced Commands

J - Join the current line with the next one. A count joins that many lines

<< - Shifts the current line to the left by one shift width

>> - Shifts the current line to the right by one shift width

~ - Switch the case of the character under the cursor

^G - Press CNTRL and G keys at the same time to show the current filename and the status

U- Restore the current line to the state it was in before the cursor entered the line

u - Undo the last change to the file. Typing 'u' again will re-do the change

:f filename - Renames current file to filename


Searching word and character

/ ? - search the strings

t/ T -search for characters in the current line only


Set commands

:set nu - Displays lines with line numbers on the left side

:set ic - Ignores case when searching

:set ai - Sets autoindent

:set ro - Changes file type to "read only"


Text Buffers in VI

36 buffers for storing pieces of text, a general purpose buffer

“mdd -delete the current line and paste to buffer m

”mp – paste from the buffer m to the current position


Abbreviations

:ab st string- use st as an abbreviation instead of string

:una st – to remove the abbreviation


Running Commands

:! ls - if you want to check whether a file exists before you try to save your file to that filename
Press any key to return to the vi session

 

Recovering Your Work When Something Goes Wrong with Your Terminal

The VI editor edits a temporary copy of your file

After the editing is complete, or when you tell it to save, it puts the contents of the temporary copy into the original file.

If something goes wrong while you are editing your file, the VI editor will attempt to save whatever work you had in progress, and store it for later recovery.

vi -r newfile – recovering the newfile and we must save it.

Thursday, January 6, 2011

JUnit

JUnit is a framework to implement testing in JAVA. We can start testing with few steps using JUnit. First we have to download the latest version of JUnit, extract the zip to a directory and add path to CLASSPATH environment variable. Here I describe basic steps to implement testing with JUnit.

1. Import junit.framework subdirectory.

import junit.framework.*;

2. Extend TestCase to your simple java class to provide the ability to define our test methods.

public class MyClass extends TestCase {

3. Implement the constructor with a string argument that passes the name to super constructor as below. Every test have a name. By implementing this constructor, we can view which test gives an error from overall test results. 

public MyClass(String name) {
   super(name);


4. Define our own test method. This method is a simple test method to check whether mytest variable equals to 2.

public void testMyClassMethod(){
    int mytest=1;
    assertEquals("Mytest must be 1", mytest,1);
}