Archive for May, 2010

Usage of Data Access Object (DAO) pattern in PHP

May 31st, 2010

Data Access Object pattern is a heavily used design pattern used in J2EE, but good thing is that it could be used in a very efficient manner in PHP.

What is DAO pattern?

The very first thing we need to understand is what is DAO pattern. In our last blog on DTO, it is emphasized that Data Object is an exact replica of a database table with getter and setter methods for the fields.

Let’s assume that a database connection is created in the controller or in the managed bean of JSF and dataobject is populated with the results. Now i need to execute the same query in another controller or managed bean than i need to again write the same query. Thus in this way our database layer is tightly coupled to the web part.

Thus to abstract the database layer, if a new layer is introduced in between web and database which provides an interface to access the database, it would decouple the database from the web layer. Also, the same query hasn’t need to be rewritten. This is what is called Data Access Object Layer.

Usage of DAO pattern

Option 1
- Create a class called EmployerDAO.php

- Let’s say i want to display the list of employers, than my function would go like in the EmployerDAO.php

public function getEmployerDetails($id)
{
$employerQuery = “select * from tbl_employer where employerid=’$id’”;
$tempEmployerVO = new EmployerVO();

$employerResult = mysql_query($employerQuery);
$row = mysql_fetch_array($employerResult) ;

$tempEmployerVO-> setId() = $row-> id;

$tempEmployerVO-> setFirstname() = $row->firstname;

$tempEmployerVO-> setLastname() = $row->lastname;

return $tempEmployerVO;
}

Thus in the controller, you would instantiate the DAO class and call this method to retrieve the dataobject of employer.

In this way wherever you want to have the enployer details, just instantiate the DAO and call the result.

The key point to note here is that if the same table is used in another php project, you can use the same DAO layer. Thus it improves the efficiency and maintenance of the code to a large extent.

Option 2

Another way you can use the same DAO layer is as the interface and different classes can implement the interface as per the requirement. This is one more level of abstraction.

It would be helpful in cases where you have different logic to be implemented before populating the dataobject.

Give it a try !!

Ushainformatique Development Team

Dynamic JSF application with MySQL on Glassfish with Toplink

May 8th, 2010

In my last post, i talked about developing a Dynamic JSF application with MySQL on JBoss with simple JDBC connection.

In this post, i am going to talk about a sample application with

- JSF

- Netbeans 6.8

- Glassfish Application Server

- MySQL Database

- Persistence API (Provider Toplink)

About the application

This would be a simple application which performs the following

- Insert Person Data into the database

- Fetch the person list from the database

The key difference over here is that we are going to use Java Persistence API over here to make the transactions.

First of all we need to understand as what is Java Persistence API.  As per the sun here is a very good definition for JPA.

The Java Persistence API is a POJO persistence API for object/relational mapping. It contains a full object/relational mapping specification supporting the use of Java language metadata annotations and/or XML descriptors to define the mapping between Java objects and a relational database. It supports a rich, SQL-like query language (which is a significant extension upon EJB QL) for both static and dynamic queries. It also supports the use of pluggable persistence providers.

Thus with the evolution of Java Persistence API, a standard of persistence framework has been set and many vendors are providing the implementation of the API and toplink is the open-source community edition of Oracle’s TopLink product.

Implementation

- In Netbeans, Create a Java Web project called TestPersonApplication and select the JSF framework while creating it. The folder structure would be created.

- After that create a mysql database,  in my case i call it jsfperson with table as person. The person table would have id (int), firstname (varchar) and lastname (varchar) as the fields

- Run the Glassfish Application Server and from services tab, against the server click “View Admin Console

Connection Pool Creation and JDBC resource creation

- After the admin console is loaded, click on JDBC and JDBC resources would be displayed

- Under Connection Pool, Click on Add a New Pool

- Enter Name, Resource Type as javax.sql.Datasource and Vendor as MySql and click on Next

- On the next screen, add the properties User, portnumber (3306), databaseName (jsfperson), Password, driverClass (com.mysql.jdbc.Driver), URL (jdbc:mysql://localhost:3306/jsfperson) and serverName(localhost) and click on Finish

- After Finish, click on Ping to check the connection, if the ping is successfully, your pool is created perfectly

- Now under JDBC resources, Click on “New”

- Enter the JNDI name and select the pool you created above (By default, when you again run the server, it creates a pool like mysql_jsfperson_rootPool, check that :) ) and click on Save

- After the save check sun-resources.xml under Server Resources and you will see the configuration

Creation of Entity Class

- Coming to Netbeans again, under Source Packages folder, create a package called com.domain

- Right click on the folder and select New – >Entity class from Database

- Select the datasource as jsfperson (Which you added earlier) and it will retrieve the database schema

- Select the table and Click on Add and than click on Next

- On next screen, it would show you the details for Person Entity and click on Finish

- The object would be created with Annotations for the mapping between Entity fields and Database field. The generated code would go like this

@Id
@Basic(optional = false)
@Column(name = “id”)
private Integer id;
@Column(name = “firstname”)
private String firstname;
@Column(name = “lastname”)
private String lastname;

