MyArchiBook

Archive for June 2013

Simple Form Handling and Performing Dependency Injection in Spring MVC Framework using NetBeans

with 6 comments

  I thought  working on Spring MVC Framework– to handle xml, configurations etc.,was a geeky kindaa job.  But I also recently learnt that , working on it using an IDE like NetBeans which provides the Spring MVC Template(pom.xml, MVC Configurations etc.,) and also the Maven build  has made me focus mainly on the design and coding part of my project , thus saving my time and leaving me unstrained .

Below I have created Simple Form Handling Application using Spring MVC Framwork(3.X).In this sample,I have also implemented Dependency Injection – annotation based .

IDE used:NetBeans 7.3

Build used:Maven 2.2

JspConsider 2 Jsp’s

Jsp 1  : MusicForm.jsp contains the text boxes to be entered.

Jsp 2 : Output.jsp conatins the TEXTS of,

  •          Object transferred from Jsp 1
  •          Object got through DEPENDENCY INJECTION

FLOW:

1.Bean : SongDetails Bean with setters and getters is created

2.Interface : IMusicService Interface is created. It has three unimplemented methods play(), pause(), stop();

3.Service Implementation class :MusicServiceImpl class that implements the above interface and its unimplemented methods is created.

@Service
public class MusicServiceImpl implements IMusicService{
@Override
 public String play() {
 return "Music is played on!!!";
 }

@Override
 public String pause() {
 return "Music has been PAUSED !";
 }

@Override
 public String stop() {
 return "Music Stopped";
 }
}

Note  that there is @Service annotation before the class name… Please have it in mind.Will tell you why, when it’s time of usage has come.

4. Jsp and Controller:

4.a) HomePage(MusicForm) Jsp and Controller :

MusicForm

Here in MusicForm.jsp, the details to be transferred is enclosed in a form.Form has the following attributes,

  • Method type – GET/POST is specified here.
  • commandName -Here we can specify name of the Object , that carries the SongDetails (above commandName is songDetForm )
  • action- Here OutCome jsp name, where the details are to be transferred is specified.

For the above Jsp , controller method has to be written.The flow goes like this,

  • ModelAndView object is created
  • ViewName is set
  • SongDetails Object is initialised and set as songDetForm (must be same as commandName in jsp).

4.b)Output jsp and Controller:

Output

Here in this Controller,

  • Output jsp name is given as the Request mapping value
  • Request method is POST as specified in First Jsp
  • View Name is set.
  • Then Two Objects are set—->1.songDetForm, 2.object got through dependency injection
  • To set songDetForm obj,
  1. Object is got from HomePageController method via @ModelAttribute(“songDetForm”)SongDetails songDetails. This means , object or attribute in the name “songDetForm” is assigned to songDetails object.
  2. This object is then added in a HashMap
  • To set Dependency injection object,
  1. IMusicService private instance is created .It is annotated with @Autowired.
  2. Apart from this, @Service annotation has to be specified on the ServiceImplementation class . This means, MusicServiceImpl class is at Service which can be injected ,when @Autowired annotation is used over its Interface instance.
  3.  In MVC Configuration, the package be scanned is specified and Component Scan is done.
  4. then dependencyObject is  added in the Controller method map.
  • Both these objects along with viewName are set in mv and mv is returned.

The controller sourcecode will look like,

@Controller
public class HomeController {

 @Autowired
 private IMusicService iMusicService;

 @RequestMapping(value="/")
 public ModelAndView homePage(){
 //Method 1:
 ModelAndView mv=new ModelAndView();
 mv.setViewName("MusicForm");
 mv.addObject("songDetForm",new SongDetails());
 return mv;

 //Method 2:                  viewName      Obj Key        Obj Value
 // return new ModelAndView("MusicForm","songDetForm",new SongDetails());
 }

 @RequestMapping(value ="/Output", method = RequestMethod.POST)
 public ModelAndView processSongDetails (@ModelAttribute("songDetForm") SongDetails songDetails){
 Map<String,Object> obj=new HashMap<String,Object>();
 obj.put("songDetails",songDetails);
 obj.put("iMusicService", iMusicService);
//                                            viewName  Obj
 ModelAndView modelAndView = new ModelAndView("Output", obj);
 return modelAndView;
 }
}
  • In the respective Output.jsp , the respective objects are got.

5. Clean the project.

