Dec 27, 2012

Configuring PHP in Apache Http Server


WAMP setup Step by Step

Download Apache Http Server
Download Apache HTTP Server from location http://httpd.apache.org/download.cgi. For this tutorial we will be using Apache HTTP server 2.2.22 i.e. httpd-2.2.22-win32-x86-openssl-0.9.8t.msi
Once downloaded install this server on local machine. Once installation is done following icon will appear on bottom right corner of your machine (if you are using windows OS). Going forward we will call this location APACHE_HOME, Save the location where Apache Httpd server is installed you will need this very frequently. (Simply create one .txt file to save all this info for time being, later you will by heart all this). In my case this location is C:\Program Files (x86)\Apache Software Foundation\Apache2.2
Hit the url http://localhost and welcome page of Apache as shown in Figure 1 should appear

Figure 1










Download PHP
Download latest version of php from http://www.php.net/downloads.php. In this tutoarial we are using latest stable version 5.4.6. Download and extract it on your local machine. Once archive is extracted, open command prompt and go to this location. Run simple command.
Note: There is a catch here download thread safe version and not non thread safe one.

Figure 2:






On command prompt it will give you some info and also this is a simple test to check that PHP running fine standalone on your local machine. Save this location too.

Figure 3















Copy php.ini-development file as php.ini.


Configure Apache with PHP
Go to APACHE_HOME/conf and save the original httpd.conf as httpd_original.conf so this file is not lost and can be restored if anything goes wrong. Now open this file for edit in your favourite editor.  (Mine is notepad++) and check for word LoadModule (or say section where all modules are loaded). At the end of this section add following lines
LoadModule php5_module "<PHP_HOME>/ php5apache2_4.dll"
AddHandler application/x-httpd-php .php

Also add following line to tell apache where php related configurations are
PHPIniDir "<PHP_HOME>"

Check in APACHE_HOME/conf/httpd.conf what is the value of DocumentRoot (by default this value in httpd.conf is set to APACHE_HOME/htdocs) lets call this value APACHE_DOC_ROOT. Now write a simple php file (hello.php) in APACHE_DOC_ROOT as follows
<?php
echo “Hello”
?>

Now hit the url http://localhost/hello.php Hello message should be shown as in Figure 4.

Figure 4


Dec 16, 2012

Web Application Security


Web Application Security:

Step 1: Add an entry in web.xml

Add an entry for <security-constraint> in web.xml as shown in Table 1

