Pages

Thursday, June 24, 2010

Logging the Request [Access Log]


If we want to log all the requests [time, what was accessed, the Response status e.t.c], we need to add a valve to the context.xml file like

<Valve
    className="org.apache.catalina.valves.FastCommonAccessLogValve"
    directory="${catalina.home}/logs/"
    prefix="access_log"
    fileDateFormat="yyyy-MM-dd.HH"
    suffix=".log"
    pattern="%t %H cookie:%{SESSIONID}c request:%{SESSIONID}r  %m %U %s %q %r"/>

This allows the tomcat to create a log file under the logs directory in tomcat home and create a file with the prefix access_log and add the requests that came .

A excerpt from the access_log in my box ,

[24/Jun/2010:01:22:33 -0500] HTTP/1.1 cookie:- request:-  GET /manager/html 200  GET /manager/html HTTP/1.1

[24/Jun/2010:01:22:36 -0500] HTTP/1.1 cookie:- request:-  GET /SimpleSample/ 200  GET /SimpleSample/ HTTP/1.1

[24/Jun/2010:01:22:36 -0500] HTTP/1.1 cookie:- request:-  POST /SimpleSample/SimpleSampleServlet 200  POST /SimpleSample/SimpleSampleServlet HTTP/1.1

More Articles To Come , So Happy Coding....
Read More

Wednesday, June 23, 2010

Accessing A DataSource In Jboss EWS


JBoss web server provides a single deployment platform for all light weight java applications.it integrates Apache Tomcat, Apache Web Server and all of the common connectors.It provides deployment support for java server pages and java servlet technologies ,Php and CGI.It uses a genuine high performance hybrid technology that incorporates the best of the most recent OS technologies for processing high volume data, while keeping all the reference Java specifications.
In this articles we will see how we can access a DataSource Configured in Jboss Web Server by uisng Jndi.
The Sample application that we create connects to Microsoft Access using ODBC . JBoss web provides a Context implementation for all the web applications running under it.there are some elements that are to be configured in WEB-INF/web.xml in order to refer the resources.
Resources referenced in web.xml can be defined in 2 ways
either as a global resource which can defined in CATLINE_HOME/conf/context.xml or
for a application specific which is defined in Application/META-INF/context.xml

in this articles we will define the Datasource which connects to ODBC and defined it in CATLINE_HOME/conf/context.xml.
lets see how we can configure a ODBC DataSource .
  1. Click Start, point to Control Panel, double-click Administrative Tools, and then double-click Data Sources(ODBC).
  2. Click the User DSN tab, and then click Add.
  3. Select "Microsoft Access Driver" and Finish
  4. in Datasource name "mySource" and select the database "student".[ student is also   available to download]
5.    in advanced options provide the username and password which will  be used when defining the resource


Once datasource is configured , we will create the resource in CATLINE_HOME/conf/context.xml

<Resource name="jdbc/StudentDB" auth="Container"
            type="javax.sql.DataSource" username="jagadesh" password="jagadesh"
            driverClassName="sun.jdbc.odbc.JdbcOdbcDriver" url="jdbc:odbc:mySource"
            maxActive="8" maxIdle="4"/>

we just added a resource to the context.xml file which is now available to all applications and can be obtained by Jndi . lets see the Resource element

name=the name of the dataSource which is accessed from Jndi.
auth=Specify whether the web Application code signs on to the corresponding resource manager programatically, or whether the Container will sign on to the resource manager on behalf of the application. The value of this attribute must be
Application or Container.
type=the java class name which the application expects when it performs a lookup.
username=userrname to connect to datasource.
password=Password to connect to datasource.
driverClassName=Class name of the driver to connect.
url=the url to connect.
maxActive: Maximum number of dB connections in pool.
maxIdle: Maximum number of idle dB connections to retain in pool.

so now we have defined the Resource in the CATALINE_HOME/conf/context.xml file. we need to refer the resource in our web.xml file