The class would implement Serializable interface with getter, setter methods for the fields, equals method and toString Method. In addition, the queries would be generated as follows

@Entity
@Table(name = “person”)
@NamedQueries({
@NamedQuery(name = “Person.findAll”, query = “SELECT p FROM Person p”),
@NamedQuery(name = “Person.findById”, query = “SELECT p FROM Person p WHERE p.id = :id”),
@NamedQuery(name = “Person.findByFirstname”, query = “SELECT p FROM Person p WHERE p.firstname = :firstname”),
@NamedQuery(name = “Person.findByLastname”, query = “SELECT p FROM Person p WHERE p.lastname = :lastname”)
})

Check the @Entity and @Table annotation (Here the mapping starts) !!

Creation of Persistence Unit

- Right click on the project and select New -> Other -> Persistence ->Persistence Unit

- Enter Name, persistence provider which is Toplink and datasource created (jsfperson)

- Click on Finish and a file called persistence.xml would be created under configuration with transaction type as JTA

- Enter the class for which this PU would be used.  The xml would go like

<?xml version=”1.0″ encoding=”UTF-8″?>
<persistence version=”1.0″ xmlns=”http://java.sun.com/xml/ns/persistence” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=”http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd”>
<persistence-unit name=”TestJSFApplicationPU” transaction-type=”JTA”>
<provider>oracle.toplink.essentials.PersistenceProvider</provider>
<jta-data-source>jsfperson</jta-data-source>
<class>com.domain.Person</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties/>
</persistence-unit>

</persistence>

Creation of JSF Managed Bean

- Create a folder called com.testjsf under Sources Folder

- Right click on it and select New Jsf Managed Bean called PersonBean with configuration file as faces-config.xml under WEB-INF

- Declare two variables named Person (Entity Object ) and personList

- Create the getter and setter method for the variables

Creation of Data Access Object

Now we will make the connection class using DAO (data access object) design pattern

- Create a package called com.dao and create a class called PersonDAO

- The class would look like the following

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.dao;

import com.domain.Person;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

/**
*
* @author Shashank
*/
public class PersonDAO {

public void insertData(Person p){

EntityManagerFactory emf = Persistence.createEntityManagerFactory(”TestJSFApplicationPU”);
EntityManager em= emf.createEntityManager();

try
{
em.getTransaction().begin();
em.persist(p);
em.getTransaction().commit();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
em.close();
}
}

public List getPersonList() {
List empList=null;
EntityManagerFactory emf = Persistence.createEntityManagerFactory(”TestJSFApplicationPU”);
EntityManager em= emf.createEntityManager();

try
{
Query q= em.createNamedQuery(”Person.findAll”);
empList= q.getResultList();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
em.close();
}
return empList;
}
}

In the above class there are few things to note

- JPA provides a class called EntityManagerFactory identified by persistence unit created above which manages all the transaction handling

- For example, to insert the data assuming Person object is there

a) Create a EntityManagerFactory

b) Create a Entity Manager

c) Begin transaction with em.getTransaction().begin()

d) call the persist function with person object as the argument. This statement would insert the data into the database

e) Finally commit is called

After creating the class, come back to PersonBean class and in the constructor for it, instantiate Person and Personlist (by calling PersonDAO getPersonList method). The constructor would go like

public PersonBean() {
person= new Person();

PersonDAO pDao= new PersonDAO();
personList = pDao.getPersonList();
}

Add two methods to it for adding a person and listing all persons which are as follows

public String addPerson()
{
PersonDAO pDao= new PersonDAO();
pDao.insertData(this.person);
this.setPersonList(pDao.getPersonList());
return “greeting“;
}

public String getAllPersonList()
{
PersonDAO pDao= new PersonDAO();
this.setPersonList(pDao.getPersonList());

return “go_person_list“;
}

Ok, now you are done with back end part. Keep the last two return statement in mind. I would discuss about them in the post below.

Front End with JSF

In the front end, add a file addPerson.jsp with firstname and lastname. The JSF part of it would go like

<f:view>
<h1>
<h:outputText value=”#{msg.inputname_header}”/>
</h1>
<h:form id=”helloForm”>
<h:outputText value=”#{msg.prompt}”/>
<h:inputText value=”#{personBean.person.firstname}” />
<h:inputText value=”#{personBean.person.lastname}” />
<h:commandButton action=”#{personBean.addPerson}” value=”#{msg.button_text}” />
<h:commandLink action=”go_person_list” value=”Show all persons”/>
</h:form>
</f:view>

Note that against the button action is mapped to addPerson method in the bean class.  The “h” and “f” tags are html and core tag libraries for JSF.

faces-config.xml

- Person bean is already added

- Add person as the managed property for it as

<managed-bean>
<managed-bean-name>personBean</managed-bean-name>
<managed-bean-class>com.testjsf.PersonBean</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<managed-property>
<property-name>person</property-name>
<property-class>com.domain.Person</property-class>
<value>#{person}</value>
</managed-property>
</managed-bean>