6.Build it using Maven… The most advantageous part about Maven is , I needn’t have to strain myself to provide any dependency jars, specify its classpath etc.,  everytime. Maven took care of that part by itself, thus making my code-writing easy and simple.

7.Run it.

The output will be as follows…

WebPageResult

That’s it about Form Handling and Dependecy Injection in Spring MVC Framework.

You can find and download the above source code from this link.  https://github.com/AishwaryaThangavelu/Spring-Repository

Advertisements

Written by thangaveluaishwarya

June 22, 2013 at 3:49 AM

Hibernate Persistence Context and Object’s LifeCycle

with 4 comments

A Software Industry mainly works on Enterprise Applications. When Persistence Frameworks are being used in the application, then it is better to know about the Persistence Context and Object’s Life Cycle, inorder to deal with the complexities.

BASICS:

  • Object Oriented Programming(OOP)  plays a major central role for developing any application. It is a design concept. It can be imagined as a Collection Of  Interacting Objects.
  • Relational Database Management System helps to store these entity objects into the Database objects(tables).
  • Object Relational Mapping (ORM) relates  objects from Object Oriented domain with relational Data model via mapping.

JPA

    Java Persistence API(JPA exists in JEE5 and higher ) is a specification which  has the features that will make the ORM work.It deals with , how Java Objects(“persistent entites”)are stored in the relational database, how they can be accessed and how the object’s state can be stored so that it can be  restored when the appication is restarted .

Hibernate 3.2,EJB 3 ,TopLink and etc., are frameworks that implement this JPA.

In this post I have briefed on Hibernate’s Persistence Context Pattern and the Object’s LifeCycle.

HIBERNATE PERSISTENCE CONTEXT PATTERN AND OBJECT’S LIFE CYCLE:

  • HIBERNATE is a Simple Persistence Framework . It is a flexible framework even.Flexible, because  it can be used even with or without an application server.
  • Hibernate provides functionality that persists objects of an object-oriented programming environment into some persistent store. These persisted objects are called Persistent Objects.
  • The place where the persistent objects are created,modified and retrieved is called the Persistence Context.
  • The three most importantly used classes of Hibernate’s Persistence API are,
  1. org.hibernate.SessionFactory
  2. org.hibernate.Session
  3. org.hibernate.Transaction

object-life-cycle

  • SessionFactory has the contract to create session instances for the application.Usually one data source has a single session factory instance. In an application, the threads servicing client requests, obtain Session Instances from this factory.
  • Session is THE Hibernate’s Persistence Context.The lifetime of a session is bound between the beginning and the end of a transaction.As said earlier, the persistent objects are created,modified and retrieved only in this session. While carrying out these operations on the objects, they might exist in one of these three states,
  1. transient state
  2. persistent state
  3. detached state
  • Transaction defines the UNIT OF WORK for an application.It is instantiated when Session.beginTransaction() is called.

Let’s get into examples to understand the Object’s life cycle with respect to Persistence Context.Here I have considered an example related to Company and its Chairman.

Attributes: Company Name and Chairman..

CASE 1:

public class CompanyDao {
	public void enterCompanyDetails(){
		Session session=HibernateSessionManager.getInstance().getHibernateSession();
		Transaction transaction=session.beginTransaction();
		try{
			transaction.begin();
			CompanyDetails companyDetails=new CompanyDetails();
			companyDetails.setCompanyName("Apple");
			companyDetails.setCompanyChairman("Steve Jobs");
			session.save(companyDetails);
            EmployeeDetails employeeDetails=new EmployeeDetails();
            employeeDetails.setNoOfEmployees(100000);
            transaction.commit();
		}catch (HibernateException e) {
			transaction.rollback();
		}finally{
			session.close();
		}
	}
}

Logic:SAVE —> COMMIT

  • Line 8 and 9 – the company name and chairman are set to the CompanyDetails object. Now this object’s instance which is a new one exists in the transient State.
  • Line 10- the object’s instance is being saved, which means it is being persisted in the Persistence Context. Now it is in the persistent state.
  • Line 11- a new employeeInstance is created.
  • Line 12- attribute is set to the instance. The instance now exists in the transient state.
  • When the transaction is committed, only the objects in the Persistence Context gets persisted in the Database as a record.i.e.,Here the persistent object companyDetails gets persisted but employeeDetails does not get persisted because it is in transient state.

Check out if you can answer this question ,

Qn.When you  Insert a data and update the same data in a session , will a new memory object be created in the Persistence Context or will it get Updated in the existing object in the Persistence Context…???

