yama quick start english version

49
Yama Quick Start Guide CHAPTER I Yama TOOLS created by Meruvian Education (Eng.version) 1

Upload: meruvian

Post on 24-May-2015

358 views

Category:

Technology


4 download

TRANSCRIPT

Page 1: Yama quick start english version

Yama Quick Start Guide

CHAPTER I

Yama TOOLS

created by Meruvian Education (Eng.version) 1

Page 2: Yama quick start english version

The Purpose

1. Know and understand the tools are needed to run Yama project such as Eclipse IDE,

M2Eclipse, Subclipse, MySQL Query Browser

Learning Material

1.1 Eclipse IDE

Eclipse is an IDE (Integrated Development Software) to develop the software and can

run on all platform (platform independent). The following is characters of Eclipse :

• Multi Platform

Supports development and execution on all the major desktop platforms (Windows,

Mac OS X, Linux, QNX Photon, Pocket PC, HP-UX, AIX, Solaris)

• Multi Language

Eclipse written mostly in Java and can be used to develop applications in Java, but

Eclipse also support with various programming language like C/C++, Cobol, Phyton,

Perl and PHP

• Multi Role

Besides as an IDE for application development, Eclipse can be used for activities in the

software development cycle such as documentation, test software, and web

development

Eclipse is one of the favorite IDE due to free and open source. It means that anyone

can view the programming code of this software. Besides, the advantages that make it

populer is the ability to be developed by users with component named plugin. Kinds of plugin

that available in Eclipse :

created by Meruvian Education (Eng.version) 2

Page 3: Yama quick start english version

– Subversion

– m2eclipse

– Glassfish Integration

– Jboss Tools

– STS (SpringSource Tool Suite)

– EGIT (Git Eclipse Plugin)

– Mercurial Eclipse (Mercurial Eclipse Plugin)

– Windows Builder

1.2 m2eclipse

m2eclipse is a plugin that used if we use Maven as the project management. Maven is

a build tool like Ant but more complex and bigger than Ant. Maven is very good if we build

software that is done by several people

1.3 Subclipse

Subclipse is a plugin that is used for Eclipse integration and Subversion Client.

Subversion (SVN) is an opensource software that useful as version control. Basically, there

are two important parts of SVN. They are SVN Client and SVN Repository. SVN Client is a

software used to access user repository. SVN Repository is a server which contain datas on

the management. Any changes to the data recorded by the SVN repository.

Using this SVN the data in the repository can be copied to the client so that users can

process local data that often called the "Checkout". Then the data at the local when

processed, can be sent back to the repository for version control, and accessible to our

colleagues that usually called "Commit"

created by Meruvian Education (Eng.version) 3

Page 4: Yama quick start english version

1.4 MySQL Query Browser

A database is a collection of information that is organized so that it can easily be

accessed, managed, and updated. The MySQL Query Browser is a graphical tool provided by

MySQL AB for creating, executing, and optimizing queries in a graphical environment. Where

the http://www.mysql.com/products/administrator/ is designed to administer a MySQL server,

the MySQL Query Browser is designed to help you query and analyze data stored within your

MySQL database

created by Meruvian Education (Eng.version) 4

Page 5: Yama quick start english version

Yama Quick Start Guide

CHAPTER II

TOOLS INSTALLATION

created by Meruvian Education (Eng.version) 5

Page 6: Yama quick start english version

The Purpose

1. Know and understand how to install the tools are needed to run Yama project such as

how to install Eclipse Indigo 3.7, m2eclipse, Subclipse

2. Know and understand how to make a database on MySQL Query Browser

Learning Material

2.1 Eclipse Indigo 3.7 Installation

Eclipse Indigo 3.7 is the latest version that just release last June 2011. Follow the

instruction below to install Eclipse Indigo :

2.1.1 Download Eclipse Indigo from http://www.eclipse.org/downloads/, choose

Eclipse Indigo for Linux 32 bit

created by Meruvian Education (Eng.version) 6

Page 7: Yama quick start english version

2.1.2 Download that link at Eclipse downloads – mirror selection

2.1.3 Save file in any directory

2.1.4 If the downloaded file is complete, extract the file and run the Eclipse by double

clicking on the Eclipse icon

created by Meruvian Education (Eng.version) 7

Page 8: Yama quick start english version

2.1.5 Eclipse Indigo will appear and select where you put Eclipse metadata by double

clicking the button Browse

created by Meruvian Education (Eng.version) 8

Page 9: Yama quick start english version

2.1.6 Eclipse Indigo ready to use

created by Meruvian Education (Eng.version) 9

Page 10: Yama quick start english version

2.2 M2Eclipse Installation

If previous Cimande we use Ant as the Build Tool, but in Cimande 2.0 we use Maven.

To run this Maven, the Eclipse must be intalled m2eclipse plugin. Follow the instruction below

to install m2eclipse :

2.2.1 To add the m2eclipse update site to the Eclipse site list, choose the menu item

Help → Install New Software

created by Meruvian Education (Eng.version) 10

Page 11: Yama quick start english version

2.2.2 Click Available Sotware Sites link

2.2.3 Click the Add button to display the Add Site dialog

created by Meruvian Education (Eng.version) 11

Page 12: Yama quick start english version

2.2.4 Insert the Name field with m2e updates , insert the Location field with the URL

http://download.eclipse.org/technology/m2e/releases , and then click OK, so the new

update site will be added to the list

