EJB 3.1 Application with Stateless Session Bean on Glassfish 3.0 and NetBeans

June 18th, 2010 by Usha Informatique Team 14 comments »

Enterprise Java Beans (EJB) is a bit complex topic before the release of EJB 3.0 specification. In the EJB 3.0 specification the things are much simplified now from many perspectives

- Development of application using EJB

- Maintaining application having EJB

- Understanding of EJB for a new beginner

We have developed a sample application (with both local and remote interface) which illustrates creation of EJB and using it in a servlet. The infrastructure parts of the application are as follows

- NetBeans 6.8

- Glassfish Application Server (v 3.0)

The steps that needs to be followed are as follows

- Create a New Java EE Project SampleEJBApplication in Netbeans. Just follow the instruction provided by Netbeans.

- There would be three folders created ( SampleEJBApplication, SampleEJBApplication-ejb, SampleEJBApplication-war )

EJB Application

- In the SampleEJBApplication-ejb, create a package called com.sample.service

- Create a Local Interface called Calculator.java as follows

package com.sample.service;

import javax.ejb.Local;

/**
*
* @author Shashank
*/
@Local
public interface Calculator
{

public int calculate (int start, int end);

}

- Look out for @Local annotation which declare the interface to be local

- Create a class called CalculatorBean.java as follows which implements the local interface

package com.sample.service;

import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;

/**
*
* @author Shashank
*/
@Stateless

@EJB(name=”java:global/MyCalculatorBean”, beanInterface=Calculator.class)
public class CalculatorBean implements Calculator {

public String getServerInfo () {
return “This is glass fish server using EE6 version”;
}

public int calculate(int start, int end) {
return start+end;

}

public int remoteCalculate(int start, int end) {
return start+end;
}

}

Notice few things in the above class

- @Stateless annotation which declares the bean to be stateless

- @EJB(name=”java:global/MyCalculatorBean”, beanInterface=Calculator.class), it says that when referring to this bean using JNDI it could be called using  java:global/MyCalculatorBean

Front End Application (SampleEJBApplication-war)

- Inside the Source folder, create a package called servlets

- Now there are two approach using which you can refer to local EJB

Approach 1

- Use @EJB annotation inside the servlet to call the local EJB ( Available with Glassfish and not JBoss :) )

Approach 2

- Use JNDI lookup inside the servlet to call the local EJB

- Create a servlet called TestServlet.java using Netbeans

- For Approach 1 the code will go as follows

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(”text/html;charset=UTF-8″);
PrintWriter out = response.getWriter();

Calculator calculatorBean;
try {

Context context = new InitialContext();
calculatorBean = (Calculator) context.lookup(”java:global/MyCalculatorBean”);
out.println(”<html>”);
out.println(”<head>”);
out.println(”<title>Servlet TestServlet</title>”);
out.println(”</head>”);
out.println(”<body>”);
out.println(”<h1>Servlet TestServlet at ” + request.getContextPath() + “</h1>”);
out.println(calculatorBean.calculate(100, 200));
out.println(”</body>”);
out.println(”</html>”);

} catch (NamingException nex) {
nex.printStackTrace();
} finally {
out.close();
}
}

- Please notice as how the bean is referred using the JNDI name defined in bean class

- The same bean can be retrieved by using

a) (Calculator) context.lookup(”com.sample.service.Calculator”) (Non Portable JNDI lookup)

b) java:global/SampleEJBApplication/SampleEJBApplication-ejb/CalculatorBean!com.sample.service.Calculator (Portable JNDI lookup)

- For Approach 2, the code would go as follows

@EJB
private Calculator calculatorBean;
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(”text/html;charset=UTF-8″);
PrintWriter out = response.getWriter();

try {

out.println(”<html>”);
out.println(”<head>”);
out.println(”<title>Servlet TestServlet</title>”);
out.println(”</head>”);
out.println(”<body>”);
out.println(”<h1>Servlet TestServlet at ” + request.getContextPath () + “</h1>”);
out.println(calculatorBean.calculate(100, 200));
out.println(”</body>”);
out.println(”</html>”);

} finally {
out.close();
}
}

- Notice the usage of @EJB annotation with no issues regarding JNDI

- Run the code in both cases and should return 300 as the result

The implemtation for the remote interface would be given in next post.