Ans: No, a new object is not created in Persistence Context while updating. Instead , the persistent object created when saving the object in the persistence context gets updated.

The answer is explained with an example below,

CASE 2:

public class CompanyDao {
	public void enterCompanyDetails(){
		Session session=HibernateSessionManager.getInstance().getHibernateSession();
		Transaction transaction=session.beginTransaction();
		try{
			transaction.begin();
			CompanyDetails companyDetails=new CompanyDetails();
			companyDetails.setCompanyName("Infosys");
			companyDetails.setCompanyChairman("K.V.Kamath");
			session.save(companyDetails);
			companyDetails.setCompanyChairman("Narayana Murthy");
			session.update(companyDetails);
            transaction.commit();
		}catch (HibernateException e) {
			transaction.rollback();
		}finally{
			session.close();
		}
	}
}

Logic: SAVE –> UPDATE –> COMMIT
TRUE 1

  • Line 8,9 – the attributes are set to the object.The object’s instance is in the transient state.
  • Line 10-The instance is saved. So , it moves to the Persistence Context and becomes a persistent object.
  • Line 11- the instance is again set.
  • Line 12- the instance is updated in the Persistence Context. I mean, already an object is created in the persistence context and that object gets modified/updated. New object is not created in the persistence context.
  • Line 13 – The persistent object is committed/persisted to the DB.

Note:Update() can be performed only on Persistent Objects and not on transient/detached objects whereas saveOrUpdate() automatically converts a transient/detached object to persistent object.

CASE 3:

public class CompanyDao {
	public void enterCompanyDetails(){
		Session session=HibernateSessionManager.getInstance().getHibernateSession();
		Transaction transaction=session.beginTransaction();
		try{
			transaction.begin();
			CompanyDetails companyDetails=new CompanyDetails();
			companyDetails.setCompanyName("Infosys");
			companyDetails.setCompanyChairman("K.V.Kamath");
			session.save(companyDetails);
			companyDetails.setCompanyChairman("Narayana Murthy");
			session.saveOrUpdate(companyDetails);
			session.clear();
			System.out.println("Company Details present : "+session.contains(companyDetails));
            transaction.commit();
		}catch (HibernateException e) {
			transaction.rollback();
		}finally{
			session.close();
		}
	}
}

Logic: SAVE –> UPDATE –> CLEAR –> COMMIT
false

Here in the above code,

  • Line 8,9 -Instance is set.It exists in the transient state.
  • Line 10 -Instance is saved to Persistence Context.It is in the persistent state now.
  • Line 11,12 – instance is set and updated in the Persistence Context
  • Line 13- All instances in the Persistance context are cleared. It has no instance in the context now. This means , the instance is in detached state now.

Like clear() there is also another method evict().The difference is ,evict() detaches a particular instance from the context but clear() detaches all the instances from the Persistence Context.
Hope this post has added an extra feather to your understanding.

Written by thangaveluaishwarya

June 7, 2013 at 9:56 PM

A JOURNEY INTO LINUX

with 6 comments

tux_dancing_medium       It has become really rare to see a house without a computer. Computer Revolution has almost conquered the whole world. Computers are much like a mind-amplification tool.“Computers are like a bicycle for our mind”– says Steve Jobs. They do things that you order them, provided the instructions given are RIGHT..

     A Computer has Hardware components ( MotherBoard, Monitor, Keyboard and  etc.,) and Software components(System Software, Application Software and etc.,). Operating System is the System Software of a computer that helps the Application softwares to function. It provides services like Task Scheduling, Security Management, Network Management, Disk Management, Memory Management and etc.,

Eg:-For Word Process Package (Application Software) to function, it needs to talk to the System’s hardware. This is done via the help of an  Operating System.

In simple terms, I would say, Operating System acts much like an ELECTRONIC SERVANT to the Hardware and Application Software . It helps to bridge the communication gap between the Application Software and Hardware.

There are several Operating Systems like,

  1. Windows
  2. Mac OS
  3. Unix
  4. Linux

To know how Linux gained its popularity, let’s take  “A JOURNEY INTO LINUX”.

Now let’s travel 44 years back.…!!!

In 1969,the first version of Unix was developed at AT & T Bells Lab.The  Kernel (written in C) formed the base of the Unix System.Unix was primarily used as an Operating System only in MainFrames and MiniComputers .