2.2.5 Check Maven Integration for Eclipse (you can click the disclosure triangle to

see what exactly is included in this feature), then click Next

created by Meruvian Education (Eng.version) 12

Page 13: Yama quick start english version

2.2.6 View the Install Details, then click Next

2.2.7 Accept the Lisence Agreement and click on the Finish button to download and

install m2eclipse

2.2.8 Restart Eclipse

created by Meruvian Education (Eng.version) 13

Page 14: Yama quick start english version

2.3 Subclipse Installation

Subclipse installation is needed when we want to check out or commit code to SVN.

Follow the instruction below to install subclipse :

2.3.1 To add the Subclipse update site to the Eclipse site list, choose the menu item

Help → Install New Software

2.3.2 Click Available Software Site link

created by Meruvian Education (Eng.version) 14

Page 15: Yama quick start english version

2.3.3 Click the Add button to display the Add Site dialog

2.3.4 Insert the Field Name with subclipse, insert the Field Location with the URL for

subclipse update site http://subclipse.tigris.org/update_1.6.x, and then click OK, so the

new update site will be added to the list

2.3.5 Check Subclipse (you can click the disclosure triangle to see what exactly is

included in this feature), then click Next

created by Meruvian Education (Eng.version) 15

Page 16: Yama quick start english version

2.3.6 View Install Details, then click Next

created by Meruvian Education (Eng.version) 16

Page 17: Yama quick start english version

2.3.7 Accept Lisence Agreement and click on the Finish button to download and

install subclispe

2.3.8 Restart Eclipse

created by Meruvian Education (Eng.version) 17

Page 18: Yama quick start english version

2.4 Creating Database

There are several ways to create MySQL database. We can use the command line,

PHP MyAdmin, or use MySQL Query Browser. If we use command line, you must memorize

the syntax to makeaa database. The Syntax is quite simple, CREATE DATABASE

database_name and ends with a semicolon. If you want to use MySQL Query Browser, follow

the instruction how to install and make a database below :

2.5.1 Select System → Administration → Synaptic Package → Manager

2.5.2 Install and download MySQL Query Browser

created by Meruvian Education (Eng.version) 18

Page 19: Yama quick start english version

2.5.3 To start creating a database, select Application → Programming → MySQL

Query Browser

created by Meruvian Education (Eng.version) 19

Page 20: Yama quick start english version

2.5.4 Default username : root, password : tulalit

2.5.5 Create database by right click → create schema

created by Meruvian Education (Eng.version) 20

Page 21: Yama quick start english version

Yama Quick Start Guide

CHAPTER III

YAMA CRUD

created by Meruvian Education (Eng.version) 21

Page 22: Yama quick start english version

The Purpose

1. Know and understand Yama overview

2. Know and understand the function using Maven as a Build Tool

3. Know and understand how to create Yama project

4. Know and understand Yama CRUD implementation

Learning Material

3.1 Yama Overview

Yama is a solution category of the various popular frameworks integration. Yama

integration made from SpringMVC that use Hibernate as the ORM (Objeck Relational

Mapping) solution and Velocity as the View. The framework components integrated to be

application integration that have high technology value

3.2 Creating Maven Project

The Build tool that we use to run Yama is Maven. Maven is a build tool like Ant Builder

but more complex. Follow the instruction below to create Maven project :

3.2.1 Open Eclipse Indigo, then change the choice of Java EE to Java

created by Meruvian Education (Eng.version) 22

Page 23: Yama quick start english version

3.2.2 Select File → New → Other → Maven → Project to create Maven project

3.2.3 Put the Yama project that you will create in any directory, for example in

home/netoya/yama2 by clicking Browse → Next

created by Meruvian Education (Eng.version) 23

Page 24: Yama quick start english version

3.2.4 At the field Catalog choose All Catalogs then click button Add Archetype and fill

them → Archetype Group Id : org.meruvian.yama

Archetype Artifact Id : yama-archetype

Archetype Version : 1.0-Beta1

Repository URL : https://maven.java.net/content/groups/staging

3.2.5 Create a project package by filling Group Id and Artifact Id. Group Id to fill the

package name and the Artifact Id to fill the project name. For example :

Group Id : org.meruvian

Artifact Id : yama

created by Meruvian Education (Eng.version) 24

Page 25: Yama quick start english version

There are two ways to generate Maven Archetype,using Eclipse or using Console.

If using Console, open Console then go to the directory where you put the

Cimande project and type the code below

  mvn archetype:generate 

  ­DarchetypeGroupId=org.meruvian.yama 

  ­DarchetypeArtifactId=yama­archetype

  ­DarchetypeVersion=1.0­Beta1 

  ­DarchetypeRepository=https://maven.java.net/content/groups/staging 

  ­DgroupId=org.mycompany 

  ­DartifactId=myproject

GroupId to give a package name (e.g : org.meruvian) and ArtifactId to give a

project name (e.g : yama)

created by Meruvian Education (Eng.version) 25

Page 26: Yama quick start english version

3.2.6 We need database configuration in the package src/main/resources →

applicationContext.html , then customize the database with the name of the database

that you create and customize the password with your MySQL password

3.3 Creating Package

After creating Maven project and import them into Eclipse at the previous chapter, now

we need to create packages as a place where we put the Java class. Create seven packages

in the package org.meruvian. They are entity, form, dao, service, controller, validator, wrapper

3.3.1 Package org.meruvian.yama.entity

This package contains the entity class that used as a link between framework with

the database. Creating table and all the variables that will be displayed in the

