Thursday, August 11, 2011

Different ways to perform Sample URL handler Mapping in Spring


Normally the SimpleUrlHandlerMapping is done inside the xxx-servlet.xml file that is inside the WEB-INF directory of your Spring project. There are different ways to do this and two ways can be described as below.


Sample

Method 1

<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<value>
/account/register.jsp=flowController
</value>
</property>
<property name="alwaysUseFullPath" value="true"/>
</bean>



Method 2

<bean id="sampleMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key ="/account/register.jsp">
flowController
</prop>
</props>
</property>
<property name="alwaysUseFullPath" value="true"/>
</bean>


flowController is an another bean id and that bean is refered whenever the relevant URL request comes.


Regards
Chathuranga Tennakoon

How to create web application project using maven

today i decided to post how to create new web application project using maven. the following command should be typed in your linux vi editor for creating new project with maven. In linux terminal, go inside your project directory where the project source files should be created.then invoke the following command in the VI editor to create new project.


mvn archetype:generate -DgroupId=org.convery.example -DartifactId=SpringEmailInGmail  -DarchetypeArtifactId=maven-archetype-webapp -Dversion=1.0


the most importnat parameter can be described as belows.

-DgroupId this reffers to the Packaging path
-DartifactId this refes to the project id


once this command is executed, it will take few times to create new project. once the project is created you can see the newly created project structure as follows.

SpringEmailInGmail (as we have specified for the project name)
|------ pom.xml
|
|-------src
          |----main
                  |-----------resources
                  |
                  |-----------webapp
                                   |---------index.jsp
                             |
                                   |---------WEB-INF
                                                 |-----web.xml




hope this will helpful for you..

regards
Chathuranga Tennakoon
chathuranga.t@gmail.com

Ant script for j2me projects

<?xml version="1.0" encoding="UTF-8"?>


<project name="Test Runner" default="build">

<property name="wtk.home" value="C:/WTK2.5.2_01"/>
<property name="polish.home" location="C:/Program Files/J2ME-Polish" />
<property name="polish.vendor" value="chathuranga"/>
<property name="polish.name" value="pibt"/>
<property name="resource" value="C:/Documents and Settings/Administrator/scm/AbansSCM/resources"/>
<property name="polish.MenuBar.useExtendedMenuBar" value="true" />
   
<taskdef name="j2mepolish"
classname="de.enough.polish.ant.PolishTask"

classpath="${polish.home}/bin/classes:${polish.home}/lib/enough-j2mepolish-build.jar:${polish.home}/lib/jdom.jar"/>


<target name="build">


<j2mepolish>
<info

name="Test Runner"
version="13.0.0"
vendorName="chathuranga"
description="my final year project for Bsc degree in computing "
jarName="${polish.vendor}-${polish.name}-example.jar"
jarUrl="${polish.jarName}"
permissions="javax.microedition.io.Connector.http">
   
</info>
   
   
<deviceRequirements>
<requirement name="Identifier" value="Generic/AnyPhone"/>
</deviceRequirements>

<build resDir="${resource}"

fullscreen="menu"
usePolishGui="true">

<midlet class="MenuMidlet" name="Test Runner"/>
   
</build>

</j2mepolish>

   
</target>


<target name="clean" >
<delete dir="build"/>
<delete file="${polish.vendor}-${polish.name}-example.jar"/>
<delete file="${polish.vendor}-${polish.name}-example.jad"/>
<delete file="${polish.jarName}"/>

</target>

<target name="rebuild" depends ="clean,build">
</target>


<target name="run">
   
<exec executable="${wtk.home}/bin/emulator">
<arg line="-Xdescriptor:dist/${polish.vendor}-${polish.name}-example.jad"/>
</exec>
</target>


</project>

Monday, August 8, 2011

Apache Ant for building and Deploying Java Web Applications

 The following Ant Script can be used to build your web application and deploy it in the remote server. it is required to change the value of the properties based on their actual paths available in your server and development environment. the following Ant Script should be copied to the build.xml file that is available inside the root of your java web project directory. (if there is no build.xml file, you can just create it and copy the below codes to there )