so in web.xml we have ,

<resource-env-ref>
     <description>Data Source For MSAcess DataBase</description>
     <resource-env-ref-name>jdbc/StudentDB</resource-env-ref-name>
     <resource-env-ref-type>javax.sql.DataSource</resource-env-ref-type>
</resource-env-ref>

The resource-env-ref element contains a declaration of a Web application's reference to an administered object associated with a resource in the Web application's environment.

resource-env-ref-name - the resource reference name
resource-env-ref-type - the resource type

Now we have defined the resource and we also made a reference to the resource from our web application.now we will see how can we access the resource from the application code .

here is a simple serlvet to access the resource ,

package com.myCompany;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

/**
 * Servlet implementation class SamServlet
 */
public class SamServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
 
  
    static {
        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        } catch(ClassNotFoundException e) {
            System.err.println("JdbcOdbc Bridge Driver not found!");
        }
    }
  
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SamServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

       
        try {
            System.out.println("in Get Method");
          
           Context initCtx = new InitialContext();
            Context envCtx = (Context) initCtx.lookup("java:comp/env");
            DataSource bean = (DataSource) envCtx.lookup("jdbc/StudentDB");
          
            Statement st=bean.getConnection().createStatement();
            ResultSet myresult=st.executeQuery("select * from Details");

          
          while(myresult.next()){
                response.getWriter().println(myresult.getString(2).toString());
          }
          
            }catch(Exception e){
                e.printStackTrace();
            }
      
    }

      
    /** Creates a Connection to a Access Database */
    public static Connection getAccessDBConnection() throws SQLException {
        Connection con=null;
        try {
        con=DriverManager.getConnection("jdbc:odbc:mySource");
        }catch(Exception  e){
            e.printStackTrace();
        }
      
        return con;
    }
  
}

We have seen how we can configure a datasource in CATLINE_HOME/conf/context.xml file and refer it in the web.xml . we also seen how we can access the resource in application code.
Here are the Links to the Documents 
More Articles To Come , So Happy Coding....
Read More

Friday, June 11, 2010

Working With a Web Application in Maven


Working With a Web Application in Maven.

In This article , we will be seeing how we can create a sample web application in maven and deploy that in tomcat server .So we will start creating a web application in maven by executing the command ,

mvn archetype:generate -DgroupId=com.SampleWeb.WebApplication -DartifactId=WebApplication -Dpackage=com.SampleWeb.WebApplication -Dversion=1.0-SHAPSHOT

We will use archeTpye#19 for creating a web application in maven. Once we execute the command, we will see the POM file like this,

<project xmlns="http://maven.apache.org/POM/4.0.0” xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.SampleWeb.WebApplication</groupId>
  <artifactId>WebApplication</artifactId>
  <packaging>war</packaging>
  <version>1.0-SHAPSHOT</version>
  <name>WebApplication Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <finalName>WebApplication</finalName>
  </build>

</project>

So we have the POM file, now will see the directory structure 



We have web.xml in WEB-INF which contains,

<web-app>
  <display-name>Archetype Created Web Application</display-name>
</web-app>

Now we will add a simple servlet to the web application, for this we need to create the package as we defined in the command [for creating a web project above] .The structure looks like this after package creation.


So I have created the “SampleServlet” in web directory. We need to update the web.xml also like

 <web-app>
 <display-name>Archetype Created Web Application</display-name>
 <servlet>
<servlet-name>simple</servlet-name>
<servlet-class>com.SampleWeb.WebApplication.web.SampleServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>simple</servlet-name>
<url-pattern>/simple</url-pattern>
</servlet-mapping>
</web-app>

So now we will try to execute the command “mvn compile” to compile all the source files. This command throws the exception, since we don’t have the libraries available


[INFO] ------------------------------------------------------------------------
[ERROR] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Compilation failure

C:\WebApplication\src\main\java\com\SampleWeb\WebApplication\web\SampleServlet.java:[4,20] package javax.servlet does not exist