Enjoy EJB 3.0 !!

Ushainformatique Development Team

Usage of Data Access Object (DAO) pattern in PHP

May 31st, 2010 by Usha Informatique Team 6 comments »

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 by Usha Informatique Team 69 comments »

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 by Usha Informatique Team 56 comments »

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

Usage of Data Transfer Object (DTO) Pattern in PHP

April 27th, 2010 by Usha Informatique Team 58 comments »

Data Transfer Object is a heavily used design pattern used in the development of web applications requiring database interaction in J2EE. It makes the life of a developer highly easy in managing the data that is being transferred and provides a secured way of transferring the data between layers.

When i switch from J2EE to PHP and with the release of PHP5, it suddenly comes to my mind to use this concept along with Data Access Object pattern (which i will explain in my next post) from J2EE in PHP  and it worked wonderfully for me to meet any level of complex applications.

What is a Data object?

First of all, we need to understand as what is a data object. A data object is a class representing a table in the database with the field names exactly same as database column names. It contains the getter and setter methods for these fields.

Let’s say i have a table called tbl_employee having columns as

- id (int 10)

- name ( varchar(50))

Now, the dataobject would typically look like

public class Employee()

{

var $id;

var $name;

public function getId()

{

return $this->id;

}

public function setId($tempId)

{

$this->id=$tempId;

return $this->id;

}

public function getName()
{
return $this->name;
}
public function setName($tempName)
{
$this->name=$tempName;
return $this->name;
}

Now the next point is about using it and see how helpful it would turn out to be. The following function interacts with the database thus assuming database connection is available.

public function getEmployeeList()

{

$employeeList = array();

$query = “select * from tbl_employee order by name”;

$result = mysql_query($query);

while ($row=mysql_fetch_array($result))

{

$tempEmployeeDO = new EmployeeDO();

$tempEmployeeDO->setId($row['id']);

$tempEmployeeDO->setName($row['name']);

$employeeList[count($employeeList)] = $tempEmployeeDO;

}

return $employeeList;

}

Thus the above function returns the list of employees containing data objects. On the front end you need to iterate through the list where each element is a DO and than use getter method to retrieve the values.

Start using it and you will realize that it makes your life pretty easy during development.

Enjoy!!

Ushainformatique Development Team

Database modeling with Microsoft Visio for an Existing MySQL Database

April 18th, 2010 by Usha Informatique Team 91 comments »

In a SDLC, creating a database model diagram is an important step that needs to be taken to achieve the following

- Create a clear visualization of the Database for the system which makes the database understanding pretty easier

- It helps in derive out the classes required to be created by just looking into the database modeling diagram in depth

If you are not able to buy the paid tool for UML modeling such as rational rose etc., it’s still achievable through Microsoft Visio. Following are the steps that need to be performed to create a model diagram from an existing MySQL database in Microsoft Visio which is called as Reverse Engineering

- First of all, download the ODBC driver for MySQL from the location http://dev.mysql.com/downloads/connector/odbc/5.1.html. Download the installable by selecting the appropriate one based on  your machine configuration (32 bit or 64 bit)

- Install the mysql connector

- After installation, open visio

- Go to File->New->Database->Database Model

- From Database Menu, select Reverse Engineer

- On the Create New Datasource screen displayed, click on User Data Source

- Provide a datasource name

- Select the mysql connector driver, click on Next

- Click Finish and your new datasource would be added and would come as selected

- Click on Next

- Enter the valid username and password to create the connection using the datasource

- Select Object Type to reverse engineers

- You would be asked to select the database

- On selecting database, tables would be displayed

- Select the tables you want to create the datamodel for

- On selecting the tables, you would be asked to create the model with shape or without shape

- I select the shaped one and the model is generated

It’s really a helpful tool for the beginner to start creating the Database Modeling Diagram from an existing Database

Code Formatting in Netbeans 6.8

April 17th, 2010 by Usha Informatique Team 21 comments »

In any project in web world, code formatting plays a key role during the development of the project as it makes the code review process very simple at least from readability point of view.

The more readable your code is the more easy it is to review it. Now, how to format the code in Netbeans 6.8.

There are two levels at which formatting can be performed in Netbeans 6.8.

1) At a global level – It’s applicable across all the projects for which netbeans would be used