database declared here

created by Meruvian Education (Eng.version) 26

Page 27: Yama quick start english version

3.3.2 Package org.meruvian.yama.form

This package contain class PersonForm.java that used as a container for all the

getter and setter methods from variable that declared in Entity class

3.3.3 Package org.meruvian.yama.dao

Data Access Object (DAO) is an object that provides an abstract interface to a

database or persistence mechanisms and certain operations without showing

details of the database. The Implementation of this concept called separation of

concern, where each code is separated by the function so the code on it only

needs to know abstractly how to access data without knowing how access to data

sources are implemented

3.3.4 Package org.meruvian.yama.service

Service is an object that used to simplify the large code like a library. In the case

of a database we can use the Service to classify some of the DAO in a

transaction

3.3.5 Package org.meruvian.yama.controller

Controller is a layer that works to set the "inter-layer" . This Layer is responsible

for application execution

3.3.6 Package org.meruvian.yama.validator

This package contain class PersonValidator.java that used to validate the data

that must be filled or can not be empty

3.3.7 Package org.meruvian.yama.wrapper

Inside this package there is @XmlRootElement that used to map class into XML

element

created by Meruvian Education (Eng.version) 27

Page 28: Yama quick start english version

3.4 Creating Java Class

3.4.1 Create class Person.java in the package org.blueoxygen.entity

package org.meruvian.yama.entity;

import java.io.Serializable;import java.util.Date;

import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.Table;import javax.xml.bind.annotation.XmlRootElement;

import org.hibernate.annotations.GenericGenerator;

/** * @author vick *  */

@Entity@Table@XmlRootElement(name = "person")

created by Meruvian Education (Eng.version) 28

Page 29: Yama quick start english version

public class Person implements Serializable {

private static final long serialVersionUID = 203559588950186907L;

@Id@GeneratedValue(generator = "p")@GenericGenerator(name = "p", strategy = "uuid")@Columnprivate String id;

@Columnprivate String firstName;

@Columnprivate String lastName;

@Columnprivate Boolean gender;

@Columnprivate Date birthDate;

@Columnprivate String address;

public String getId() {return id;

}

public void setId(String id) {this.id = id;

}

public String getFirstName() {return firstName;

}

public void setFirstName(String firstName) {this.firstName = firstName;

}

public String getLastName() {return lastName;

}

public void setLastName(String lastName) {this.lastName = lastName;

}

public Boolean getGender() {return gender;

}

public void setGender(Boolean gender) {this.gender = gender;

}

public Date getBirthDate() {return birthDate;

}

public void setBirthDate(Date birthDate) {this.birthDate = birthDate;

}

created by Meruvian Education (Eng.version) 29

Page 30: Yama quick start english version

public String getAddress() {return address;

}

public void setAddress(String address) {this.address = address;

}}

3.4.2 Create class PersonForm.java in the package org.meruvian.yama.form

package org.meruvian.yama.form;

import java.util.Date;

import org.meruvian.yama.entity.Person;

/** *  * @author vick */public class PersonForm {

public Person person = new Person();

public PersonForm() {

}

public PersonForm(Person person) {this   .  person    = person;

}

public void setPerson(Person person) {this   .  person    = person;

}

public Person getPerson() {return person;

}

public void setId(String id) {person.setId(id);

}

public String getId() {return person.getId();

}

public void setFirstName(String firstName) {person.setFirstName(firstName);

}

public String getFirstName() {return person.getFirstName();

}

public void setLastName(String lastName) {person.setLastName(lastName);

}

public String getLastName() {return person.getLastName();

}

created by Meruvian Education (Eng.version) 30

Page 31: Yama quick start english version

public void setGender(Boolean gender) {person.setGender(gender);

}

public Boolean getGender() {return person.getGender();

}

public void setBirthDate(Date birthDate) {person.setBirthDate(birthDate);

}

public Date getBirthDate() {return person.getBirthDate();

}

public void setAddress(String address) {person.setAddress(address);

}

public String getAddress() {return person.getAddress();

}}

3.4.3 Create class PersonDao.java in the package org.meruvian.yama.dao

package org.meruvian.yama.dao;

import java.util.List;import org.meruvian.yama.dao.base.BaseDaoHibernate;import org.meruvian.yama.entity.Person;import org.springframework.stereotype.Repository;