Table 1
<security-constraint>
     <web-resource-collection>
           <web-resource-name>Generic</web-resource-name>
           <url-pattern>/*</url-pattern>
           <http-method>GET</http-method>
           <http-method>POST</http-method>
     </web-resource-collection>
</security-constraint>

<security-constraint>
     <web-resource-collection>
      <web-resource-name>Protected</web-resource-name>
      <description>Protected Resources</description>
      <url-pattern>/protected/*</url-pattern>
      <http-method>POST</http-method>
      <http-method>GET</http-method>                 
     </web-resource-collection>
     <auth-constraint>
           <role-name>admin</role-name>
     </auth-constraint>
     <user-data-constraint>
      <transport-guarantee>NONE</transport-guarantee>      
     </user-data-constraint>
</security-constraint>
<login-config>
     <auth-method>FORM</auth-method>
     <form-login-config>
           <form-login-page>/login.html</form-login-page>
           <form-error-page>/loginfail.html</form-error-page>
     </form-login-config>
</login-config>
<security-role>     
     <role-name>admin</role-name>
</security-role>

Step 2: Create an html/jsp file for login form
Now we need to create a file/form that we want to use for accepting user credentials (id and password). So create a simple html file as shown in Table 2.

Table 2
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Sample Application: Login</title>
</head>
<body>
       <form action="j_security_check" method="POST">
              <table>
                     <tr>
                           <td>User Name</td>
                           <td><input id="j_username" name="j_username"></td>
                     </tr>
                     <tr>
                           <td>Password</td>
                           <td>
                           <input id="j_password" name="j_password" type="password">
                           </td>
                     </tr>
                     <tr>
                           <td colspan="2"><input type="submit" value="Login"></td>
                     </tr>
              </table>
       </form>
</body>
</html>

Also we need to create a file where application will be routed if login fails. So create an error html as shown in Table 3.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Sample Application: Login Failed</title>
</head>
<body>
       <span style="color:red">Login Failed</span>
</body>
</html>

Also create one index.html  as a home page and one html (protected.html in folder protected inside Web application root) Now deploy this application/war on your Application Server.

Step 3: Try to access non protected resource
Hit the url http://localhost:7001/SampleApp/ it will show the home page as show in Figure 1

Figure 1


So resource at above mentioned location is successfully accessed.
Step 4: Try to access protected resource
Now if we try to access web resource (i.e http://localhost:7001/SampleApp/protected/protected.html) which we have protected by adding following lines in web.xml

<security-constraint>
     <web-resource-collection>
      <web-resource-name>Protected</web-resource-name>
      <description>Protected Resources</description>
      <url-pattern>/protected/*</url-pattern>
      <http-method>POST</http-method>
      <http-method>GET</http-method>                 
     </web-resource-collection>
     <auth-constraint>
           <role-name>admin</role-name>
     </auth-constraint>
     <user-data-constraint>
      <transport-guarantee>NONE</transport-guarantee>      
     </user-data-constraint>
</security-constraint>


It will first ask for credentials as shown in Figure 2

Figure 2


If credentials are not proper then it will show file configured in form-error-page as shown in Figure 3.

Figure 3


If login is successful then requested resource will be displayed as shown in Figure 4

Figure 4


Dec 8, 2012

doWork in Hibernate


Hibernate 4 onwards method connection() for fetching java.sql.Connection is removed (in later versions of Hibernate 3 it was deprecated). Instead of getting connection from Hibernate Session we need to use two new methods provided by Hibernate depending on whether you we need to return some value after performing JDBC operation. These two methods are
  • doWork
  • doReturningWork
To explain difference between these two methods consider following scenario.
We need to run two Stored Procedure
  1. Run a procedure to generate salary data for the organization and return an ARRAY to Java code which will in turn generate salary sleeps in PDF format and a mail API will send this information to employees. So here we will use doReturingWork of HibernateSession.
  2. Run a procedure which will Perform Bank’s EOD (End Of Day) operations and will not return anything in case of Successful execution but will store cause of Error in some table for audit purpose. Here we are not expecting any value from Stored Procedure so we will use doWork method of Hibernate Session.
For simplicity we will use much simpler examples here to understand working of these two methods.
Hibernate doWork()
Let’s say we have a table EMP_DETAILS as shown in Figure 1
Figure 1

And we have a list of Employees who have moved out of company and their id is passed in a java.util.List. We want to set IS_ACTIVE for these employees to ’N’.  So we will call doWork method on Hibernate Session. This method will accept single argument of org.hibernate.jdbc.Work interface.
Interface org.hibernate.jdbc.Work has single method
public void execute(Connection arg0) throws SQLException
So we have two options
1)      Implement this method within the call
2)      Create a separate class that will implement this method and pass this class in doWork method while calling from Session.
We will use first approach. So first we write a method that will accept list of Employee IDs for which we want to set IS_ACTIVE to false.

public void updateEmployeeStatus(final List<String> employeeList) throws DBException
{
       Session session = null;
       try
       {
              session = HibernateUtil.getSession();
              session.beginTransaction();
              session.doWork(new Work() {
                     @Override
                     public void execute(Connection conn) throws SQLException {
                           PreparedStatement pStmt = null;
                           try
                           {
                                  String sqlQry = "UPDATE EMP_DETAILS set IS_ACTIVE='N' WHERE EMP_ID=?";
                                  pStmt = conn.prepareStatement(sqlQry);
                                  for(String empId:employeeList)
                                  {
                                         pStmt.setString(1, empId);
                                         pStmt.addBatch();
                                  }
                                  pStmt.executeBatch();
                           }
                           finally
                           {
                                  pStmt.close();
                           }                                
                     }
              });
              session.getTransaction().commit();
       }
       catch(HibernateException e)
       {
              throw new DBException("Error occured while updating Employee Status",e);
       }
       finally
       {
              HibernateUtil.closeSession(session);
       }            
}

And then we will call this method with list of Employee IDs.
List<String> employeeList = new ArrayList<>();
employeeList.add("A001");
updateEmployeeStatus(employeeList);


Now we are done with doWork so let’s return something after performing JDBC operation with the help of doReturingWork
Hibernate doReturningWork()
So now let’s reconsider previous example with a slight change. We just do not want to update records but also want to get number of records updated (assuming a scenario where we have few employee Ids missing in our table so by end of the day we want to compare number of records passed in List and number of records updated and count returned from DAO.
So we need to change our function as follows
public int updateEmployeeStatusWithCount(final List<String> employeeList) throws DBException
{
       Session session = null;
       try
       {
              session = HibernateUtil.getSession();
              session.beginTransaction();
              int cnt = session.doReturningWork(new ReturningWork<Integer>() {
                     @Override
                     public Integer execute(Connection conn) throws SQLException {
                           PreparedStatement pStmt = null;
                           try
                           {
                                  int updatedCnt = 0;
                                  String sqlQry = "UPDATE EMP_DETAILS set IS_ACTIVE='N' WHERE EMP_ID=?";
                                  pStmt = conn.prepareStatement(sqlQry);
                                  for(String empId:employeeList)
                                  {
                                         System.out.println(empId);
                                         pStmt.setString(1, empId);
                                         int cnt = pStmt.executeUpdate();
                                         updatedCnt+=cnt;
                                  }
                                  return updatedCnt;
                           }
                           finally
                           {
                                  pStmt.close();
                           }                                
                     }
              });
              session.getTransaction().commit();
              return cnt;
       }
       catch(HibernateException e)
       {
              throw new DBException("Error occured while updating Employee Status",e);
       }
       finally
       {
              HibernateUtil.closeSession(session);
       }            
}
                                                                                                                                                                                                                                                        
We will call our function slightly in a different way as shown below.
List<String> employeeList = new ArrayList<>();
employeeList.add("A001");
employeeList.add("A002");
int cnt = dao.updateEmployeeStatusWithCount(employeeList);
if(employeeList.size()!=cnt)
{
       System.out.println("Number of ids passed and number of records update not matching.");
}

So this will give us output as shown.
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: UPDATE EMP_DETAILS set IS_ACTIVE='N' WHERE EMP_ID=?
A001
A002
Number of ids passed and number of records update not matching

So this works…Happy coding J

Same blog is available on my  blogging site