C:\WebApplication\src\main\java\com\SampleWeb\WebApplication\web\SampleServlet.java:[5,25] package javax.servlet.http does not exist

C:\WebApplication\src\main\java\com\SampleWeb\WebApplication\web\SampleServlet.java:[6,25] package javax.servlet.http does not exist

C:\WebApplication\src\main\java\com\SampleWeb\WebApplication\web\SampleServlet.java:[7,25] package javax.servlet.http does not exist


So for this we will make sure that maven downloads the required artifacts [jars] for compiling the source code. We need servlet-api.jar and jsp-api.jar. In order to make sure the jars are available to the maven, we need to make some modifications to the POM file like adding the dependencies. The complete POM looks like

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.SampleWeb.WebApplication</groupId>
  <artifactId>WebApplication</artifactId>
  <packaging>war</packaging>
  <version>1.0-SHAPSHOT</version>
  <name>WebApplication Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
           
<dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.4</version>
      <scope>provided</scope>
   </dependency>
           
<dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.0</version>
      <scope>provided</scope>
  </dependency>

  </dependencies>
 
  <build>
    <finalName>WebApplication</finalName>
  </build>
</project>  


I just added the dependencies for the servlet and jsp api.But how can we find the groupId,artifactID and version e.t.c. for these details go to

https://repository.sonatype.org/index.html#welcome and search for the necessary api like 




We have an artifact Search available, by which we can search the artifact by the name and many other ways. We can search for any type of artifact in this.

Once we made the changes to the POM file, we will once again run “mvn clean install” .once this executes it downloads all the necessary artifacts and compiles the source code, create a target directory and also creates a war file with the name specified in the finalName element in Build.

So now we have created a sample web application which contains a simple servlet.Now we will see how we can deploy the war file in Tomcat and Jetty Server using plug-ins.

Deploying an Application in Tomcat 

In order to deploy the application in tomcat, we need to make use of the tomcat plug-in.for using the tomcat plug-in we need to make some changes to the POM file for downloading the necessary plug-in. So add the plug-in element to the build element in POM file like

<build>
    <finalName>WebApplication</finalName>
            <plugins>
            <plugin>
                                                <groupId>org.codehaus.mojo</groupId>
                                                <artifactId>tomcat-maven-plugin</artifactId>
                                                <configuration>
                                                           <url>http://localhost:29801/manager/html</url>
                                                             <server>netcontrol</server>
                                                            <path>/simple</path>
                                                </configuration>
            </plugin>
            </plugins>
  </build>

So now we have added the plug-in, we need to run the install command to download the plug-in. so we execute the “mvn clean install”.This command makes sure to download the necessary tomcat plugin.lets see the configuration part in plug-in element for tomcat.
url : the url of the tomcat .
path is the web-path defined in the url-pattern of the web.xml.

The server element is the important thing, in order to provide the authentication to the tomcat server; we will create a server element in the setting.xml file which is in c: drive. Go for the user and look for .m2 directory which contains the setting.xml file. So once you find the file, add the servers element to the file like

<servers>
        <server>
            <id>netcontrol</id>
            <username>admin</username>
            <password>admin</password>
        </server>
  </servers>

We have specified a server name which has the user name and password for authentication. Now execute the “mvn -e clean tomcat:deploy” . so the info in the console may look like ,