/**** @author vick*/@Repositorypublic class PersonDao extends BaseDaoHibernate<Person>{

@SuppressWarnings("unchecked")    public List<Person> listParent(String personId){        return sessionFactory.getCurrentSession().createQuery("from "+domainClass.getName()+" where id != '"+personId+"' and relation_id != '"+personId+"' or relation_id = null ").list();    }

@SuppressWarnings("unchecked")    public List<Person> listChild(String personId, String parentId){        return sessionFactory.getCurrentSession().createQuery("from "+domainClass.getName()+" where id != '"+personId+"' ").list();    }

@SuppressWarnings("unchecked")    public List<Person> listPerson(boolean sex){        return sessionFactory.getCurrentSession().createQuery("from "+domainClass.getName()+" where relation_id = null and gender != "+sex+" ").list();    }

@SuppressWarnings("unchecked")    public List<Person> findPerson(String firstName){        return sessionFactory.getCurrentSession().createQuery("from "+domainClass.getName()+" where 

created by Meruvian Education (Eng.version) 31

Page 32: Yama quick start english version

firstName like '%"+firstName+"%' ").list();    }

@SuppressWarnings("unchecked")    public List<Person> getParentC(String id){        return sessionFactory.getCurrentSession().createQuery("from "+domainClass.getName()+" where id = '"+id+"'").list();    }

@SuppressWarnings("unchecked")    public List<Person> getChildP(String personId, String relationId){

return sessionFactory.getCurrentSession().createQuery("from "+domainClass.getName()+" where parent_id = '"+personId+"' or parent_id = '"+relationId+"' ").list();

}}

3.4.4 Create class BaseDaoHibernate.java in the package

org.meruvian.yama.dao.base

package org.meruvian.yama.dao.base;

import java.lang.reflect.ParameterizedType;import java.util.List;import javax.persistence.PersistenceException;import org.hibernate.ObjectDeletedException;import org.hibernate.SessionFactory;import org.springframework.beans.factory.annotation.Autowired;

/** * * @author vick */public class BaseDaoHibernate<T> {

    @SuppressWarnings("unchecked")    protected Class domainClass;        @Autowired protected SessionFactory sessionFactory;        @SuppressWarnings("unchecked")    public BaseDaoHibernate(){        this.domainClass = (Class) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];    }

    @SuppressWarnings("unchecked")    public T findById(String id){        if(id.equalsIgnoreCase("")) return null;        final T domain = (T) sessionFactory.getCurrentSession().get(domainClass, id);        return domain;    }

    public T save(T domain){        sessionFactory.getCurrentSession().saveOrUpdate(domain);        return domain;    }

    public void delete(T domain){        sessionFactory.getCurrentSession().delete(domain);    }

    @SuppressWarnings("unchecked")

created by Meruvian Education (Eng.version) 32

Page 33: Yama quick start english version

    public List<T> findAll(Integer startIndex, Integer pageSize){        return sessionFactory.getCurrentSession().createQuery("from "+domainClass.getName()).setFirstResult(startIndex).setMaxResults(pageSize).list();    }

    @SuppressWarnings("unchecked")    public List<T> findAll(){        return sessionFactory.getCurrentSession().createQuery("from "+domainClass.getName()).list();    }    }

3.4.5 Create class PersonService.java in the package org.meruvian.yama.service

package org.meruvian.yama.service;

import java.util.List;import org.meruvian.yama.entity.Person;

/**** @author vick*/public interface PersonService {

    void save(Person person);    void delete(Person person);    Person getPerson(String id);    List<Person> getPersons();    List<Person> getPersons(int start, int num);    List<Person> listParents(String personId);    List<Person> listChilds(String personId, String parentId);    List<Person> listPersons(boolean sex);        Person getRelation(String id);    Person getParent(String id);    List<Person> getRelations();    List<Person> getParents(String id);    List<Person> getChilds(String personId, String relationId);    List<Person> findPersons(String firstName);}

3.4.6 Create class PersonServiceImpl.java in the package

org.meruvian.yama.service.impl

package org.meruvian.yama.service.impl;

import java.util.List;import org.meruvian.yama.dao.PersonDao;import org.meruvian.yama.entity.Person;import org.meruvian.yama.service.PersonService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;

/**** @author vick*/

created by Meruvian Education (Eng.version) 33

Page 34: Yama quick start english version

@Service("personService")@Transactional(readOnly = true)public class PersonServiceImpl implements PersonService {

@Autowired private PersonDao personDao;

@Transactional    public void save(Person person) {        personDao.save(person);    }

    @Transactional    public void delete(Person person) {        personDao.delete(person);    }        public Person getPerson(String id){        return personDao.findById(id);    }

    public List<Person> getPersons(){        return personDao.findAll();    }

    public List<Person> getPersons(int start, int num){        return personDao.findAll(start, num);    }        public Person getRelation(String id){        return personDao.findById(id);    }        public Person getParent(String id){        return personDao.findById(id);    }

    public List<Person> getRelations(){        return personDao.findAll();    }        public List<Person> getParents(String id){        return personDao.getParentC(id);    }        public List<Person> getChilds(String personId, String relationId){        return personDao.getChildP(personId, relationId);    }        public List<Person> listParents(String personId){        return personDao.listParent(personId);    }        public List<Person> listChilds(String personId, String parentId){        return personDao.listChild(personId, parentId);    }        public List<Person> listPersons(boolean sex){        return personDao.listPerson(sex);    }        public List<Person> findPersons(String fristName){        return personDao.findPerson(fristName);    } }

created by Meruvian Education (Eng.version) 34

Page 35: Yama quick start english version

3.4.7 Create class PersonController.java in the package org.meruvian.yama.controller

package org.meruvian.yama.controller;

import java.text.SimpleDateFormat;import java.util.List;

import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;

import org.meruvian.yama.entity.Person;import org.meruvian.yama.form.PersonForm;import org.meruvian.yama.service.PersonService;import org.meruvian.yama.validator.PersonValidator;import org.meruvian.yama.wrapper.PersonListWrapper;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.validation.BindingResult;import org.springframework.web.bind.annotation.ModelAttribute;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.servlet.ModelAndView;import org.springframework.web.servlet.view.RedirectView;

/** *  * @author vick */

@Controllerpublic class PersonController {

@Autowiredprivate PersonService personService;

@RequestMapping(value = "/person", method = RequestMethod.GET)public ModelAndView person(HttpServletRequest request,

HttpServletResponse response) throws Exception {ModelAndView mv = new ModelAndView();System.out.println("Person OI");mv.addObject("person", new Person());mv.setViewName("person/person­add");return mv;

}

@RequestMapping(value = "/person", method = RequestMethod.POST)public ModelAndView person(HttpServletRequest request,

HttpServletResponse response,@ModelAttribute("person") PersonForm person,BindingResult bindingResult) {

new PersonValidator().validate(person, bindingResult);System.out.println("­­­­­­­­­­­­­­­­­­­­" + person.getBirthDate());if (bindingResult.hasErrors()) {

ModelAndView mv = new ModelAndView();mv.addObject("person", person);mv.setViewName("person/person­add");return mv;

} else {personService.save(person.getPerson());return new ModelAndView(new RedirectView(request.getContextPath()

+ "/person"));

created by Meruvian Education (Eng.version) 35

Page 36: Yama quick start english version

}}

@RequestMapping(value = "person/listPerson/{sex}", method = RequestMethod.GET)public ModelAndView personList(HttpServletRequest request,

HttpServletResponse response, @RequestParam("sex") boolean sex)throws Exception {

List<Person> persons = personService.listPersons(sex);ModelAndView mv = new ModelAndView("person/person­list");mv.addObject("list", persons);return mv;

}

@RequestMapping(value = "/person/search", method = RequestMethod.GET)public ModelAndView search(HttpServletRequest request,

HttpServletResponse response) throws Exception {ModelAndView mv = new ModelAndView();mv.setViewName("person/person­search");return mv;

}

@RequestMapping(value = "/person/result", method = RequestMethod.POST)public ModelAndView builder(@RequestParam("firstName") String firstName) {

StringBuilder builder = new StringBuilder();builder.append("result");if (!firstName.equalsIgnoreCase("")) {

builder.append("/" + firstName);}ModelAndView mv = new ModelAndView(new RedirectView(builder.toString()));return mv;

}

@RequestMapping(value = "/person/result/{firstName}", method = RequestMethod.GET)public ModelAndView result(@PathVariable("firstName") String firstName) {

ModelAndView mv = new ModelAndView();PersonListWrapper persons = new PersonListWrapper();persons.setPersons(personService.findPersons(firstName));mv.addObject("list", persons);mv.setViewName("person/person­result");return mv;

}

@RequestMapping(value = "/person/result", method = RequestMethod.GET)public ModelAndView result(HttpServletRequest request,

HttpServletResponse response) throws Exception {PersonListWrapper persons = new PersonListWrapper();persons.setPersons(personService.getPersons());ModelAndView mv = new ModelAndView("person/person­result");mv.addObject("list", persons);return mv;

}

@RequestMapping(value = "/person/{id}/detail", method = RequestMethod.GET)public ModelAndView detailPerson(@PathVariable("id") String personId) {

Person person = personService.getPerson(personId);ModelAndView mv = new ModelAndView();mv.setViewName("person/person­detail");return mv;

}

@RequestMapping(value = "/person/{id}/edit", method = RequestMethod.GET)public ModelAndView updatePerson(@PathVariable("id") String personId) {

Person person = personService.getPerson(personId);SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");ModelAndView mv = new ModelAndView();mv.setViewName("person/person­edit");

created by Meruvian Education (Eng.version) 36

Page 37: Yama quick start english version

mv.addObject("person", person);return mv;

}

@RequestMapping(value = "/person/{id}/edit", method = RequestMethod.POST)public ModelAndView updatePerson(HttpServletRequest request,

@ModelAttribute("person") PersonForm person,BindingResult bindingResult) {

new PersonValidator().validate(person, bindingResult);if (bindingResult.hasErrors()) {

ModelAndView mv = new ModelAndView();mv.addObject("person", person);mv.setViewName("person/person­edit");return mv;

} else {personService.save(person.getPerson());return new ModelAndView(new RedirectView(request.getContextPath()

+ "/person/result"));}

}

@RequestMapping(value = "/person/{id}/delete", method = RequestMethod.GET)public ModelAndView deletePerson(HttpServletRequest request,

@PathVariable("id") String personId) {Person person = personService.getPerson(personId);personService.delete(person);return new ModelAndView(new RedirectView(request.getContextPath()

+ "/person/result"));}

}

3.4.8 Create class Index.java in the package org.meruvian.yama.controller

package org.meruvian.yama.controller;

import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.servlet.ModelAndView;import org.springframework.web.servlet.view.RedirectView;

/** * @author vick * */@Controllerpublic class Index {

@RequestMapping(value="/",method=RequestMethod.GET)public ModelAndView index(HttpServletRequest request, HttpServletResponse response) {    return new ModelAndView(new RedirectView(request.getContextPath()+"/person"));}

}

3.4.9 Create class PersonValidator.java in the package org.meruvian.yama.validator

package org.meruvian.yama.validator;

import org.meruvian.yama.form.PersonForm;

created by Meruvian Education (Eng.version) 37

Page 38: Yama quick start english version

import org.springframework.validation.Errors;import org.springframework.validation.ValidationUtils;import org.springframework.validation.Validator;

/**** @author vick*/public class PersonValidator implements Validator{

public boolean supports(Class<?> clazz){        return PersonForm.class.equals(clazz);    }

public void validate(Object val, Errors errors){        ValidationUtils.rejectIfEmpty(errors, "firstName", "firstName.empty");        ValidationUtils.rejectIfEmpty(errors, "lastName", "lastName.empty");        ValidationUtils.rejectIfEmpty(errors, "gender", "gender.empty");    }

}

3.4.10 Create class PersonListWrapper.java in the package org.meruvian.yama.wrapper

package org.meruvian.yama.wrapper;

import java.util.List;

import javax.xml.bind.annotation.XmlRootElement;

import org.meruvian.yama.entity.Person;

/** * @author vick * */

@XmlRootElement(name = "personListWrapper")public class PersonListWrapper {

private List<Person> persons;

public List<Person> getPersons() {return persons;

}

public void setPersons(List<Person> persons) {this.persons = persons;

}}

3.5 Creating View

Creating code for the View that stored in the package /src/main/webapp/WEB-

INF/velocity/person

created by Meruvian Education (Eng.version) 38

Page 39: Yama quick start english version

3.5.1 Create view person-add.xhtml

<?xml version="1.0" encoding="UTF­8"?><!DOCTYPE html PUBLIC "­//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1­strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head>    <link rel="stylesheet" type="text/css" media="all" href="jscalendar­1.0/calendar­win2k­cold­1.css" title="win2k­cold­1" /><script type="text/javascript" src="jscalendar­1.0/calendar.js"></script><script type="text/javascript" src="jscalendar­1.0/lang/calendar­en.js"></script><script type="text/javascript" src="jscalendar­1.0/calendar­setup.js"></script>     <meta http­equiv="Content­Type" content="text/html;charset=UTF­8" />    <title>Person Add</title>    </head>    <body>        <form id="person" action="" method="post">                              <table border="0" cellpadding="5" cellspacing="0" align="center" width="40%">                 <tr>                 <td colspan="3"><a href="person/search">Search</a></td>                </tr>                         </table>                         <table border="1" cellpadding="5" cellspacing="0" align="center" width="40%">                      <tr bgcolor="#d0dcff">                    <td colspan="3">                        <strong>PERSON ADD</strong>                    </td>                </tr>                                                <tr bgcolor="#ffffff">                    <td align="right">First Name</td>                    <td align="center">:</td>                    <td colspan="2"><input type="text" size="25" name="firstName" id="firstName" value="$!person.firstName" tabindex="1" maxlength="20"/>                     #springBind("person.firstName")                     <font color="red" >#springShowErrors("<br/>" "")</font>                    </td>                </tr>                                <tr bgcolor="#ffffff">                    <td align="right">Last Name</td>                    <td align="center">:</td>                    <td colspan="2"><input type="text" size="25" name="lastName" id="lastName" value="$!person.lastName" tabindex="2" maxlength="20"/>                     #springBind("person.lastName")                     <font color="red" >#springShowErrors("<br/>" "")</font>                    </td>                </tr>                                <tr bgcolor="#ffffff">                    <td align="right">Sex</td>                    <td align="center">:</td>                    <td colspan="2">                     <input type="radio" id="gender" name="gender" value="true">Male</input>                     <input type="radio" id="gender" name="gender" value="false">Female</input>                     #springBind("person.gender")                     <font color="red" >#springShowErrors("<br/>" "")</font>                    </td>                </tr>                                <tr bgcolor="#ffffff">

created by Meruvian Education (Eng.version) 39

Page 40: Yama quick start english version

<td align="right">Birth Date</td><td align="center">:</td><td><input type="text" size="25" name="birthDate" value="$!

person.birthDate" size="20" id="f_date_b" readonly="1"/><img src="jscalendar­1.0/img.gif" id="f_trigger_b" style="cursor: 

pointer; border: 1px solid red;" title="Date selector" onmouseover="this.style.background='red';" onmouseout="this.style.background=''" /></td>

</tr>                

<tr bgcolor="#ffffff">                    <td align="right">Address</td>                    <td align="center">:</td>                    <td colspan="2">                     <textarea rows="3" cols="25" name="address" id="address">$!person.address</textarea>                     #springBind("person.address")                     <font color="red" >#springShowErrors("<br/>" "")</font>                    </td>                </tr>                                <tr bgcolor="#e4e4e4">                    <td colspan="3">                        <input type="submit" value="Submit"/>                        <input type="reset" tabindex="21"/>                    </td>                </tr>            </table>        </form>                <p>&nbsp;</p>        <script type="text/javascript">    Calendar.setup({        inputField     :    "f_date_b",      // id of the input field        ifFormat       :    "%d/%m/%Y",       // format of the input field        showsTime      :    true,            // will display a time selector        button         :    "f_trigger_b",   // trigger for the calendar (button ID)        singleClick    :    false,           // double­click mode        step           :    1                // show all years in drop­down boxes (instead of every other year as default)    });</script>

</body></html>

3.5.2 Create view person-list.xhtml

<?xml version="1.0" encoding="windows­1252"?>

<!DOCTYPE html PUBLIC "­//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1­strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml">    <head>        <meta http­equiv="Content­Type" content="text/html; charset=windows­1252"/>        <title>Person List</title>    </head>    <body>        <h3>PERSON LIST</h3>        #if ($person.isEmpty()) No person        #else

        <table width=100% border="0" cellpadding="5">            <tr>

created by Meruvian Education (Eng.version) 40

Page 41: Yama quick start english version

                <td width=60%>None</td>                <td><input type="button" onClick="javascript:window.opener.document.getElementById('relation').value='';window.opener.document.getElementById('personRelation').value='None';window.close();" value="Set"/></td>            </tr>                        #foreach ($i in $list)            <tr>                <td width=60%>$i.firstName</td>                <td><input type="button" onClick="javascript:window.opener.document.getElementById('relation').value='$i.id';window.opener.document.getElementById('personRelation').value='$i.firstName';window.close();" value="Set"/></td>            </tr>            #end        </table>        #end    </body></html>

3.5.3 Create view person-search.xhtml

<?xml version="1.0" encoding="UTF­8"?><!DOCTYPE html PUBLIC "­//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1­strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http­equiv="Content­Type" content="text/html;charset=UTF­8" /><title>Person Search</title><!­­script type="text/javascript">            function search() {                var input = document.getElementsByName("firstName").value='';            }        </script­­></head><body><form id="search" action="result" method="post"><table border="1" cellpadding="3" cellspacing="0" align="center">

<tr bgcolor="#d0dcff"><td colspan="2"><strong>PERSON SEARCH</strong></td>

</tr>

<tr bgcolor="#ffffff"><td>First Name</td><td><input type="text" size="25" name="firstName" tabindex="1" maxlength="20"  /></td>

</tr><tr bgcolor="#e4e4e4">

<td colspan="2"><input type="submit" value="Search" tabindex="20" /></td>

</tr></table></form></body></html>

3.5.4 Create view person-result.xhtml

<!DOCTYPE html PUBLIC "­//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1­strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">    <head>        <meta http­equiv="Content­Type" content="text/html; charset=UTF­8"/>

created by Meruvian Education (Eng.version) 41

Page 42: Yama quick start english version

        <title>View Person Data</title>    </head>    <body>        <table bgcolor="#000000" border="0" cellpadding="3" cellspacing="1" width="98%">     <tr bgcolor="#d0dcff">         <td colspan="7">             <strong>PERSON RESULT</strong>         </td>      </tr>           <tr bgcolor="#e4e4e4" align="center">         <td><strong>First Name</strong></td>         <td><strong>Last Name</strong></td>         <td><strong>Sex</strong></td>         <td><strong>Birth Date</strong></td>         <td><strong>Address</strong></td>         <td><strong>Action</strong></td>     </tr>         #foreach($p in $list.persons)     <tr bgcolor="#ffffff"  align="center" onmouseover="javascript:this.style.background='#d0dcff';" onmouseout="javascript:this.style.background='#ffffff';">         <td>$!p.firstName</td>         <td>$!p.lastName</td>         <td>

         #if($!p.gender == "true" )         Male         #else         Female         #end

            </td>         <td>$!p.birthDate</td>         <td>$!p.address</td>         <td>

            <a href="/yama/person/$!p.id/detail">                <img src="/yama/images/silk/application_view_detail.png" title="Detail" 

border="0"/></a>&nbsp;&nbsp;&nbsp;         <a href="/yama/person/$!p.id/edit">                <img src="/yama/images/silk/application_edit.png" title="Edit" 

border="0"/></a>&nbsp;&nbsp;&nbsp;            <a href="/yama/person/$!p.id/delete" onclick="javascript:return 

confirm('Are you sure want to delete $!p.firstName');">                <img src="/yama/images/silk/delete.png" title="Delete" 

border="0"/></a>&nbsp;&nbsp;&nbsp;       </td>     </tr>    #end        </table>    </body>    <script type="javascript">

function hl(){this.style.bgcolor='#d0dcff';

}</script>

</html>

3.5.5 Create view person-detail.xhtml

<?xml version="1.0" encoding="UTF­8"?>

<!DOCTYPE html PUBLIC "­//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1­strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml">

created by Meruvian Education (Eng.version) 42

Page 43: Yama quick start english version

<head><meta http­equiv="Content­Type" content="text/html; charset=UTF­8" /><title>Detail Person Data</title></head><body> <table border="0" cellpadding="5" cellspacing="0" align="center" width="50%">  

<tr><td bgcolor="#ffffff" colspan="3"><a href="../result">Person List</a></td>

</tr></table> <table border="1" cellpadding="5" cellspacing="0" align="center" width="50%">  

<tr bgcolor="#d0dcff"><td colspan="3"><strong>PERSON DETAIL</strong></td>

</tr>

<tr><td bgcolor="#ffffff" align="right">First Name</td><td bgcolor="#ffffff" align="center">:</td><td bgcolor="#ffffff">$person.firstName</td>

</tr>

<tr><td bgcolor="#ffffff" align="right">Last Name</td><td bgcolor="#ffffff" align="center">:</td><td bgcolor="#ffffff">$person.lastName</td>

</tr>

<tr><td bgcolor="#ffffff" align="right">Sex</td><td bgcolor="#ffffff" align="center">:</td><td bgcolor="#ffffff">#if($person.gender == true) Male #elseFemale #end</td>

</tr>

<tr><td bgcolor="#ffffff" align="right">Birth Date</td><td bgcolor="#ffffff" align="center">:</td><td bgcolor="#ffffff">$!person.birthDate</td>

</tr>

<tr><td bgcolor="#ffffff" align="right">Address</td><td bgcolor="#ffffff" align="center">:</td><td bgcolor="#ffffff">$person.address</td>

</tr></table></body></html>

3.5.6 Buat view person-edit.xhtml

<?xml version="1.0" encoding="UTF­8"?><!DOCTYPE html PUBLIC "­//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1­strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head>

<link rel="stylesheet" type="text/css" media="all"href="../../jscalendar­1.0/calendar­win2k­cold­1.css"title="win2k­cold­1" />

<script type="text/javascript" src="../../jscalendar­1.0/calendar.js"></script><script type="text/javascript"

src="../../jscalendar­1.0/lang/calendar­en.js"></script><script type="text/javascript"

created by Meruvian Education (Eng.version) 43

Page 44: Yama quick start english version

src="../../jscalendar­1.0/calendar­setup.js"></script><meta http­equiv="Content­Type" content="text/html;charset=UTF­8" /><title>Person Edit</title></head><body><form id="person" action="" method="post">

  <table border="1" cellpadding="5" cellspacing="0" align="center" width="40%">                               <tr bgcolor="#d0dcff">                    <td colspan="3">                        <strong>PERSON EDIT</strong>                    </td>                </tr>                                                <tr bgcolor="#ffffff">                    <td align="right">First Name</td>                    <td align="center">:</td>                    <td colspan="2"><input type="text" size="25" name="firstName" id="firstName" value="$!person.firstName" tabindex="1" maxlength="20"/>                     #springBind("person.firstName")                     <font color="red" >#springShowErrors("<br/>" "")</font>                    </td>                </tr>                                <tr bgcolor="#ffffff">                    <td align="right">Last Name</td>                    <td align="center">:</td>                    <td colspan="2"><input type="text" size="25" name="lastName" id="lastName" value="$!person.lastName" tabindex="2" maxlength="20"/>                     #springBind("person.lastName")                     <font color="red" >#springShowErrors("<br/>" "")</font>                    </td>                </tr>                              <tr bgcolor="#ffffff">

<td align="right">Sex</td><td align="center">:</td><td colspan="2"><input type="radio" id="person.gender" 

name="person.gender" value="true" #  if  ($!   person.gender   ==true) checked #  end   >Male</input> <input type="radio"

id="person.gender" name="person.gender" value="false" #  if  ($!   person.gender== false   )   checked #  end   >Female</input>

#springBind("person.gender") <font color="red">#springShowErrors("<br />" "")</font></td>

</tr>

<tr bgcolor="#ffffff"><td align="right">BirthDate</td><td align="center">:</td>

           <td><input type="text" name="person.birthDate" value="$!person.birthDate" size="20" id="f_date_b" readonly="1" />                      <input type="hidden" id="df" value="$!person.birthDate" />

<img src="../../jscalendar­1.0/img.gif" id="f_trigger_b"style="cursor: pointer; border: 1px solid red;" title="Date selector" onmouseover="this.style.background='red';" onmouseout="this.style.background=''" /></td>

        </tr>                                <tr bgcolor="#ffffff">                    <td align="right">Address</td>                    <td align="center">:</td>                    <td colspan="2">                     <textarea rows="3" cols="25" name="address" id="address">$!person.address</textarea>                     #springBind("person.address")                     <font color="red" >#springShowErrors("<br/>" "")</font>

created by Meruvian Education (Eng.version) 44

Page 45: Yama quick start english version

                    </td>                </tr>                                <tr bgcolor="#e4e4e4">                    <td colspan="3">                        <input type="submit" value="Submit"/>                        <input type="reset" tabindex="21"/>                    </td>                </tr>            </table></form><p>&nbsp;</p>

<script type="text/javascript">    Calendar.setup({        inputField     :    "f_date_b",      // id of the input field        ifFormat       :    "%d/%m/%Y",       // format of the input field        showsTime      :    true,            // will display a time selector        button         :    "f_trigger_b",   // trigger for the calendar (button ID)        singleClick    :    false,           // double­click mode        step           :    1                // show all years in drop­down boxes (instead of every other year as default)    });</script></body></html>

3.6 Hibernate Mapping

Hibernate is a device for easier access into database. Hibernate handles the database

connection from Java application to the database server. Hibernate create an automatic table

in the database, so all the existing Entity must be incorporated into the Hibernate

configuration file (hibernate.cfg.xml).

Enter the Entity Person.java in the package src / main / resources / hibernate.cfg.xml

<?xml version="1.0" encoding="UTF­8"?><!DOCTYPE hibernate­configuration PUBLIC "­//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate­configuration­3.0.dtd"><hibernate­configuration>  <session­factory>    <property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>    <property name="hibernate.hbm2ddl.auto">update</property>    <property name="hibernate.search.default.directory_provider">org.hibernate.search.store.FSDirectoryProvider</property>

  <mapping class="org.meruvian.yama.entity.Person"/>

  </session­factory></hibernate­configuration>

created by Meruvian Education (Eng.version) 45

Page 46: Yama quick start english version

3.7 Running Yama Project

To run the Yama project and generate the database we use Maven build by right click

Yama project → Run As → Maven Build and use command tomcat:run to run the server

3.9 Yama CRUD

Open web browser then enter URL http://localhost:8080/yama/ to run Yama CRUD

3.9.1 CREATE

PERSON-ADD form contain input field to fill First Name, Last Name, Sex, Birth

Date and Address. First Name, Last Name dan Sex as the validation data

created by Meruvian Education (Eng.version) 46

Page 47: Yama quick start english version

created by Meruvian Education (Eng.version) 47

Page 48: Yama quick start english version

3.9.2 SEARCH

to search for data, click Search at the top ADD PERSON form

created by Meruvian Education (Eng.version) 48

Page 49: Yama quick start english version

3.9.3 DETAIL

There are three actions at the PERSON RESULT form. They are Detail, Update

and Delete.The picture below is the form that will launch when detail action clicked

3.9.4 UPDATE

3.9.5 DELETE

When the Delete icon is clicked, automatically the data will be deleted directly

created by Meruvian Education (Eng.version) 49