The high-powered desktop workstations of companies like SUN were based on UNIX. Soon a number of other companies like HP, IBM, Apollo and etc.,entered into the workstation field to compete against SUN. Each one had Unix of their own version.On the other side, personal computers were also getting developed. Most of the homes and offices started having personal Computers.  The UNIX proprietary operating systems owned by separate companies were not able to capture the market due to different versions of UNIX.So most people started using MS DOS / Windows on their PC’s.     

The First Announcement from  Linus Torvalds (Image taken from thelinuxdaily.com)

The First Announcement from 
Linus Torvalds
(Image taken from thelinuxdaily.com)

 

  The year 1990, marked a new way. Linus Torvalds, a young man, studying Computer Science at the University of Helsinki wanted to make the Linux Kernel available for free to the world . He made his first Announcement to the world in the year 1991.(Refer image to your left)

     From that time, it was Linus’ goal to give a free OS, that completely compliants with the original UNIX. He also wanted to maintain  POSIX standards (Portable Operating System Interface for UniX) .

     Many Programmers started working on Linux. Whenever these coders found a new piece of hardware, they submitted it to the Linux lab. The Linux working group started releasing more free advanced code for an ever wide range of hardwares. For these coders , every piece of  new hardware they could find was useful for Linux development. From that time till now ,they did not stop at all .Their Journey is still on….

This made Linux to run not only on PC’s but also on Server-Side, Mobile Platforms etc.,.

 Important Properties of Linux:583-2542-1-PB

1.Stability– Linux systems are known for their ability to run without failure. Many Linux users have not seen a crash.It also has the ability to handle multiple processes at once. But other OS loose their stability soon when running multiprocesses.

2.No Frequent Rebooting– Configuration changes can be done while the Linux System is running and without affecting the other services. Generally, other OS needs a reboot when configuration changes are done, but  there is no need to restart Linux .

hacker

3. Security – “Internet is a world devoid of empathy”– says a LulzSec Hacker. The threat of hacking and cracking is still persisting. Protecting our systems has become the major issue.

Security model in Linux is based on the UNIX idea of Security. This security system is powerfully built. Linux comes with Security Firewall Software such as open source netfilter and other firewall tools that helps to protect our desktop from the crackers and hackers.Whereas in other OS , we have to purchase separately and update the Firewall Tool periodicaly.

Of course, Linux also gets attcked by viruses and malware. But the vulnerability is less. The bug can be found and fixed quickly.

1

4.Portability & Scalability-Linux is being run in almost all  hardware types- starting from the big MainFrame Machines to the PalmTops.

6.ResponseTime– Linux OS is faster and takes less time for debugging.

7.Cost Effective– If you want to install an operating system without punching holes in your pocket, then Linux is the Best Solution. It is an Open Source Software. It’s totally available for free.

Here are a few inportant places where Linux is being used –

  • U.S. Department of Defense,
  • U.S. Navy Submarine Fleet,
  • Federal Aviation Administration,
  • French Parliament, 
  • State-Owned Industrial and Commercial Bank of China,
  • Government of Mexico City, 
  • New York Stock Exchange, 
  • Giant Companies like-Google,Panasonic,Amazon, Sony PlayStation 3,Wikipedia,Cisco,
  • Several Schools and Universities and etc.,
linux-android

Linux Kernel in Android

Today, Linux is the only operating system in the world covering a wide range of hardwares like workstations, mid- and high-end servers, pc’s, “gadgets” like PDA’s, mobiles, embedded applications and etc.,

Linux Kernel is also being used in Google’s Android.

Linux Flavors:

Here are a few popular Linux Distribution names:

  1. Redhat Enterprise Linux
  2. Fedora Linux
  3. Debian Linux
  4. Suse Enterprise Linux
  5. Ubuntu Linux

logo

Click on this link to take yourself on an UBUNTU LINUX RIDE—->http://www.ubuntu.com/tour/en/

Linux File System Tree:

linux-file-tree

Image taken from linuxconfig.org

Below I have specifeid few basic Linux Commands. These commands can be used to traverse through the above tree.

Command Description
pwd Prints present working directory name
ls List Files
cp Copy Files
rm Remove Files
cd Change Directory
mkdir Create Directory
rmdir Delete/Remove Directory
find Locate files
which Locate commands
whereis Locate standard files
touch Change file timestamp
wc Count words/lines/bytes
chmod Change file Protections
grep Search text for matching lines
cdrecord Burns a Disk
compress Compresses Files(UNIX)

Written by thangaveluaishwarya

June 1, 2013 at 2:31 PM