mvn -e clean tomcat:deploy
+ Error stacktraces are turned on.
[INFO] Scanning for projects...
[INFO] Searching repository for plugin with prefix: 'tomcat'.
[INFO] ------------------------------------------------------------------------
[INFO] Building WebApplication Maven Webapp
[INFO]    task-segment: [clean, tomcat:deploy]
[INFO] ------------------------------------------------------------------------
[INFO] [clean:clean]
[INFO] Preparing tomcat:deploy
[INFO] [resources:resources]
[INFO] Using default encoding to copy filtered resources.
[INFO] [compiler:compile]
[INFO] Compiling 1 source file to C:\WebApplication\target\classes
[INFO] [resources:testResources]
[INFO] Using default encoding to copy filtered resources.
[INFO] [compiler:testCompile]
[INFO] No sources to compile
[INFO] [surefire:test]
[INFO] No tests to run.
[INFO] [war:war]
[INFO] Packaging webapp
[INFO] Assembling webapp[WebApplication] in [C:\WebApplication\target\WebApplication]
[INFO] Processing war project
[INFO] Webapp assembled in[63 msecs]
[INFO] Building war: C:\WebApplication\target\WebApplication.war
[INFO] [tomcat:deploy]
[INFO] Deploying war to http://localhost:29801/simple
[INFO] OK - Deployed application at context path /simple
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL

It deploys the web application at the /simple path and shows in the tomcat.for more information on tomcat plug-in, go to http://mojo.codehaus.org/tomcat-maven-plugin/

Some more articles coming, So Happy Coding…..
Read More

Monday, June 7, 2010

Maven Property References

 
In a daily application, properties play key roles in providing data at required time. In maven also we have a facility to set properties and access them at required places. We can access system, operating system specific properties also.

Maven properties are like place holders, they can be accessed anywhere in the POM file and can be accessed using ${x}, where x is a property to be accessed.

So in this article we will see how to access system and also user defined properties in Maven by creating a sample application,

First create a sample application

mvn archetype: generate -DgroupId=com.myCompany.VerySample -DartifactId= VerySample -Dpackage=com.myCompany.VerySample -Dversion=1.0-SNAPSHOT

And here are the contents of the POM file,

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.myCompany.VerySample</groupId>
  <artifactId>VerySample</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>VerySample</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>

So now we will create some properties in the POM file and access them. In order to set a property in maven we will use the property element as
I just added the myName property as

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
   <myName>jagadesh</myName>
  </properties>


So now we want to see the value defined for the myName property. How are we going to do this, for this we will use the maven-antrun plugin.we can use the echo of Ant to display the value of the property.

Maven AntRun Plug-in
Maven AntRun plug-in allows us to run ant tasks in Maven. This plug-in was introduced mainly to provide some help in migrating from Ant based projects to Maven.

So we will add the plug-in to the POM file like

<build>
            <plugins>
            <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-antrun-plugin</artifactId>
            <version>1.1</version>
            <executions>
                <execution>
                        <phase>validate</phase>
                            <goals>
                                    <goal>run</goal>
                             </goals>
                             <configuration>
                                    <tasks>
                                    <echo>Displaying value of 'myName' property</echo>
                                    <echo>[myName] ${myName}</echo>
                                    </tasks>
                            </configuration>
               </execution>
            </executions>
            </plugin>
            </plugins>
</build>


So we added a plug-in to the POM file and now we will now run a life cycle phase to test the property of the myName.so now we will execute the validate phase

“mvn validate” – since we are telling the antRun plug-in to execute at validate phase [see phase in execution]

We will see the following output

[INFO] [antrun:run {execution: default}]
[INFO] Executing tasks
     [echo] Displaying value of 'myName' property
     [echo] [myName] jagadesh
[INFO] Executed tasks
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL


We can the value of the myName displayed as “jagadesh”.

If we execute the command “mvn help:effective-pom” also we can see the value of the property defined .

Maven provides 3 variables by which we can access the maven properties

env – env variable is used to access the properties defined by the operating system or by shell like env.PATH .

project – this variable is used to access various information regarding the project like
project-artifactId , project-groupId.

Settings – this variable is used to access maven setting information like setting. activeProfile.

In addition to the above we can also access the system properties like java.HOME to access java home, os.name.

We have a properties plug-in for maven which reads the properties defined in the text file, refer - http://mojo.codehaus.org/properties-maven-plugin/

Here are some of the links about maven properties,

Some more articles coming, So Happy Coding…..










Read More