Yama Quick Start Guide                                      CHAPTER I                                    Yama TOOLScreated...
The Purpose  1.    Know and understand the tools are needed to run Yama project such as Eclipse IDE,        M2Eclipse, Sub...
– Subversion    – m2eclipse    – Glassfish Integration    – Jboss Tools    – STS (SpringSource Tool Suite)    – EGIT (Git ...
1.4 MySQL Query Browser       A database is a collection of information that is organized so that it can easily beaccessed...
Yama Quick Start Guide                                      CHAPTER II                     TOOLS INSTALLATIONcreated by Me...
The Purpose    1. Know and understand how to install the tools are needed to run Yama project such as        how to instal...
2.1.2 Download that link at Eclipse downloads – mirror selection        2.1.3 Save file in any directory        2.1.4 If t...
2.1.5 Eclipse Indigo will appear and select where you put Eclipse metadata by double        clicking the button Browsecrea...
2.1.6 Eclipse Indigo ready to usecreated by Meruvian Education (Eng.version)   9
2.2 M2Eclipse Installation        If previous Cimande we use Ant as the Build Tool, but in Cimande 2.0 we use Maven.To run...
2.2.2 Click Available Sotware Sites link        2.2.3 Click the Add button to display the Add Site dialogcreated by Meruvi...
2.2.4 Insert the Name field with m2e updates , insert the Location field with the URL        http://download.eclipse.org/t...
2.2.6 View the Install Details, then click Next        2.2.7 Accept the Lisence Agreement and click on the Finish button t...
2.3 Subclipse Installation       Subclipse installation is needed when we want to check out or commit code to SVN.Follow t...
2.3.3 Click the Add button to display the Add Site dialog        2.3.4 Insert the Field Name with subclipse, insert the Fi...
2.3.6 View Install Details, then click Nextcreated by Meruvian Education (Eng.version)           16
2.3.7 Accept Lisence Agreement and click on the Finish button to download and        install subclispe        2.3.8 Restar...
2.4 Creating Database       There are several ways to create MySQL database. We can use the command line,PHP MyAdmin, or u...
2.5.3     To start creating a database, select Application → Programming → MySQL      Query Browsercreated by Meruvian Edu...
2.5.4     Default username : root, password : tulalit      2.5.5     Create database by right click → create schemacreated...
Yama Quick Start Guide                                     CHAPTER III                                     YAMA CRUDcreate...
The Purpose   1. Know and understand Yama overview   2. Know and understand the function using Maven as a Build Tool   3. ...
3.2.2 Select File → New → Other → Maven → Project to create Maven project      3.2.3 Put the Yama project that you will cr...
3.2.4 At the field Catalog choose All Catalogs then click button Add Archetype and fill             them → Archetype Group...
There are two ways to generate Maven Archetype,using Eclipse or using Console.             If using Console, open Console ...
3.2.6 We need database configuration in the package src/main/resources →      applicationContext.html , then customize the...
3.3.2 Package org.meruvian.yama.form              This package contain class PersonForm.java that used as a container for ...
3.4 Creating Java Class      3.4.1 Create class Person.java in the package org.blueoxygen.entitypackage org.meruvian.yama....
public class Person implements Serializable {        private static final long serialVersionUID = 203559588950186907L;    ...
public String getAddress() {               return address;        }        public void setAddress(String address) {       ...
public void setGender(Boolean gender) {               person.setGender(gender);        }        public Boolean getGender()...
firstName like %"+firstName+"% ").list();    }       @SuppressWarnings("unchecked")    public List<Person> getParentC(Stri...
    public List<T> findAll(Integer startIndex, Integer pageSize){        return sessionFactory.getCurrentSession().createQ...
@Service("personService")@Transactional(readOnly = true)public class PersonServiceImpl implements PersonService {        @...
3.4.7 Create class PersonController.java in the package org.meruvian.yama.controllerpackage org.meruvian.yama.controller;i...
}        }        @RequestMapping(value = "person/listPerson/{sex}", method = RequestMethod.GET)        public ModelAndVie...
mv.addObject("person", person);                return mv;        }        @RequestMapping(value = "/person/{id}/edit", met...
import org.springframework.validation.Errors;import org.springframework.validation.ValidationUtils;import org.springframew...
3.5.1 Create view person-add.xhtml<?xml version="1.0" encoding="UTF­8"?><!DOCTYPE html PUBLIC "­//W3C//DTD XHTML 1.0 Stric...
<td align="right">Birth Date</td>                                     <td align="center">:</td>                           ...
                <td width=60%>None</td>                <td><input type="button" onClick="javascript:window.opener.document...
        <title>View Person Data</title>    </head>    <body>        <table bgcolor="#000000" border="0" cellpadding="3" ce...
<head><meta http­equiv="Content­Type" content="text/html; charset=UTF­8" /><title>Detail Person Data</title></head><body> ...
src="../../jscalendar­1.0/calendar­setup.js"></script><meta http­equiv="Content­Type" content="text/html;charset=UTF­8" />...
                    </td>                </tr>                                <tr bgcolor="#e4e4e4">                    <t...
3.7 Running Yama Project      To run the Yama project and generate the database we use Maven build by right clickYama proj...
created by Meruvian Education (Eng.version)   47
3.9.2 SEARCH             to search for data, click Search at the top ADD PERSON formcreated by Meruvian Education (Eng.ver...
3.9.3 DETAIL             There are three actions at the PERSON RESULT form. They are Detail, Update             and Delete...
Upcoming SlideShare
Loading in...5
×

Yama quick start english version

346

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
346
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
6
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Yama quick start english version

  1. 1. Yama Quick Start Guide CHAPTER I Yama TOOLScreated by Meruvian Education (Eng.version) 1
  2. 2. The Purpose 1. Know and understand the tools are needed to run Yama project such as Eclipse IDE, M2Eclipse, Subclipse, MySQL Query BrowserLearning Material1.1 Eclipse IDE Eclipse is an IDE (Integrated Development Software) to develop the software and canrun 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 anyonecan view the programming code of this software. Besides, the advantages that make itpopuler is the ability to be developed by users with component named plugin. Kinds of pluginthat available in Eclipse :created by Meruvian Education (Eng.version) 2
  3. 3. – Subversion – m2eclipse – Glassfish Integration – Jboss Tools – STS (SpringSource Tool Suite) – EGIT (Git Eclipse Plugin) – Mercurial Eclipse (Mercurial Eclipse Plugin) – Windows Builder1.2 m2eclipse m2eclipse is a plugin that used if we use Maven as the project management. Maven isa build tool like Ant but more complex and bigger than Ant. Maven is very good if we buildsoftware that is done by several people1.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, thereare two important parts of SVN. They are SVN Client and SVN Repository. SVN Client is asoftware used to access user repository. SVN Repository is a server which contain datas onthe 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 canprocess local data that often called the "Checkout". Then the data at the local whenprocessed, can be sent back to the repository for version control, and accessible to ourcolleagues that usually called "Commit"created by Meruvian Education (Eng.version) 3
  4. 4. 1.4 MySQL Query Browser A database is a collection of information that is organized so that it can easily beaccessed, managed, and updated. The MySQL Query Browser is a graphical tool provided byMySQL AB for creating, executing, and optimizing queries in a graphical environment. Wherethe 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 yourMySQL databasecreated by Meruvian Education (Eng.version) 4
  5. 5. Yama Quick Start Guide CHAPTER II TOOLS INSTALLATIONcreated by Meruvian Education (Eng.version) 5
  6. 6. 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 BrowserLearning Material2.1 Eclipse Indigo 3.7 Installation Eclipse Indigo 3.7 is the latest version that just release last June 2011. Follow theinstruction below to install Eclipse Indigo : 2.1.1 Download Eclipse Indigo from http://www.eclipse.org/downloads/, choose Eclipse Indigo for Linux 32 bitcreated by Meruvian Education (Eng.version) 6
  7. 7. 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 iconcreated by Meruvian Education (Eng.version) 7
  8. 8. 2.1.5 Eclipse Indigo will appear and select where you put Eclipse metadata by double clicking the button Browsecreated by Meruvian Education (Eng.version) 8
  9. 9. 2.1.6 Eclipse Indigo ready to usecreated by Meruvian Education (Eng.version) 9
  10. 10. 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 belowto install m2eclipse : 2.2.1 To add the m2eclipse update site to the Eclipse site list, choose the menu item Help → Install New Softwarecreated by Meruvian Education (Eng.version) 10
  11. 11. 2.2.2 Click Available Sotware Sites link 2.2.3 Click the Add button to display the Add Site dialogcreated by Meruvian Education (Eng.version) 11
  12. 12. 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 Nextcreated by Meruvian Education (Eng.version) 12
  13. 13. 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 Eclipsecreated by Meruvian Education (Eng.version) 13
  14. 14. 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 linkcreated by Meruvian Education (Eng.version) 14
  15. 15. 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 Nextcreated by Meruvian Education (Eng.version) 15
  16. 16. 2.3.6 View Install Details, then click Nextcreated by Meruvian Education (Eng.version) 16
  17. 17. 2.3.7 Accept Lisence Agreement and click on the Finish button to download and install subclispe 2.3.8 Restart Eclipsecreated by Meruvian Education (Eng.version) 17
  18. 18. 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 memorizethe syntax to makeaa database. The Syntax is quite simple, CREATE DATABASEdatabase_name and ends with a semicolon. If you want to use MySQL Query Browser, followthe 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 Browsercreated by Meruvian Education (Eng.version) 18
  19. 19. 2.5.3 To start creating a database, select Application → Programming → MySQL Query Browsercreated by Meruvian Education (Eng.version) 19
  20. 20. 2.5.4 Default username : root, password : tulalit 2.5.5 Create database by right click → create schemacreated by Meruvian Education (Eng.version) 20
  21. 21. Yama Quick Start Guide CHAPTER III YAMA CRUDcreated by Meruvian Education (Eng.version) 21
  22. 22. 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 implementationLearning Material3.1 Yama Overview Yama is a solution category of the various popular frameworks integration. Yamaintegration made from SpringMVC that use Hibernate as the ORM (Objeck RelationalMapping) solution and Velocity as the View. The framework components integrated to beapplication integration that have high technology value3.2 Creating Maven Project The Build tool that we use to run Yama is Maven. Maven is a build tool like Ant Builderbut more complex. Follow the instruction below to create Maven project : 3.2.1 Open Eclipse Indigo, then change the choice of Java EE to Javacreated by Meruvian Education (Eng.version) 22
  23. 23. 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 → Nextcreated by Meruvian Education (Eng.version) 23
  24. 24. 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 : yamacreated by Meruvian Education (Eng.version) 24
  25. 25. 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
  26. 26. 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 password3.3 Creating Package After creating Maven project and import them into Eclipse at the previous chapter, nowwe need to create packages as a place where we put the Java class. Create seven packagesin 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 herecreated by Meruvian Education (Eng.version) 26
  27. 27. 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 elementcreated by Meruvian Education (Eng.version) 27
  28. 28. 3.4 Creating Java Class 3.4.1 Create class Person.java in the package org.blueoxygen.entitypackage 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
  29. 29. public class Person implements Serializable { private static final long serialVersionUID = 203559588950186907L; @Id @GeneratedValue(generator = "p") @GenericGenerator(name = "p", strategy = "uuid") @Column private String id; @Column private String firstName; @Column private String lastName; @Column private Boolean gender; @Column private Date birthDate; @Column private 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
  30. 30. 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.formpackage 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
  31. 31. 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.daopackage 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
  32. 32. 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.basepackage 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
  33. 33.     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.servicepackage 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.implpackage 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
  34. 34. @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
  35. 35. 3.4.7 Create class PersonController.java in the package org.meruvian.yama.controllerpackage 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 { @Autowired private 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
  36. 36. } } @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
  37. 37. 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.controllerpackage 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.validatorpackage org.meruvian.yama.validator;import org.meruvian.yama.form.PersonForm;created by Meruvian Education (Eng.version) 37
  38. 38. 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.wrapperpackage 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/personcreated by Meruvian Education (Eng.version) 38
  39. 39. 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
  40. 40. <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
  41. 41.                 <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
  42. 42.         <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
  43. 43. <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 #else Female #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
  44. 44. 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 #   >Male</input> <input   endtype="radio" id="person.gender" name="person.gender" value="false" #  ($!  if   person.gender== false  checked #   >Female</input>    )  end #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
  45. 45.                     </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 databaseconnection from Java application to the database server. Hibernate create an automatic tablein the database, so all the existing Entity must be incorporated into the Hibernateconfiguration 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
  46. 46. 3.7 Running Yama Project To run the Yama project and generate the database we use Maven build by right clickYama project → Run As → Maven Build and use command tomcat:run to run the server3.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 datacreated by Meruvian Education (Eng.version) 46
  47. 47. created by Meruvian Education (Eng.version) 47
  48. 48. 3.9.2 SEARCH to search for data, click Search at the top ADD PERSON formcreated by Meruvian Education (Eng.version) 48
  49. 49. 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 directlycreated by Meruvian Education (Eng.version) 49

×