<project name="myproject" default="all">

    <target name="init">
       
        <property name="server_home" value="C:/Program Files/Apache Software Foundation/Tomcat 6.0"/>
        <property name="server_deploy" value="${server_home}/webapps"/>
        <property name="servlet_jar" value="${server_home}/lib/javax.servlet.jar"/>
        <property name="outdir" value="./output"/>
        <property name="classes" value="${outdir}/webclasses"/>
        <property name="lib" value="${outdir}/lib"/>
        <property name="project_name" value="jdbc"/>
               
    </target>

    <target name="prepare" depends="init">
   
        <mkdir dir="${outdir}"/>
        <mkdir dir="${classes}"/>
        <mkdir dir="${lib}"/>
   
    </target>

    <target name="compile" depends="prepare">
             <echo>${servlet_jar}</echo>
        <javac srcdir="./src" destdir="${classes}">
            <classpath>
                <pathelement location="${servlet_jar}"/>
            </classpath>
        </javac>
 </target>

    <target name="package" depends="compile">
        <jar destfile="${lib}/lib.jar" basedir="${classes}" includes="**/data/*.*"/>
        <war destfile="${outdir}/${project_name}.war" webxml="./WebContent/WEB-INF/web.xml">
            <fileset dir="./WebContent"/>
            <classes dir="${classes}">
           
            </classes>
            <lib dir="${lib}"/>
        </war>
    </target>

    <target name="deploy" depends="package">
        <copy file="${outdir}/${project_name}.war" todir="${server_deploy}"/>
              
    </target>

    <target name="clean" depends="init">
        <delete dir="${outdir}"/>
        <delete file="${server_deploy}/${project_name}.war"/>
    </target>

    <target name="all" depends="clean, deploy">

   </target>


</project>

Solving Package javax.servlet does not exist Error using Eclipse and Ant


Suppose you are working on a web application project with Eclipse IDE, Apache ant and Tomcat server. When you compile and run the program you will get the following error saying that Servlet.jar API cannot be found.

Package  javax.servlet  does not exist

This error will get even if the servlet.jar API is available in the lib directory of the Tomcat web container. The reason for this error is you have not set the CLASSPATH environmental variable for referring javax.servlet API. In addition you have not set the Apache Ant run time class path to javax.servlet API.
You can follow the instructions given below to set both the classpaths properly.

1. Setting up CLASSPATH environmental variable.

 Right Click on My Computer -> Properties -> Advanced tab -> Environment Variables