2) At a project level – It is specific to a particular project

For the first option

a) Go to Tools->Options->Editor-> Formatting

b) Please select the language for which you want to apply the formatting, for me it is PHP

c) Select the category, which could be Tabs and Indent or Braces

d) Put your option for Tabs and Indent in terms of tabs or if you choose to go with spaces

e) For braces, you can select new line, same line or preserve existing

This is pretty useful as if you are aware of it, it saves lot of effort from your end.

Enjoy working with Netbeans 6.8 !!

Dynamic JSF Application with MySql on JBoss 4.2.2 GA

March 21st, 2010 by Usha Informatique Team 109 comments »

I have created a small JSF application (Employer Management) with MySQL as database on JBoss 4.2.2 GA in Netbeans 6.8.

These are the steps that need to be followed

1) Copy the mysql driver class (mysql-connector-java-5.1.6-bin.jar) which comes with Netbeans and located under {INSTALL DIR}/NetBeans 6.8/ide12/modules/ext to {INSTALL DIR}/server/default/lib. You don’t need to have the driver in your classpath.

2) Go to  {INSTALL DIR}/docs/examples, copy the mysql-ds.xml and copy it to {INSTALL DIR}/server/default/deploy. Change the database settings as per your configuration

3) Go to the services and (re)start the Application Server

4) Come back to netbeans, create a new project under category “Java Web”

5) Create a Managed Bean called “Employer” with member variables (id, firstname, lastname,phone and email) and corresponding getter and setter methods

6) Create a Backing Bean called EmployerFormBean with two variables

a) Employer

b) EmployerList

7) Create the getter setter for the above two variables and initialize the employerList by calling the getEmployerList function in EmployerDAO which is discussed later

8) Add method called addEmployer with its code as follows

EmployerDAO empDAO = new EmployerDAO();
empDAO.insertData(this.getEmployer());
return “go_insert_data”;

9) The configuration for Managed Bean, Backing Bean and “go_insert_data” should be made in faces-config.xml

<managed-bean>
<managed-bean-name>employerBean</managed-bean-name>
<managed-bean-class>com.testjsf.EmployerFormBean</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<managed-property>
<property-name>employer</property-name>
<property-class>com.domain.Employer</property-class>
<value>#{employer}</value>
</managed-property>
</managed-bean>
<managed-bean>
<managed-bean-name>employer</managed-bean-name>
<managed-bean-class>com.domain.Employer</managed-bean-class>
<managed-bean-scope>none</managed-bean-scope>
</managed-bean>

<from-view-id>/employer.jsp</from-view-id>
<navigation-case>
<from-outcome>go_insert_data</from-outcome>
<to-view-id>/employerlist.jsp</to-view-id>
</navigation-case>

10) As you see, the database operations are performed inside DAO. The method insertData would be as follows

InitialContext ctx = new InitialContext();
//DataSource ds = (DataSource) ctx.lookup(”jdbc/jsfperson”);
DataSource ds = (DataSource) ctx.lookup(”java:/MySqlDS”);
conn = ds.getConnection();
String query = “insert into employer(firstname,lastname,email,phone) values (?,?,?,?)”;
//String query = “insert into employer(firstname,lastname,email,phone) values (’Mayank’,'Singhai’,'123456′,’abc@yahoo.com’)”;
stmt = conn.prepareStatement(query);
stmt.setString(1, emp.getFirstname());
stmt.setString(2, emp.getLastname());
stmt.setString(3, emp.getEmail());
stmt.setString(4, emp.getPhone());
stmt.executeUpdate();

11) While doing the JNDI lookup in JBoss call it as “java:/{dsname}” as defined in mysql-ds.xml

12) After insert, populate the employerList again in the backing bean before redirecting

12) Similarly create the getEmployerList function to get the list of employers

13) Now create two jsp

a) employer.jsp where form to insert data for the employer. The fields here are bind to the employer object in employerbean. The structure is as

<h:form id=”EmployerForm”>
<h:outputLabel value=”#{msg.firstname}”/> <h:inputText value=”#{employerBean.employer.firstname}”/>
<h:outputLabel value=”#{msg.lastname}”/> <h:inputText value=”#{employerBean.employer.lastname}”/>
<h:outputLabel value=”#{msg.phone}”/> <h:inputText value=”#{employerBean.employer.phone}”/>
<h:outputLabel value=”#{msg.email}”/> <h:inputText value=”#{employerBean.employer.email}”/>
<h:commandButton action=”#{employerBean.addEmployer}” value=”Submit”/>
<h:commandLink action=”show_emp_data” value=”Show all employers”/>
</h:form>