This is how the person object is accessed under personbean in the jsf.

Handling Navigation

- Add the navigation rule as follows

<navigation-rule>
<from-view-id>/welcomeJSF.jsp</from-view-id>
<navigation-case>
<from-outcome>greeting</from-outcome>
<to-view-id>/personlist.jsp</to-view-id>
</navigation-case>
<from-view-id>/welcomeJSF.jsp</from-view-id>
<navigation-case>
<from-outcome>go_person_list</from-outcome>
<to-view-id>/personlist.jsp</to-view-id>
</navigation-case>
</navigation-rule>

- On submission of form, addMethod is called. If you see the last statement given above, on return “greeting” , the flow would go to first navigation rule with from view as welcomeJSF.jsp and action as greeting thus personlist.jsp would be called and loaded.

- The person list file would go like

<f:view>
<h:form>
<h:dataTable value=”#{personBean.personList}” var=”item”>
<h:column>
<f:facet name=”header”>
<h:outputText value=”Id”/>
</f:facet>
<h:outputText value=”#{item.id}”/>
</h:column>
<h:column>
<f:facet name=”header” >
<h:outputText value=”First Name”/>
</f:facet>
<h:outputText value=”#{item.firstname}”/>
</h:column>
<h:column>
<f:facet name=”header” >
<h:outputText value=”Last Name”/>
</f:facet>
<h:outputText value=”#{item.lastname}”/>
</h:column>

</h:dataTable>
</h:form>
</f:view>

In the file above, when {personBean.personList} is called, personBean is invoked and in the constructor, the latest person list is set. Thus on calling getter for personList, it returns the latest list after addition.

Thus you can develop the sample application using JPA with JSF in netbeans.

Thanks,

Ushainformatique Development Team

Implement Yahoo weather API along with Google map integration

May 2nd, 2010

Requirements

We got a requirement to display weather for a city along with google map for the city.

Approach

There can be two approach that can be used

1) Implement yahoo weather API and Google map separately thus each is working independently

2) Implement google map using the information derived from yahoo weather API

Here i am going to talk about the second approach

To access weather for any city using Yahoo weather API, you have to use the following code

<?php

<span>XML</span> document into memory first.

$doc = new DOMDocument();

$doc->load(’http://weather.yahooapis.com/forecastrss?w=’.$weatherlocation.’&u=c‘);

//now I get all elements inside this document with the following name “channel”, this is the ‘root’

$channel = $doc->getElementsByTagName(”channel”);

//now I go through each item withing $channel

foreach($channel as $chnl)
{

$item = $chnl->getElementsByTagName(”item”);

foreach($item as $itemgotten)
{

echo “<b>”.$itemgotten->getElementsByTagName(”title”)->item(0)->nodeValue.”</b><br/>”;

//now I search within ‘$item’ for the element “description”

$describe = $itemgotten->getElementsByTagName(”description”);

//once I find it I create a variable named “$description” and assign the value of the Element to it

$description = $describe->item(0)->nodeValue;

//and display it on-screen

echo $description;

$latitude=$itemgotten->getElementsByTagName(”lat”)->item(0)->nodeValue;

$longitude=$itemgotten->getElementsByTagName(”long”)->item(0)->nodeValue;

}

}
?>

In the above code, the yahoo weather url is called with arguments w and u (Unit of temperature). “w” is the location of the city you want the get the weather for. This you will get from yahoo weather page http://weather.yahoo.com.

Simply enter the city and from the url retrieve the value for e.g in http://weather.yahoo.com/united-states/california/bombay-2366506/, 2366506 is the value of “w”.

The last two lines in the code above are the tricky one’s. From the last two lines, you can retrieve the latitude and longitude of the place, thus think you are saving so much database space by not storing latitude and longitude of places.

After getting the latitude and longitude for the place just pass to it google map API code which in my case is like the following

<script type=”text/javascript” src=”http://www.google.com/jsapi?key=ABQIAAAAQg2VLDfgi8yxVrFlqjXF7xTQHiNlpCS1vy260As8BGMS2rl5kBTvFuKiyHlh1z2mfCbd6sJqj9WfIw”></script>
<script type=”text/javascript”>
google.load(”maps”, “2.x”);
</script>
<script type=”text/javascript” charset=”utf-8″>
$(document).ready(function(){
var map = new GMap2($(”#mapdiv”).get(0));

var delhi = new GLatLng(<?php echo $latitude; ?>,<?php echo $longitude; ?>);
map.setCenter(delhi,8);
marker = new GMarker(delhi);
map.addOverlay(marker);
});
</script>
<style type=”text/css” media=”screen”>
#mapdiv { float:left; width:213px; height:144px;padding:0px 0px 0px 0px;margin:0px 0px 0px 0px;overflow:hidden;border:1px solid #CCCCCC;}

</style>
<div id=”mapdiv”></div>

Thus i would have both weather and google map for the place by just storing one value in the database  i.e. “w” factor.

Thanks !! Ushainformatique Development Team