(In that you can amend/create CLASSPATH environment variable to servlet.jar
(In my case, CLASSPATH=C:/Program Files/Apache Software Foundation/Tomcat 6.0/lib/javax.servlet.jar )

2. Setting up Apache Ant runtime classpath

In addition, it is required to include the javax.servlet API (servlet.jar ) into the Apache Ant runtime. This can be done using your Eclipse IDE as follows.
Click on Window menu -> preferences -> Ant -> Runtime -> Global Entries
(In this location, you can add the servlet.jar API to the Apache Ant runtime as an external JAR file).


if you follow the above instructions properly,  you should be able to compile and deploy your web application without having such compilation error.

Thursday, July 28, 2011

CAS (Centralized Authentication Service) Introduction


CAS is a Java based open source SSO (Single Sign On) solution originally developed by the Yale University. You can just have a Google search to find more on CAS and SSO. The official CAS web page is http://www.jasig.org/cas and you can download the CAS server from there.  Today I am going to give a brief description about how to deploy the CAS server application in your web server.
CAS is built on Spring Web Flow framework and Apache Maven has been used as the building tool. Therefore if you are going to re build/modify the CAS distribution, it is required to install Apache Maven and Spring web flow in your development environment. In addition, I am going to deploy the CAS sever application in the apache Tomcat server. Therefore it is good if you have installed following software prior to download and deploy CAS server.
  • Java
  • Apache Tomcat
  • Apache Maven
  • Spring Web Flow


CAS Server is available to download at http://www.jasig.org/cas/download . It is good if you download the latest version of the CAS server distribution. In my case, I have downloaded the cas-server-3.4.10 version. Once the download is completed, extract the CAS server zip file and you will get the CAS server directory with all available modules. Those modules are included in the CAs server directory as follows.





In order to deploy the CAS server application in your tomcat server, we need to work with the cas-server-webapp module.  That module should be built to get the deployable CAS server web application module (known as war file). You can follow the below steps to build the CAS server web application.( Use command prompt (in wndows) or terminal/vi editor (in linux) to build the cas-server-webapp module.)

1. go to the cas-server-webapp directory using your command prompt.

 In my case, C\cas-server-3.4.10\cas-server-webapp\

2. You can see the standard directory structure of the maven module and you are required to build the module using  Apache maven. In order to build the module, use the following command.

C\cas-server-3.4.10\cas-server-webapp\ mvn clean install
It will take few times to build the application module because; the required dependencies (as declared in the pom.xml file) should be downloaded from the maven repositories. Once the module is built, you can see a newly built directory called target. Inside the target directory, you will find the cas.war file. This file should be deployed in the webapps ($CATALINA_HOME/webapps) directory of the tomcat installation. After deploying the cas.war file, make sure to restart the tomcat server for reflecting the newly deployed web applications. (Even you can use the touch command also)


3. Now you can access the CAS server application as a web application hosted in your tomcat server.

http://localhost:4287/cas (i have changed the tomcat port from 8080 to 4287. This is because my 8080 port is used by some other application installed in my pc. You are not required to change it and you can use your default port that is 8080)

4. Then you will see the CAS login screen and it requests for your username and password. The CAS in built version authenticates the user credentials using through a simple authentication handler implemented by them. Therefore you have to type the same value for both username and password.

The class definition is available at : org.jasig.cas.authentication.handler.support.SimpleTestUsernamePasswordAuthenticationHandler

5. Once you are successfully authenticated, you will be displayed a login success page. Then open  a new tab and try to login again.

You will again see the login screen even if you have successfully logged in using previous tab. In order to avoid this situation, it is required to make the below configuration to the cas-server-webapp/src/main/webapp/WEB-INF/spring-configuration/TicketGrantingTicketCookieGenerator.xml file. Change the p:cookieSecure="true" property value to the p:cookieSecure="false". Then re-build the application and deploy it in tomcat server. Try to login again using two tabs. The problem may not occur anymore.


The next post will be how to integrate facebook login Authentication system with CAS server to make use of the facebook login for your website login.

Regards 
Chathuranga Tennkoon 

Wednesday, July 20, 2011

JAR Signing and Verification


In order to make your J2ME mobile application trusted, it has to be digitally signed. I have realized that the most of the J2ME developers do not know how to digitally sign a MIDlet suite to add it to the trusted domain. Today I am going to discuss a lengthy article on how to sign jar file. 

It is possible to use jarsigner utility for signing the JAR file digitally. Jarsigner is a utility that comes by default with the installation of the JDK (Java Development Kit). First open the command prompt and enter the command called jarsigner to check whether the jarsigner utility is available and ready to be used. Sometimes you will get the following error that says that jarsigner cannot be recognized as a command. If you do not get this error, you will be ended up by showing a list of commands available under the jarsigner utility.





The reason for this error is you have not set the class path for the java in your command prompt (This can be verified by invoking the javac command in the command prompt). Therefore it is required to set the class path for the JDK as follows.




 Once the class path is set, the availability of the jarsigner utility should be verified again. Type jarsigner and press enter in the command prompt. You will see a list of commands available under the jar signer utility as follows.




Now it is possible to use the jarsigner utility to digitally sign your selected JAR file. Before signing the digitally signing process you may require to check whether the JAR file has already been signed or not. In oder to do this fist go into the directory where the relevant jar file is stored (In my case it is stored inside E:\J2ME>).then the verification can be done with the following command.
jarsigner -verify YourjarFieName.jar

 If the verification is successful and the JAR file is already signed, the following message will be displayed.
jar verified.
 
Otherwise it will display the following error message to indicate the JAR file verification process is failed and JAR  file is unsigned.



If it is unsigned, then you can start the signing process as below.

First it is required to create a set of keys that will be used for both JAR file signing process and the JAR file verification process.  The following command can be used to create a keystore with key entries.

keytool -genkey -alias your-alias-name -keystore your-keystore-name

In my case, I used the following command to create a keystore with key entries.

keytool -genkey -alias chathurangaAlias -keystore chathurangaKeyStore


Then it prompted set of questions and those were answered as below.


 
Note: I have used 123456 as the password for both keystore and alias. 

    What is your first and last name?
      [Unknown]:  Chathuranga tennakoon
    What is the name of your organizational unit?
      [Unknown]:  IT Department 
    What is the name of your organization?
      [Unknown]:  Chathuranga (pvt) Ltd 
    What is the name of your City or Locality?
      [Unknown]:  colombo
    What is the name of your State or Province?
      [Unknown]:  western province
    What is the two-letter country code for this unit?
      [Unknown]:  sl 
    Is <CN=Chathuranga tennakoon, OU=IT Department, O=Chathuranga (pvt) Ltd,
        L=colombo, ST=colombo, C=sl > correct?
      [no]:  yes


If you successfully answer all the questions then it will create the keystore file in your current working directory with the given keystore name. In my case, the keystore file has been created in my current working directory as chathurangaKeyStrore.


After successfully creating the keystore file, it is the time to sign the JAR file using jarsigner utility. It can be done by using the following command.

jarsigner -keystore keystore-name -storepass keystore-password 
-keypass key-password jar-file alias-name




Once the jar file is digitally signed, it will display the validity period of the certificate as displayed above. If you need to verify whether the JAR file has been successfully signed, you can use the following command as mentioned at the starting of this article.

    jarsigner -verify YourjarFieName.jar 




Then you can see that the message that says jar verified. That means the JAR file has been successfully signed.

Monday, July 18, 2011

Touch Screen Devices programming with J2ME


There is no specific way to code for j2ME application that should run on touch screen devices. The touch screen behavior is almost determined by the implementation of the device. That means it is the responsibility of the device to recognize the touch events (touch screen events) and response for them appropriately. However there are set of things that might be useful for you when developing applications for touch screen devices.
  

  You might be using Sun Java Wireless Tool kit as the mobile emulator/simulator for testing the application in the development environment. You may have noticed that the emulators available under the Sun Java Wireless Toolkit are no touch supported emulators. Therefore you can follow the steps given below to make them touch enable emulators.


Steps

  •      Go to the installation directory  of the Sun Java Wireless Toolkit installation. Under that directory go to wtklib ---> devices directories.  In my case, C:\WTK2.5.2_01\wtklib\devices. Then you will see a set of directories as below with the names of the mobile emulators available






  •         Then open one of the directory (Mobile Simulator) and open the properties file available for that simulator.

In my case, I have selected DefaultColorPhone Simulator and opened the DefaultColorPhone.properties file under that. The property file contains the properties of the Mobile Simulator. In order to enable the touch screen event of the selected simulator, change the touch_screen=true as the properties file. Otherwise make it as false. Once it is done, the emulator/simulator will be touch screen enabled.



  Make sure that you are going to build the application (JAR file and JAD file) targeting the type of the device that is  Generic/AnyPhone. This will make sure that you application will be run on both touch screen and non touch screen devices properly. This can be done by adding the following code segment for the Ant script (build.xml) of your Mobile Application.

<deviceRequirements>
<requirement name="Identifier" value="Generic/AnyPhone"/>
</deviceRequirements>


Sunday, July 17, 2011

Deploying J2ME Applications on Windows Mobile


These days I am working on a J2ME based mobile application development project and that mobile application is required to be deployed in a PDA (Personal Digital Assistant) where the Windows Mobile 6.1 Operating System available. Even if I have developed and deployed mobile application for wide range of java enabled mobile devices that are manufactured by leading mobile manufactures  Nokia, Sony Ericson etc…, I was little bit confused in this case. This is because I have never had experience on deploying J2ME applications for the PDA devices whose operating system is Windows Mobile. However after a lengthy study of internet materials, eBooks and so on.., I was able to run the Mobile Application on the PDA successfully.  Finally I decided to share my experience on this mobile development with others because; this might be useful for some of you at some point of your career. It is important to note that the deploying J2ME application on Windows Mobile Device is only a deployment time/level effort (not a development time effort). Therefore you are free to develop the mobile application in your development environment using one of the mobile emulator/simulator as wish. Once it is developed, it can be deployed in any device where the Windows Mobile OS operates. The following tutorial shows you how to deploy it.
First download the JavaFX mobile (latest version) for the Windows Mobile. It is available to be downloaded at the following site. It will be easy to install if you download this software from your PDA web browser. This is because the JavaFX should be installed in your PDA device.


Once the download is completed, just open the file and browse it.  The file is in the Zip format and you will be able to see a file called SUN_JAVAFX.CAB under that zip file. Please refer the below screenshot.


Once the SUN_JAVAFX.CAB is fond, double click on it to launch the JavaFX application installer. It will ask for your permission to continue with the installation process and click on YES to proceed. Please refer the below screenshot.


 
Once the permission is granted to proceed with the installation process, it will prompt another screen to select the storage location for JavaFx application installation. Please refer the below screenshot.




After selecting the storage location, click on Install to start the installation process. It will display below screen to indicate the carrying out of the installation process.


 
If the installation process is successfully completed, the below screen should be displayed.



Now the JavaFX is successfully installed in your PDA and it is ready to launch. In order to launch it, open the Programs of the PDA. Then you will see an icon called JavaFX. Double click on it. Please refer the below screenshot.



 
Once the JavaFX application is launched, it will display the below screen. You can see that there are set of sample applications are available. (e.g.:- calculator application) You can just double click on one of the sample application and have a look at it. Please refer the below screenshot.

Now we are ready to deploy our application which is build using J2ME on our PDA device. Io order to install your application, it is required to have related JAR and JAD file for that application. In my case, I transferred those two files using my email (GMAIL).  I attached those two files to email. Then I access that email from the web browser available in the PDA. I just click on the JAD file and it launches the application installer. It asks for my permission to continue with the installation. Once the permission is granted, it asks for the installation location of the application (select your decided location for the application).In my case, I selected root as the installation location. This took few minutes to complete the installation. Once the installation is completed, the application can be started by double clicking the JavaFX icon under the programs section. Please refer the below screenshot.





Important:-
If the application is modified, then it will be required to install the newly modified version of the Mobile application on the PDA. In order to o this you have to re-install the install the application in your PDA. When building the JAR file and JAD file for the re-installation, make sure that you have changed the version number of the mobile application. Otherwise the PDA will discard the installation process because, the application version that you are trying to install is already available in the PDA. The application version should be changed in the JAD file. If you are using the Apache Ant ,it may be required to change  the application version in the build.xml file too. Therefore please make sure that the JAD file version is reflected in the build.xml file.


Friday, March 18, 2011

Indexing in Database


indexes are used to speed up the data retrieving queries known as select queries. Indexes are created on a per column basis. If you have a table with the columns: name, age, birthday and employeeID and want to create an index to speed up how long it takes to find employeeID values in your queries, then you would need to create an index for employeeID. When you create this index, MySQL will build a lookup index where employeeID specific queries can be run quickly. However, the where clause based on the  name, age and birthday queries would not be any faster.

Indexes are something extra that you can enable on your MySQL tables to increase performance,but they do have some downsides. When you create a new index MySQL builds a separate block of information that needs to be updated every time there are changes made to the table. This means that if you are constantly updating, inserting and removing entries in your table this could have a negative impact on performance.


Advantages 
  • Indexes speed up the data retrieving based on where and order by clauses
Disadavantages
  •  Indexes slow down inserts , update and deleted, so you want to use them carefully on columns that are FREQUENTLY changed.
  •  Creating an index requires an additional storage space . this space is occupied by the look-up index and it keep a track of modification(insert/delete/update) records those were done to the related column/field. therefore too many indexes can increase the database size and the file size unnecessarily.

create mysql index on new table

 If you are creating a new MySQL table you can specify a column to index by using the INDEX term as we have below. We have created two fields: name and employeeID (index).

CREATE TABLE employee (
 name VARCHAR(50), 
 employeeID INT, INDEX (employeeID)
)
 
 
create mysql index on existing table

CREATE INDEX id_index ON employee(employeeID)
 
Hope this will helpful for you!

regards
Chathuranga Tennakoon
chathuranga.t@mail.com

Saturday, March 12, 2011

Enable HTTPS in Apache Tomcat server

I have assumed that you have properly installed Apache tomcat server and it is perfectly running on HTTP protocol.if you don't know how to install Apache tomcat , you can refer my previous blog post on  Installing Apache Tomcat .In order to configure HTTPS support in the tomcat server, you are required to folllow the steps given below.

1. it is required to have a self-signed server certificate for https. therefore you have to use keytool utility to generate such certificate for your tomcat server. type the keytool command in the command prompy \t to check whether the key tool utility is working.

C:\> keytool

if it is working, it should display a list of commands that are owned to the keytool utility. otherwise it will show you an error message indicating that keytool is not recognized as an internal or external command. if you get such error message, the reason is exactly you have not set JDK/JRE classpath in your command prompt. in such case, it is required to append C:\Program Files\Java\jdk1.6.0\bin (in my case) to the end of the path environment variable. then it will run the keytool utility properly.

Environment Variable
path = C:\Program Files\Java\jdk1.6.0\bin

2. then type the following command in the command prompt for generating the server certificate.

keytool -genkeypair -alias tomcat -keyalg RSA -keysize 1024 -dname "CN=localhost, OU=Organization, O=Company Name, L=City, S=State, C=US"
-validity 365 -keystore keystore

Enter keystore password: <enter a new password here>

 
Enter key password for <tomcat>

        (RETURN if same as keystore password): <just hit enter here>


The password you enter in the first password prompt will be the password for the keystore where your server certificate is stored.

3.Next, edit your Tomcat's conf/server.xml to enable the HTTPS connector. Look for a connector that looks like this:

    <!--
    <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" />
    -->


by default, this has been commented and you are required to remove the comment.

Wednesday, March 9, 2011

Installing Apache Maven in Windows Environment

Apache Maven is a java based project build and automation tool. since it is java based, it is required to have a valid JDK version prior to proceed with the Maven installation.Apache maven can be downloaded through Apache maven official website.  Here i am downloading and installing the Apache maven 3.0.3 version.  please follow the instructions given below for installing Maven in your windows based development environment.

 1. extract the downloaded ZIP file and copy the extracted directory (In my case, apache-maven-3.0.3 directory  ) to the C:\Program Files

2. then create the following environment variables

  M2_HOME ( values refers to the maven home directory e.g:-  C:\Program Files\apache-maven-3.0.3 )
  M2 ( value refers to the maven binary directory e.g:- C:\Program Files\apache-maven-3.0.3\bin )
  path (if this variable already exists, please append this value to the end - %M2%)

 3. now the maven is installed to your computer and you can check it through the command line as follows.

   mvn --version


 hope this will helpful for you !

regards
Chathuranga Tennakoon
chathuranga.t@gmail.com