b) employerlist.jsp To display the list of employers. In this use the dataTable concept of JSF which is as follows

<h:form>
<h:dataTable value=”#{employerBean.empList}” var=”item”>
<h:column>
<f:facet name=”header”>
<h:outputText value=”Employee No.”/>
</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:column>
<f:facet name=”header” >
<h:outputText value=”Email”/>
</f:facet>
<h:outputText value=”#{item.email}”/>
</h:column>
<h:column>
<f:facet name=”header” >
<h:outputText value=”Phone”/>
</f:facet>
<h:outputText value=”#{item.phone}”/>
</h:column>

</h:dataTable>
</h:form>

16) Compile the code and run employer.jsp. On successful insertion, employerlist with newly inserted record would be displayed.

How to save your image from being stolen?

March 19th, 2010 by Usha Informatique Team 8 comments »

In one of the projects (in PHP)  we are working on, the client has a requirement that logo image should not be downloaded to “Temporary Internet Files” folder so that it can not be stolen. Although i gave him the suggestion that  i can even do that using photoshop. After doing lot of research we boiled down to two options

1) Manage it from .htaccess file but this works only in case you want to prevent hot linking to your site images where you can easily check that if the image request in not coming from your domain, forward it to a forbidden page

2) Create a transparent image with the actual image being taken as the background image. Thus when a user try to save it it saves the transparent image but not the actual image in the background. This technique works best with the actual image not been saved to  “Temporary Internet Files” folder. Keep in mind while using this technique save the images as PNG

JDBC Connection with Glassfish and MySQL on Netbeans 6.8

March 19th, 2010 by Usha Informatique Team 49 comments »

This is a small proof of concept that we have done for creating the JDBC connection with MySql Database and  Glassfish Application Server. This is performed on Netbeans 6.8 which seems to be working best for our team.

These are the steps that need to be followed

1) Copy the mysql driver class (mysql-connector-java-5.1.6-bin.jar) which comes with Netbeans and located under {INSTALL DIR}/NetBeans 6.8/ide12/modules/ext to {INSTALL DIR}/glassfish/domains/domain1/lib/ext. You don’t need to have the driver in your classpath.

2) Go to the services and (re)start the Application Server

3) Right click on Server Name and click on View Admin Console

4) After admin console loads, click on Resources in left nav, JDBC resources and connection pools will be displayed

5) Create a Connection pool with resource type as javax.sql.DataSource and Datasource class name as com.mysql.jdbc.jdbc2.optional.MysqlDataSource ( This will be present in jar copied in step 1). Under additional attributes, add user,password, databaseName.

6) Always keep the ping enabled to check the connectivity

7) On Save, ping would be executed. Based on the status (Success or failure) message would be displayed

8) If the ping is successful,  create a JDBC resource with name as jdbc/{yourname}. In glassfish always give jdbc name starting with ‘jdbc/’.

9) Come back to netbeans, create a new project under category “Java Web”

10) In the Source Package Folder, create a package

11) Right click on package name and select new “Servlet”

12) After the servlet is created, in the try block within doProcess method, paste the following code

InitialContext ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup(”jdbc/{yourjdbcname}”);

Connection conn = ds.getConnection();
Statement stmt = conn.createStatement();

13) The above code gets the datasource connection in the JDBC pool created from Admin console

14) Execute a query which in my case is

ResultSet rs = stmt.executeQuery(”select * from person”);

out.println(”<html>”);
out.println(”<head>”);
out.println(”<title>Servlet POC on Glassfish</title>”);

while(rs.next())
{
out.println(”<h1>First Name is ” + rs.getString(”firstname”) + “</h1>”);
out.println(”<h1>Last Name is ” + rs.getString(”lastname”) + “</h1>”);
}
out.println(”</body>”);
out.println(”</html>”);

stmt.close();
stmt=null;
conn.close();
conn=null;

15) Always close the connections at the end

16) Compile the code and run it. The result would be displayed