Showing posts with label Technical. Show all posts
Showing posts with label Technical. Show all posts
Wednesday, January 2, 2013
Monday, October 17, 2011
Are you thinking Y 3389 as default RDP port?? Lets chage it ..!!
To do this we need little bit knowledge on windows registry. If you are not aware of registry just follow my steps blindly.
1. Goto Registry Editor (Ctrl+R and type regedit).
2. Find the PortNumber registry subkey in HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\TerminalServer\WinStations\RDP-Tcp\PortNumber
3. On the Edit menu, click Modify, and then click Decimal.
4. Type the new port number, and then click OK.
5. Quit Registry Editor.
6. Restart the computer.
Dont complain me about these steps are copied .. Yes it is copied from MSDN. here is the link change RDP default port
1. Goto Registry Editor (Ctrl+R and type regedit).
2. Find the PortNumber registry subkey in HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\TerminalServer\WinStations\RDP-Tcp\PortNumber
3. On the Edit menu, click Modify, and then click Decimal.
4. Type the new port number, and then click OK.
5. Quit Registry Editor.
6. Restart the computer.
Dont complain me about these steps are copied .. Yes it is copied from MSDN. here is the link change RDP default port
Thursday, January 13, 2011
Generate MD5 hash to a given string -- java
Yesterday I had a requirement to compute MD5 hash for a particular string to validate in my code. A quick googling I got lot of sources. Here I am posting the code which I worked out.
public class MD5Hash {
public static void main(String args[]) {
try {
String md5Hash = MD5("Give String");
System.out.println("MD5 hash is : " + md5Hash);
} catch(Exception e) {
//TODO: Nothing
}
}
private static String convertToHex(byte[] data) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < halfbyte =" (data[i]">>> 4) & 0x0F;
int two_halfs = 0;
do {
if ((0 <= halfbyte) && (halfbyte <= 9))
buf.append((char) ('0' + halfbyte));
else
buf.append((char) ('a' + (halfbyte - 10)));
halfbyte = data[i] & 0x0F;
} while(two_halfs++ < 1);
}
return buf.toString();
}
private static String MD5(String text) throws Exception {
MessageDigest md;
md = MessageDigest.getInstance("MD5");
byte[] md5hash = new byte[32];
md.update(text.getBytes("iso-8859-1"), 0, text.length());
md5hash = md.digest();
return convertToHex(md5hash);
}
}
public class MD5Hash {
public static void main(String args[]) {
try {
String md5Hash = MD5("Give String");
System.out.println("MD5 hash is : " + md5Hash);
} catch(Exception e) {
//TODO: Nothing
}
}
private static String convertToHex(byte[] data) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < halfbyte =" (data[i]">>> 4) & 0x0F;
int two_halfs = 0;
do {
if ((0 <= halfbyte) && (halfbyte <= 9))
buf.append((char) ('0' + halfbyte));
else
buf.append((char) ('a' + (halfbyte - 10)));
halfbyte = data[i] & 0x0F;
} while(two_halfs++ < 1);
}
return buf.toString();
}
private static String MD5(String text) throws Exception {
MessageDigest md;
md = MessageDigest.getInstance("MD5");
byte[] md5hash = new byte[32];
md.update(text.getBytes("iso-8859-1"), 0, text.length());
md5hash = md.digest();
return convertToHex(md5hash);
}
}
Friday, November 26, 2010
Set default profile in Outlook
When you start Outlook 2007 it will prompt you dialog box to select outlook profile, On bottom if you click options it will show you "Set as default profile". We thought of next time onwards it will not ask for seleting profile if you select this option. But every time when you start outlook it will prompt you to select profile. MS saying that this behaviour is by design.
If you want to set default profile follow these easy steps. It means it will not ask to select profile every time you start outlook.
1. Click Start, and then click Control Panel.
2. In Control Panel, double click Mail.
3. In the Mail Setup dialog box, click Show Profiles.
4. Click Always use this profile radio button option, and then select the profile that you want to use as the default profile in drop down list.
5. Click Apply and OK.
If you want to set default profile follow these easy steps. It means it will not ask to select profile every time you start outlook.
1. Click Start, and then click Control Panel.
2. In Control Panel, double click Mail.
3. In the Mail Setup dialog box, click Show Profiles.
4. Click Always use this profile radio button option, and then select the profile that you want to use as the default profile in drop down list.
5. Click Apply and OK.
Tuesday, November 16, 2010
How to stop VNC service starting at windows startup?
Q : Recently I installed VNC server in my desktop for some R&D purpose,I am done with this tool. But every time when system is up the service will automatically started eventhough I really don't need it. I searched windows startup menu, VNC service not listed here. How can I stop VNC server strating at windows startup?
Sol :
1. Go to Run --> type services.msc and press enter.
2. It will propmt you system services. Search for VNC Server.
3. Right click on VNC Server and modify start type as Manual from Automatic.
thts it ..
Sol :
1. Go to Run --> type services.msc and press enter.
2. It will propmt you system services. Search for VNC Server.
3. Right click on VNC Server and modify start type as Manual from Automatic.
thts it ..
Wednesday, October 6, 2010
Useful Eclipse plugin
Hi bloggers this time I came up with an interesting and useful JD-Eclipse plugin. Two days back my team leader tell us about this tool. Actually while debugging the java code in eclipse, If you are using any thirdparty libs then you can't access that code to debug. Using JD-Eclipse plugin we can also debug third party class files. For more details please check here JD-Eclipse. It is very easy to install this plug in, you will get all details about JD-Eclipse in the link I provided.
Tuesday, September 21, 2010
VMWare-tools installation in Linux/Windows VMs
Before yesterday I tried to install VMWare-tools in windows/linux VMs in my local VMserver. It is very simple and easy to do. In this post I will explain this procedure step by step with screen shots.
Windows : Installing VMware-tools in windows VM is very simple. Right click on VM and select Guest and click on Install/Upgrade VMware Tools option. It will prompt you warning message . Click Ok. Before doing above things open console view of the VM. Now you will see prompt on console as see pic-2. Read the instructions carefully and finish the installation.
Pic-1

Pic -2

Linux[GUI] : Installing VMware-tools in Linux GUI is also very simple. Right click on VM and select Guest and click on Install/Upgrade VMware Tools option. It will propmt you warning message . Click Ok. Before doing above things open console view of the VM. Now you will see prompt on console as see pic-3. Click on VMwaretools...rpm. Read instructions carefully and finish the installation.
Pic-3

Linux [Text mode] :Installing VMware-tools in Linux text mode is little bit difficult compare to GUI. Follow the steps carefully.
Right click on VM and select Guest and click on Install/Upgrade VMware Tools option. It will prompt you warning message . Click Ok.Open the console view and proceed as below.
1. First mount the CDROM using cmd mount /dev/cdrom /mnt .
2. Check whether it is mounted or not using cmd ll /mnt, If it is mounted correctly then you will see file VMwareTools-4.0.0-208167.tar.gz.
3. Create temporary dir to proceed installation from here .. mkdir /tmp/vmtools
4. Go to /tmp/vmtools.
5. Untar /mnt/VMwareTools-4.0.0-208167.tar.gz in /tmp/vmtools by run the cmd tar -xzvf /mnt/VMwareTools-4.0.0-208167.tar.gz. Now you will find one dir named vmware-tools-distrib.
6. In vmware-tools-distrib dir you will find one perl script file named vmware-install.pl. Run the perl script file. here 2 ways to proceed. If you run the script using cmd
a. perl vmware-install.pl --default : it will install without asking any further confirmation from you.
b. perl vmware-install.pl : This cmd will start install and ask your confirmation for each step. Read each confirmation and proceed[Simply say yes for all].
Windows : Installing VMware-tools in windows VM is very simple. Right click on VM and select Guest and click on Install/Upgrade VMware Tools option. It will prompt you warning message . Click Ok. Before doing above things open console view of the VM. Now you will see prompt on console as see pic-2. Read the instructions carefully and finish the installation.
Pic-1
Pic -2
Linux[GUI] : Installing VMware-tools in Linux GUI is also very simple. Right click on VM and select Guest and click on Install/Upgrade VMware Tools option. It will propmt you warning message . Click Ok. Before doing above things open console view of the VM. Now you will see prompt on console as see pic-3. Click on VMwaretools...rpm. Read instructions carefully and finish the installation.
Pic-3
Linux [Text mode] :Installing VMware-tools in Linux text mode is little bit difficult compare to GUI. Follow the steps carefully.
Right click on VM and select Guest and click on Install/Upgrade VMware Tools option. It will prompt you warning message . Click Ok.Open the console view and proceed as below.
1. First mount the CDROM using cmd mount /dev/cdrom /mnt .
2. Check whether it is mounted or not using cmd ll /mnt, If it is mounted correctly then you will see file VMwareTools-4.0.0-208167.tar.gz.
3. Create temporary dir to proceed installation from here .. mkdir /tmp/vmtools
4. Go to /tmp/vmtools.
5. Untar /mnt/VMwareTools-4.0.0-208167.tar.gz in /tmp/vmtools by run the cmd tar -xzvf /mnt/VMwareTools-4.0.0-208167.tar.gz. Now you will find one dir named vmware-tools-distrib.
6. In vmware-tools-distrib dir you will find one perl script file named vmware-install.pl. Run the perl script file. here 2 ways to proceed. If you run the script using cmd
a. perl vmware-install.pl --default : it will install without asking any further confirmation from you.
b. perl vmware-install.pl : This cmd will start install and ask your confirmation for each step. Read each confirmation and proceed[Simply say yes for all].
Thursday, September 9, 2010
Integrating hibernate to java web application
This post is continuation to my last post "Sample web application using struts framework". In this post we will see how to integrate hibernate to our sample web application .
Application : My application is simple login page with server side validation and verify the login details from DB and render success/failure page. I used Mysql as DB.
Step 1 : Setup in Eclipse:
=================
Please create the setup as specified in previous post and add the following additional things.
1. Additional sub folder structure
A. Create src dir structure
i. Login/src/com/srini/model
ii. Login/src/com/srini/model/hbm
iii. Login/src/com/srini/hibernate
iv. Login/src/com/srini/db
2. Addtional Files needs to be create
i. hibernate.cfg.xml [Login/src/com/srini/webapp/WEB-INF/classes]
ii. Login.java [Login/src/com/srini/model]
iii. Login.hbm.xml [Login/src/com/srini/model/hbm]
iv. HibernateSessionFactory.java [Login/src/com/srini/hibernate]
v. mysql_users.sql [Login/src/com/srini/db].
vi. mysql_dbscript.sql [Login/src/com/srini/db]
vii. LoginAction [Login/src/com/srini/action] -- This class is modified
3. Additional Dependency jars :
i. asm.jar
ii. cglib-2.1.jar
iii. dom4j-1.6.jar
iv. ehcache-1.1.jar
v. hibernate3.jar
vi. jaxen-1.1-beta-4.jar
vii. jta.jar
viii. mysql-connector-java-3.1.12-bin.jar
Application : My application is simple login page with server side validation and verify the login details from DB and render success/failure page. I used Mysql as DB.
Step 1 : Setup in Eclipse:
=================
Please create the setup as specified in previous post and add the following additional things.
1. Additional sub folder structure
A. Create src dir structure
i. Login/src/com/srini/model
ii. Login/src/com/srini/model/hbm
iii. Login/src/com/srini/hibernate
iv. Login/src/com/srini/db
2. Addtional Files needs to be create
i. hibernate.cfg.xml [Login/src/com/srini/webapp/WEB-INF/classes]
ii. Login.java [Login/src/com/srini/model]
iii. Login.hbm.xml [Login/src/com/srini/model/hbm]
iv. HibernateSessionFactory.java [Login/src/com/srini/hibernate]
v. mysql_users.sql [Login/src/com/srini/db].
vi. mysql_dbscript.sql [Login/src/com/srini/db]
vii. LoginAction [Login/src/com/srini/action] -- This class is modified
3. Additional Dependency jars :
i. asm.jar
ii. cglib-2.1.jar
iii. dom4j-1.6.jar
iv. ehcache-1.1.jar
v. hibernate3.jar
vi. jaxen-1.1-beta-4.jar
vii. jta.jar
viii. mysql-connector-java-3.1.12-bin.jar
4. Modify 'server.xml' file : This is to specify your DB details and add docBase so that when you hit the url http://localhost:8080, it will automatically run your web application. Add the Context tag to server.xml file in tomcat conf dir. Add the following code with in Host tag . Modify the context path to your server path.
The configuration looks like
<Context path="" docBase="C:/Program Files/Apache Software Foundation/Tomcat 5.5/webapps/login" privileged="true" antiResourceLocking="false" antiJARLocking="false"> <Resource name="jdbc/struts" auth="Container" type="javax.sql.DataSource" maxActive="100" minIdle="10" maxIdle="30" maxWait="10000" username="struts" password="struts" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://127.0.0.1/struts?useUnicode=true&characterEncoding=utf8&autoReconnect=true" logAbandoned="true" validationQuery="SELECT 1" removeAbandoned="true" testOnBorrow="true" testWhileIdle="true" timeBetweenEvictionRunsMillis="10000" minEvictableIdleTimeMillis="180000" removeAbandonedTimeout="60" /> </Context>
5. Modify 'login-build.xml' file : Modify ant build script slightly to add hibernate related changes.
i. Add new target 'copy.hbm.files '.
<target name="copy.hbm.files" >
<copy todir="${build}/${name}/WEB-INF/classes/com/srini/model/hbm">
<fileset dir="${login.src.root}/src/com/srini/model/hbm">
<include name="*.xml"/>
</fileset>
</copy>
</target>
ii. Add new target to dependents list in compile target.
<target name="compile" depends="init, copy.login.webapp, copy.hbm.files" >
iii. Add additional jars to classpath.
Step 2 : Each file description and code inside the file :
============================================
1. hibernate.cfg.xml : Hibernate uses the hibernate.cfg.xml to create the connection pool and setup required environment. Hibernate uses the Plain Old Java Objects (POJOs) classes to map to the database table. We can configure the variables to map to the database column.
The configuration looks like
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://127.0.0.1/struts?useUnicode=true&characterEncoding=utf8&autoReconnect=true</property>
<property name="hibernate.connection.username">struts</property>
<property name="connection.password">struts</property>
<property name="connection.pool_size">1</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping resource="com/srini/model/hbm/Login.hbm.xml"/>
</session-factory>
</hibernate-configuration>
I think you are already knew the first 6 properties. If 'show_sql' property is 'true' then it will write all SQL statements to console. <mapping resource="com/srini/model/hbm/Login.hbm.xml"/> property is the mapping for our login_details table.
2. Login.java : This is model class to map table.
package com.srini.model;
/**
* @author srinut096@gmail.com
*
*/
public class Login {
private int id;
private String name;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
3. Login.hbm.xml : This file is used to map Login Object to the login_details table in the database.
The configuration looks like
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.srini.model">
<class name="Login" table="login_details">
<id name="id" unsaved-value="0">
<generator class="native"/>
</id>
<property name="name" type="string" column="name"/>
<property name="password" type="string" column="password"/>
</class>
</hibernate-mapping>
The hibernate-mapping element is the root element. The class element is used to map the Java class with the database table. The Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute of the class element. The id element is used to create the primary key. The name attribute of the id element refers to the property in the Login class and the column attribute refers to the column in the login_details table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type and vice versa. The generator element within the id element is used to automatically generate the primary key values. When the class attribute of the generator element is set to native, hibernate picks either identity, sequence or hilo algorithm depending upon the capabilities of the underlying database. The property element is used to link a property in the Java class to a column in the database table.
4. HibernateSessionFactory.java : This class helps in creating the SessionFactory from the Hibernate configuration file(it automatically pick up the hibernate.cfg.xml file from WEB-INF dir of web application).
package com.srini.hibernate;
import java.util.logging.Logger;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
* @author srinut096@gmail.com
*
*/
public class HibernateSessionFactory {
private static final SessionFactory sessionFactory;
private static Logger log = Logger.getLogger(HibernateSessionFactory.class.getName());
static {
try {
sessionFactory = new Configuration().configure()
.buildSessionFactory();
} catch (Throwable ex) {
log.severe("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
The SessionFactory is threadsafe, so it is not necessary to obtain one for each thread. Here the static singleton pattern is used to instantiate the SessionFactory.
5. mysql_users.sql : script to create user, db in mysql.
DROP DATABASE IF EXISTS struts;
DELETE FROM mysql.user WHERE User='struts';
FLUSH PRIVILEGES;
CREATE DATABASE IF NOT EXISTS struts CHARACTER SET utf8;
GRANT ALL PRIVILEGES ON msp.* to `struts`@`127.0.0.1` IDENTIFIED BY 'struts' WITH GRANT OPTION;
GRANT ALL PRIVILEGES ON struts.* to `struts`@`localhost` IDENTIFIED BY 'struts' WITH GRANT OPTION;
GRANT ALL PRIVILEGES ON struts.* to `struts`@`%` IDENTIFIED BY 'struts' WITH GRANT OPTION;
use struts;
6. mysql_dbscript.sql : script to create db schema.
USE struts;
--
-- Table structure for table login_details
--
DROP TABLE IF EXISTS login_details;
CREATE TABLE login_details (
id bigint(20) NOT NULL auto_increment,
name varchar(255) NOT NULL,
password varchar(255) NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY login_key (name)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO login_details VALUES (1,'srini','pass123');
7. LoginAction.java : This class is modified slightly to add logic to get data from DB and compare form values with DB values and forward respective pages.
package com.srini.action;
import java.util.List;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.srini.form.LoginForm;
import com.srini.hibernate.HibernateSessionFactory;
import com.srini.model.Login;
/**
*
* @author srinut096@gmail.com
*/
public class LoginAction extends Action {
/* forward name="success" path="" */
private final static String SUCCESS = "success";
private final static String FAILURE = "failure";
private static Logger log = Logger.getLogger(LoginAction.class.getName());
/**
* This is the action called from the Struts framework.
* @param mapping The ActionMapping used to select this instance.
* @param form The optional ActionForm bean for this request.
* @param request The HTTP Request we are processing.
* @param response The HTTP Response we are processing.
* @throws java.lang.Exception
* @return
*/
@SuppressWarnings("unchecked")
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
LoginForm loginForm = (LoginForm) form;
log.severe("Username in Action: " + loginForm.getUserName());
Session session = HibernateSessionFactory.getSessionFactory().openSession();
Transaction transaction = null;
Login loginDetails = null;
ActionForward forward = null;
try {
transaction = session.beginTransaction();
Query query = session.createQuery("from Login where name = ?");
//if (values != null) {
//for (int i = 0; i < logins =" query.list();" logins ="=" logindetails =" (Login)logins.get(0);" logindetails ="=" forward =" mapping.findForward(FAILURE);" forward =" mapping.findForward(SUCCESS);" forward =" mapping.findForward(FAILURE);">
The first call to the HibernateSessionFactory.getSessionFactory().openSession() method begins the session. The session.beginTransaction() method is used to start a new transaction. The session.createQuery() method is used to create a query object which helps in retrieving the persistant objects. Here we use Hibernate Query Language (HQL). "from Login where name=?" returns a the login details matched to name in the login_details table. Note that in the HQL we only specify the java class names and not the table names. Later, using the for loop we iterate the list of login details.
============================================
1. hibernate.cfg.xml : Hibernate uses the hibernate.cfg.xml to create the connection pool and setup required environment. Hibernate uses the Plain Old Java Objects (POJOs) classes to map to the database table. We can configure the variables to map to the database column.
The configuration looks like
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://127.0.0.1/struts?useUnicode=true&characterEncoding=utf8&autoReconnect=true</property>
<property name="hibernate.connection.username">struts</property>
<property name="connection.password">struts</property>
<property name="connection.pool_size">1</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping resource="com/srini/model/hbm/Login.hbm.xml"/>
</session-factory>
</hibernate-configuration>
I think you are already knew the first 6 properties. If 'show_sql' property is 'true' then it will write all SQL statements to console. <mapping resource="com/srini/model/hbm/Login.hbm.xml"/> property is the mapping for our login_details table.
2. Login.java : This is model class to map table.
package com.srini.model;
/**
* @author srinut096@gmail.com
*
*/
public class Login {
private int id;
private String name;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
3. Login.hbm.xml : This file is used to map Login Object to the login_details table in the database.
The configuration looks like
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.srini.model">
<class name="Login" table="login_details">
<id name="id" unsaved-value="0">
<generator class="native"/>
</id>
<property name="name" type="string" column="name"/>
<property name="password" type="string" column="password"/>
</class>
</hibernate-mapping>
The hibernate-mapping element is the root element. The class element is used to map the Java class with the database table. The Java class name is specified using the name attribute of the class element and the database table name is specified using the table attribute of the class element. The id element is used to create the primary key. The name attribute of the id element refers to the property in the Login class and the column attribute refers to the column in the login_details table. The type attribute holds the hibernate mapping type, this mapping types will convert from Java to SQL data type and vice versa. The generator element within the id element is used to automatically generate the primary key values. When the class attribute of the generator element is set to native, hibernate picks either identity, sequence or hilo algorithm depending upon the capabilities of the underlying database. The property element is used to link a property in the Java class to a column in the database table.
4. HibernateSessionFactory.java : This class helps in creating the SessionFactory from the Hibernate configuration file(it automatically pick up the hibernate.cfg.xml file from WEB-INF dir of web application).
package com.srini.hibernate;
import java.util.logging.Logger;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
* @author srinut096@gmail.com
*
*/
public class HibernateSessionFactory {
private static final SessionFactory sessionFactory;
private static Logger log = Logger.getLogger(HibernateSessionFactory.class.getName());
static {
try {
sessionFactory = new Configuration().configure()
.buildSessionFactory();
} catch (Throwable ex) {
log.severe("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
The SessionFactory is threadsafe, so it is not necessary to obtain one for each thread. Here the static singleton pattern is used to instantiate the SessionFactory.
5. mysql_users.sql : script to create user, db in mysql.
DROP DATABASE IF EXISTS struts;
DELETE FROM mysql.user WHERE User='struts';
FLUSH PRIVILEGES;
CREATE DATABASE IF NOT EXISTS struts CHARACTER SET utf8;
GRANT ALL PRIVILEGES ON msp.* to `struts`@`127.0.0.1` IDENTIFIED BY 'struts' WITH GRANT OPTION;
GRANT ALL PRIVILEGES ON struts.* to `struts`@`localhost` IDENTIFIED BY 'struts' WITH GRANT OPTION;
GRANT ALL PRIVILEGES ON struts.* to `struts`@`%` IDENTIFIED BY 'struts' WITH GRANT OPTION;
use struts;
6. mysql_dbscript.sql : script to create db schema.
USE struts;
--
-- Table structure for table login_details
--
DROP TABLE IF EXISTS login_details;
CREATE TABLE login_details (
id bigint(20) NOT NULL auto_increment,
name varchar(255) NOT NULL,
password varchar(255) NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY login_key (name)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO login_details VALUES (1,'srini','pass123');
7. LoginAction.java : This class is modified slightly to add logic to get data from DB and compare form values with DB values and forward respective pages.
package com.srini.action;
import java.util.List;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.srini.form.LoginForm;
import com.srini.hibernate.HibernateSessionFactory;
import com.srini.model.Login;
/**
*
* @author srinut096@gmail.com
*/
public class LoginAction extends Action {
/* forward name="success" path="" */
private final static String SUCCESS = "success";
private final static String FAILURE = "failure";
private static Logger log = Logger.getLogger(LoginAction.class.getName());
/**
* This is the action called from the Struts framework.
* @param mapping The ActionMapping used to select this instance.
* @param form The optional ActionForm bean for this request.
* @param request The HTTP Request we are processing.
* @param response The HTTP Response we are processing.
* @throws java.lang.Exception
* @return
*/
@SuppressWarnings("unchecked")
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
LoginForm loginForm = (LoginForm) form;
log.severe("Username in Action: " + loginForm.getUserName());
Session session = HibernateSessionFactory.getSessionFactory().openSession();
Transaction transaction = null;
Login loginDetails = null;
ActionForward forward = null;
try {
transaction = session.beginTransaction();
Query query = session.createQuery("from Login where name = ?");
//if (values != null) {
//for (int i = 0; i < logins =" query.list();" logins ="=" logindetails =" (Login)logins.get(0);" logindetails ="=" forward =" mapping.findForward(FAILURE);" forward =" mapping.findForward(SUCCESS);" forward =" mapping.findForward(FAILURE);">
The first call to the HibernateSessionFactory.getSessionFactory().openSession() method begins the session. The session.beginTransaction() method is used to start a new transaction. The session.createQuery() method is used to create a query object which helps in retrieving the persistant objects. Here we use Hibernate Query Language (HQL). "from Login where name=?" returns a the login details matched to name in the login_details table. Note that in the HQL we only specify the java class names and not the table names. Later, using the for loop we iterate the list of login details.
Now run the application in any standard browser
1. Start Tomcat
2. http://localhost:8080
3. Enter the name and password and click login button. It will check the name in DB and returns success/failure page.
Wednesday, September 8, 2010
Sample web application using struts framework
Hello all yesterday I tried to build a simple java web application using struts and hibernate from scratch using tomcat webserver. I would like to explain step by step procedure here.
I am assuming you are already familiar with java, struts, hibernate theoretically. If not please take a low level view of all these. All my setup is build in Eclipse IDE. I wrote an ant script to build and deploy my application, So that we can directly run the build script to build/deploy the web application.
Required Tools
1. Tomcat 5.5
2. Eclipse IDE
3. Dependecy jars
About Application : My application is simple login page with server side validation and verify the login details from DB and render success/failure page. In this post i will explain how to build sample web application using struts, later post i will tell about hibernate integration to this application. I used HTML form, JSP for UI and servlets for business logic and also used beans.
Step 1 : Setup in Eclipse
====================
1. Goto File --> New --> Project
2. Select Java --> java project
3. Name the project as 'Login'
4. Click Finish.
5. Create folder structure as follows
A. Create src dir structure
i. Login/src/com/srini/action
ii. Login/src/com/srini/form
B. Create webapp dir structure
i. Login/src/com/srini/webapp
ii. Login/src/com/srini/webapp/jsp
iii. Login/src/com/srini/webapp/WEB-INF
iv. Login/src/com/srini/webapp/WEB-INF/lib
v. Login/src/com/srini/webapp/WEB-INF/classes/resources
6. Files needs to be create are
i. web.xml [Login/src/com/srini/webapp/WEB-INF]
ii. struts-config.xml [Login/src/com/srini/webapp/WEB-INF]
iii. LoginAction.java [Login/src/com/srini/action]
iv. LoginForm.java [Login/src/com/srini/form]
v. login.jsp [Login/src/com/srini/webapp/jsp]
vi. success.jsp [Login/src/com/srini/webapp/jsp]
vii. failure.jsp [Login/src/com/srini/webapp/jsp]
viii. MessageResources.properties [Login/src/com/srini/webapp/WEB- INF/classes/resources]
ix. login-build.xml [Login]
x. login-build.properties [Login]
7. Dependency jars : Please download following jars from net. I don't hv an option to upload here.
i. antlr.jar
ii. commons-beanutils.jar
iii. commons-collections.jar
iv. commons-digester.jar
v. commons-logging.jar
vi. commons-validator.jar
vii. jakarta-oro.jar
viii. jsp-api.jar
ix. servlet-api.jar
x. struts.jar
Step 2 : Each file description and code inside the file
===========================================
1.web.xml : This file has all the configuration information which we have defined for our web application. The configuration information includes the index file, the default welcome page,the mapping of our servlets including path and the extension name...etc.
ActionServlet is the central component of the Struts controller. This servlet extends the HttpServlet. This servlet basically performs two important things.
I am assuming you are already familiar with java, struts, hibernate theoretically. If not please take a low level view of all these. All my setup is build in Eclipse IDE. I wrote an ant script to build and deploy my application, So that we can directly run the build script to build/deploy the web application.
Required Tools
1. Tomcat 5.5
2. Eclipse IDE
3. Dependecy jars
About Application : My application is simple login page with server side validation and verify the login details from DB and render success/failure page. In this post i will explain how to build sample web application using struts, later post i will tell about hibernate integration to this application. I used HTML form, JSP for UI and servlets for business logic and also used beans.
Step 1 : Setup in Eclipse
====================
1. Goto File --> New --> Project
2. Select Java --> java project
3. Name the project as 'Login'
4. Click Finish.
5. Create folder structure as follows
A. Create src dir structure
i. Login/src/com/srini/action
ii. Login/src/com/srini/form
B. Create webapp dir structure
i. Login/src/com/srini/webapp
ii. Login/src/com/srini/webapp/jsp
iii. Login/src/com/srini/webapp/WEB-INF
iv. Login/src/com/srini/webapp/WEB-INF/lib
v. Login/src/com/srini/webapp/WEB-INF/classes/resources
6. Files needs to be create are
i. web.xml [Login/src/com/srini/webapp/WEB-INF]
ii. struts-config.xml [Login/src/com/srini/webapp/WEB-INF]
iii. LoginAction.java [Login/src/com/srini/action]
iv. LoginForm.java [Login/src/com/srini/form]
v. login.jsp [Login/src/com/srini/webapp/jsp]
vi. success.jsp [Login/src/com/srini/webapp/jsp]
vii. failure.jsp [Login/src/com/srini/webapp/jsp]
viii. MessageResources.properties [Login/src/com/srini/webapp/WEB- INF/classes/resources]
ix. login-build.xml [Login]
x. login-build.properties [Login]
7. Dependency jars : Please download following jars from net. I don't hv an option to upload here.
i. antlr.jar
ii. commons-beanutils.jar
iii. commons-collections.jar
iv. commons-digester.jar
v. commons-logging.jar
vi. commons-validator.jar
vii. jakarta-oro.jar
viii. jsp-api.jar
ix. servlet-api.jar
x. struts.jar
Step 2 : Each file description and code inside the file
===========================================
1.web.xml : This file has all the configuration information which we have defined for our web application. The configuration information includes the index file, the default welcome page,the mapping of our servlets including path and the extension name...etc.
ActionServlet is the central component of the Struts controller. This servlet extends the HttpServlet. This servlet basically performs two important things.
1. When the container gets start, it reads the Struts Configuration files and loads it into memory in the init() method.
2. It intercepts the HTTP request in the doGet() and doPost() method and handles it appropriately.
The configuration looks like
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>jsp/login.jsp</welcome-file>
</welcome-file-list>
<jsp-config>
<taglib>
<taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-html.tld</taglib-location>
</taglib>
</jsp-config>
</web-app>
2.struts-config.xml : The name of the struts configuration file can be configured in the web.xml file. This file is placed under the WEB-INF directory of the web application. This file has all the information about many types of Struts resources and configures their interaction.
This configuration looks like
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">
<struts-config>
<form-beans>
<form-bean name="LoginForm" type="com.srini.form.LoginForm"/>
</form-beans>
<global-forwards>
<forward name="welcome" path="/Welcome.do"/>
</global-forwards>
<action-mappings>
<action input="/jsp/login.jsp" name="LoginForm" path="/Login" scope="session" type="com.srini.action.LoginAction">
<forward name="success" path="/jsp/success.jsp" />
<forward name="failure" path="/jsp/failure.jsp" />
</action>
<action path="/Welcome" forward="/jsp/welcomeStruts.jsp"/>
</action-mappings>
<message-resources parameter="resources/MessageResource"/>
</struts-config>
This file is used to associate paths with the controller components of your application., known as Action classes like <action input="/jsp/login.jsp" name="LoginForm" path="/Login" scope="session" type="com.srini.action.LoginAction">. This tag tells the Struts ActionServlet that whenever the incoming request is http://localhost/login.do, then it must invoke the controller component LoginAction. Above, you can see that we have written .do in the URL. This mapping is done to tell the web application that whenever a request is received with the .do extension then it should be appended to the URL.
3. LoginAction.java : The execute method contains the business logic of the application. Here first we typecast the ActionForm object to LoginForm, so that we can access the form variables using the getter and setter methods. If the user name and password is same then we forward the user to the success page else we forward to the failure page.
package com.srini.action;
import java.util.List;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.srini.form.LoginForm;
/**
*
* @author srinut096@gmail.com
*/
public class LoginAction extends Action {
/* forward name="success" path="" */
private final static String SUCCESS = "success";
private final static String FAILURE = "failure";
private static Logger log = Logger.getLogger(LoginAction.class.getName());
/**
* This is the action called from the Struts framework.
* @param mapping The ActionMapping used to select this instance.
* @param form The optional ActionForm bean for this request.
* @param request The HTTP Request we are processing.
* @param response The HTTP Response we are processing.
* @throws java.lang.Exception
* @return
*/
@SuppressWarnings("unchecked")
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
LoginForm loginForm = (LoginForm) form;
log.severe("Username in Action: " + loginForm.getUserName());
if(loginForm.getUserName().equals(loginForm.getPassword())) {
return mapping.findForward(SUCCESS);
} else {
return mapping.findForward(FAILURE);
}
}
}
4. LoginForm.java : Inside the validate method, we check whether the user name and password is entered. If not the corresponding error message is displayed to the user. The error messages are configured in the Message.properties file.
package com.srini.form;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
/**
* @author srinut096@gmail.com
*/
@SuppressWarnings("serial")
public class LoginForm extends org.apache.struts.action.ActionForm {
private String userName = null;
private String password = null;
/**
*
*/
public LoginForm() {
super();
// TODO Auto-generated constructor stub
}
/**
* This is the action called from the Struts framework.
* @param mapping The ActionMapping used to select this instance.
* @param request The HTTP Request we are processing.
* @return
*/
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
if (userName == null || userName.length() < password ="=" username =" userName;" password =" password;">
5. login.jsp : We use Struts HTML Tags to create login page. The form has one text field to get the user name and one password field to get the password. The form also has one submit button, which when clicked calls the login action. <html:errors /> tag is used to display the error messages to the user.
<%--
Document : login
Created on : Sep 08, 2010, 4:12:46 PM
Author : srinut096@gmail.com
--%>
<%@taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<div style="color:red">
<html:errors />
</div>
<html:form action="/Login" >
User Name :<html:text name="LoginForm" property="userName" />
Password :<html:password name="LoginForm" property="password" />
<html:submit value="Login" />
</html:form>
</body>
</html>
6. success.jsp :
<%--
Document : success
Created on : Sep 08, 2010, 4:12:46 PM
Author : srinut096@gmail.com
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<!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=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Login Success. Welcome <bean:write name="LoginForm" property="userName"></bean:write></h1>
</body>
</html>
7. failure.jsp :
<%--
Document : failure
Created on : Sep 08, 2010, 4:12:46 PM
Author : srinut096@gmail.com
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<!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=UTF-8">
<title>JSP Page</title>
</head>
<body>
<div style="color:red">
<h1>Invalid user name <bean:write name="LoginForm" property="userName"></bean:write></h1>
</div>
</body>
</html>
8. MessageResources.properties : This file contains the error messages. The key "error.userName.required" is used in the validate function to add a new error. Since the error messages are configured in a seperate properties file they can be changed anytime without making any changes to the java files or the jsp pages.
9. login-build.xml : Ant build script to build the login.war
<?xml version="1.0" encoding="UTF-8"?>
<project name="Login2" default="build.war" basedir=".">
<property file="login-build.properties"/>
<property name="name" value="login2" />
<property name="build" value="${login.src.root}/build" />
<property name="war" value="${build}/war" />
<property name="source" value="${login.src.root}/src" />
<property name="lib" value="${login.src.root}/webapp/WEB-INF/lib" />
<!-- ********************************************************************** -->
<!-- Deploy war -->
<!-- ********************************************************************** -->
<target name="deploy.war" depends="build.war" >
<delete file="${login.server.root}/${name}.war" />
<delete dir="${login.server.root}/${name}" />
<copy todir="${login.server.root}">
<fileset dir="${war}">
<include name="${name}.war"/>
</fileset>
</copy>
</target>
<!-- ********************************************************************** -->
<!-- build war -->
<!-- ********************************************************************** -->
<target name="build.war" depends="compile" >
<war warfile="${war}/${name}.war" webxml="${build}/${name}/WEB-INF/web.xml">
<fileset dir="${build}/${name}">
<include name="**/**" />
</fileset>
</war>
</target>
<!-- ********************************************************************** -->
<!-- Compilation -->
<!-- ********************************************************************** -->
<target name="compile" depends="init, copy.login.webapp" >
<javac srcdir="${source}" destdir="${build}/${name}/WEB-INF/classes" debug="${javac.debug}">
<classpath refid="class.path"/>
</javac>
</target>
<path id="class.path">
<fileset dir="${lib}">
<include name="antlr.jar"/>
<include name="commons-beanutils.jar"/>
<include name="commons-collections.jar"/>
<include name="commons-digester.jar"/>
<include name="commons-logging.jar"/>
<include name="commons-validator.jar"/>
<include name="jakarta-oro.jar"/>
<include name="jsp-api.jar"/>
<include name="servlet-api.jar"/>
<include name="struts.jar"/>
</fileset>
</path>
<!-- ********************************************************************** -->
<!-- Initialization -->
<!-- ********************************************************************** -->
<target name="init" >
<delete dir="${build}" />
<mkdir dir="${build}/${name}/WEB-INF/classes"/>
<mkdir dir="${war}" />
</target>
<!-- ********************************************************************** -->
<!-- Copy struts webapp dirs -->
<!-- ********************************************************************** -->
<target name="copy.login.webapp" >
<copy todir="${build}/${name}">
<fileset dir="${login.src.root}/webapp">
<include name="**/**"/>
<exclude name="META-INF/**"/>
</fileset>
</copy>
</target>
10. login-build.properties : properties for ant build script
2. It intercepts the HTTP request in the doGet() and doPost() method and handles it appropriately.
The configuration looks like
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>jsp/login.jsp</welcome-file>
</welcome-file-list>
<jsp-config>
<taglib>
<taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-html.tld</taglib-location>
</taglib>
</jsp-config>
</web-app>
2.struts-config.xml : The name of the struts configuration file can be configured in the web.xml file. This file is placed under the WEB-INF directory of the web application. This file has all the information about many types of Struts resources and configures their interaction.
This configuration looks like
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">
<struts-config>
<form-beans>
<form-bean name="LoginForm" type="com.srini.form.LoginForm"/>
</form-beans>
<global-forwards>
<forward name="welcome" path="/Welcome.do"/>
</global-forwards>
<action-mappings>
<action input="/jsp/login.jsp" name="LoginForm" path="/Login" scope="session" type="com.srini.action.LoginAction">
<forward name="success" path="/jsp/success.jsp" />
<forward name="failure" path="/jsp/failure.jsp" />
</action>
<action path="/Welcome" forward="/jsp/welcomeStruts.jsp"/>
</action-mappings>
<message-resources parameter="resources/MessageResource"/>
</struts-config>
This file is used to associate paths with the controller components of your application., known as Action classes like <action input="/jsp/login.jsp" name="LoginForm" path="/Login" scope="session" type="com.srini.action.LoginAction">. This tag tells the Struts ActionServlet that whenever the incoming request is http://localhost/login.do, then it must invoke the controller component LoginAction. Above, you can see that we have written .do in the URL. This mapping is done to tell the web application that whenever a request is received with the .do extension then it should be appended to the URL.
3. LoginAction.java : The execute method contains the business logic of the application. Here first we typecast the ActionForm object to LoginForm, so that we can access the form variables using the getter and setter methods. If the user name and password is same then we forward the user to the success page else we forward to the failure page.
package com.srini.action;
import java.util.List;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.srini.form.LoginForm;
/**
*
* @author srinut096@gmail.com
*/
public class LoginAction extends Action {
/* forward name="success" path="" */
private final static String SUCCESS = "success";
private final static String FAILURE = "failure";
private static Logger log = Logger.getLogger(LoginAction.class.getName());
/**
* This is the action called from the Struts framework.
* @param mapping The ActionMapping used to select this instance.
* @param form The optional ActionForm bean for this request.
* @param request The HTTP Request we are processing.
* @param response The HTTP Response we are processing.
* @throws java.lang.Exception
* @return
*/
@SuppressWarnings("unchecked")
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
LoginForm loginForm = (LoginForm) form;
log.severe("Username in Action: " + loginForm.getUserName());
if(loginForm.getUserName().equals(loginForm.getPassword())) {
return mapping.findForward(SUCCESS);
} else {
return mapping.findForward(FAILURE);
}
}
}
4. LoginForm.java : Inside the validate method, we check whether the user name and password is entered. If not the corresponding error message is displayed to the user. The error messages are configured in the Message.properties file.
package com.srini.form;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
/**
* @author srinut096@gmail.com
*/
@SuppressWarnings("serial")
public class LoginForm extends org.apache.struts.action.ActionForm {
private String userName = null;
private String password = null;
/**
*
*/
public LoginForm() {
super();
// TODO Auto-generated constructor stub
}
/**
* This is the action called from the Struts framework.
* @param mapping The ActionMapping used to select this instance.
* @param request The HTTP Request we are processing.
* @return
*/
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
if (userName == null || userName.length() < password ="=" username =" userName;" password =" password;">
5. login.jsp : We use Struts HTML Tags to create login page. The form has one text field to get the user name and one password field to get the password. The form also has one submit button, which when clicked calls the login action. <html:errors />
<%--
Document : login
Created on : Sep 08, 2010, 4:12:46 PM
Author : srinut096@gmail.com
--%>
<%@taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<div style="color:red">
<html:errors />
</div>
<html:form action="/Login" >
User Name :<html:text name="LoginForm" property="userName" />
Password :<html:password name="LoginForm" property="password" />
<html:submit value="Login" />
</html:form>
</body>
</html>
6. success.jsp :
<%--
Document : success
Created on : Sep 08, 2010, 4:12:46 PM
Author : srinut096@gmail.com
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<!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=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Login Success. Welcome <bean:write name="LoginForm" property="userName"></bean:write></h1>
</body>
</html>
7. failure.jsp :
<%--
Document : failure
Created on : Sep 08, 2010, 4:12:46 PM
Author : srinut096@gmail.com
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<!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=UTF-8">
<title>JSP Page</title>
</head>
<body>
<div style="color:red">
<h1>Invalid user name <bean:write name="LoginForm" property="userName"></bean:write></h1>
</div>
</body>
</html>
8. MessageResources.properties : This file contains the error messages. The key "error.userName.required" is used in the validate function to add a new error. Since the error messages are configured in a seperate properties file they can be changed anytime without making any changes to the java files or the jsp pages.
error.userName.required = User Name is required.
error.password.required = Password is required.
error.password.required = Password is required.
9. login-build.xml : Ant build script to build the login.war
<?xml version="1.0" encoding="UTF-8"?>
<project name="Login2" default="build.war" basedir=".">
<property file="login-build.properties"/>
<property name="name" value="login2" />
<property name="build" value="${login.src.root}/build" />
<property name="war" value="${build}/war" />
<property name="source" value="${login.src.root}/src" />
<property name="lib" value="${login.src.root}/webapp/WEB-INF/lib" />
<!-- ********************************************************************** -->
<!-- Deploy war -->
<!-- ********************************************************************** -->
<target name="deploy.war" depends="build.war" >
<delete file="${login.server.root}/${name}.war" />
<delete dir="${login.server.root}/${name}" />
<copy todir="${login.server.root}">
<fileset dir="${war}">
<include name="${name}.war"/>
</fileset>
</copy>
</target>
<!-- ********************************************************************** -->
<!-- build war -->
<!-- ********************************************************************** -->
<target name="build.war" depends="compile" >
<war warfile="${war}/${name}.war" webxml="${build}/${name}/WEB-INF/web.xml">
<fileset dir="${build}/${name}">
<include name="**/**" />
</fileset>
</war>
</target>
<!-- ********************************************************************** -->
<!-- Compilation -->
<!-- ********************************************************************** -->
<target name="compile" depends="init, copy.login.webapp" >
<javac srcdir="${source}" destdir="${build}/${name}/WEB-INF/classes" debug="${javac.debug}">
<classpath refid="class.path"/>
</javac>
</target>
<path id="class.path">
<fileset dir="${lib}">
<include name="antlr.jar"/>
<include name="commons-beanutils.jar"/>
<include name="commons-collections.jar"/>
<include name="commons-digester.jar"/>
<include name="commons-logging.jar"/>
<include name="commons-validator.jar"/>
<include name="jakarta-oro.jar"/>
<include name="jsp-api.jar"/>
<include name="servlet-api.jar"/>
<include name="struts.jar"/>
</fileset>
</path>
<!-- ********************************************************************** -->
<!-- Initialization -->
<!-- ********************************************************************** -->
<target name="init" >
<delete dir="${build}" />
<mkdir dir="${build}/${name}/WEB-INF/classes"/>
<mkdir dir="${war}" />
</target>
<!-- ********************************************************************** -->
<!-- Copy struts webapp dirs -->
<!-- ********************************************************************** -->
<target name="copy.login.webapp" >
<copy todir="${build}/${name}">
<fileset dir="${login.src.root}/webapp">
<include name="**/**"/>
<exclude name="META-INF/**"/>
</fileset>
</copy>
</target>
10. login-build.properties : properties for ant build script
# ********************************************************
# Customize this one with your own root directory
# ********************************************************
login.src.root=C:/E-Folder/struts_workspace/login
login.server.root=C:/Program Files/Apache Software Foundation/Tomcat 5.5/webapps
# ********************************************************
# compilation
# ********************************************************
java.home = C:/Program Files/Java/jdk1.6.0
javac.deprecation = off
javac.nowarn = off
javac.debug = on
javac.optimize = off
jndi.prefix = java:comp/env/
Now run the application in any standard browser
# Customize this one with your own root directory
# ********************************************************
login.src.root=C:/E-Folder/struts_workspace/login
login.server.root=C:/Program Files/Apache Software Foundation/Tomcat 5.5/webapps
# ********************************************************
# compilation
# ********************************************************
java.home = C:/Program Files/Java/jdk1.6.0
javac.deprecation = off
javac.nowarn = off
javac.debug = on
javac.optimize = off
jndi.prefix = java:comp/env/
Now run the application in any standard browser
1. Start Tomcat
2. http://localhost:8080/Login/login.do
Friday, August 27, 2010
Java strings splitting issue
Yesterday I faced an interesting issue with java strings. I have a string values with .(dot) , ex. 127.4.3.2 ,,etc. My aim is to split the string by .(dot), As usual I used the following stmts to do it.
String myStr = "172.5.33.22";
String[] strs = myStr.split(".");
System.out.println("Length : " + strs.length);
But when I run the program the resulte strs length is 0. Then I modified myStr as '172,22,,5,6' and modified split str as ','. its resulting strs length as 4. I wondered why happening this, A quick googling I got solution and its worked. The sol is If you want to slpit the string by .(dot) you need to specify regExp as '\\.'.
The working code is
String myStr = "172.5.33.22";
String[] strs = myStr.split("\\.");
System.out.println("Length : " + strs.length);
String myStr = "172.5.33.22";
String[] strs = myStr.split(".");
System.out.println("Length : " + strs.length);
But when I run the program the resulte strs length is 0. Then I modified myStr as '172,22,,5,6' and modified split str as ','. its resulting strs length as 4. I wondered why happening this, A quick googling I got solution and its worked. The sol is If you want to slpit the string by .(dot) you need to specify regExp as '\\.'.
The working code is
String myStr = "172.5.33.22";
String[] strs = myStr.split("\\.");
System.out.println("Length : " + strs.length);
Now I got correct strs length.
Tuesday, August 17, 2010
Get short timezone displayname -- Java
I think you are already familiar with timezones, Ofcourse its not mandatory. Here discussion is If you want to export timezone value into Excel(.xls/.CSV) by default long name will come(like Asia/Calcutta). If you want to save short name(like IST) try the following code.
String timeZoneStr = "Asia/Calcutta";
String shortDisplayName = TimeZone.getTimeZone(timeZoneStr).getDisplayName(false, TimeZone.SHORT);
String timeZoneStr = "Asia/Calcutta";
String shortDisplayName = TimeZone.getTimeZone(timeZoneStr).getDisplayName(false, TimeZone.SHORT);
Here first boolean param indicates daylight saving on/off and TimeZone.SHORT indicates a style specifier for getDisplayName() indicating a short name, such as "IST."
Thursday, July 29, 2010
Configure proxy settings in Linux
Cmd to set proxy: export http_proxy= "http://PROXY_IP:PORT"
Cmd to test proxy settings : env | grep proxy
it will show you the proxy details.
Cmd to test proxy settings : env | grep proxy
it will show you the proxy details.
Quick reference of Linux/Unix commands
Following page contains basic commands which we are daily using in Linux env. Hope it will help you.
Tuesday, July 27, 2010
Call MAVEN task from ANT
Few days back I got a requirement like call maven task from ant script. For this I wrote one shell script and in which I defined maven task(build war). From ant I called this script using 'exec' cmd, see below
<target>
exec executable="/bin/bash">
<arg value="${src.dir}/SAMPLE_MAVEN.sh"/>
</exec>
</target>
Today I came to know that we can call maven task from ant using 'marcodef', Its very easy to use and its worked for me . See the equavalent macrodef script for the above ant script
<target name="build.sw" depends="env, init, prepare">
<maven basedir="${pom.dir}" goal="clean" resultproperty="maven.build.result" options="-e -Dspring.root=${firware.build.root} -Dbuild.for.prod=false -Djavac.debug=true -Djavac.optimize=false"/>
<maven basedir="${pom.dir}" goal="package" resultproperty="maven.build.result" options="-e -Dspring.root=${firware.build.root} -Dbuild.for.prod=false -Djavac.debug=true -Djavac.optimize=false"/>
</target>
<!--
This is the macro definition for maven Ant task
-->
<macrodef name="maven">
<attribute name="options" default="" />
<attribute name="goal" />
<attribute name="basedir" />
<attribute name="resultproperty" default="maven.result" />
<element name="args" implicit="true" optional="true" />
<sequential>
<java classname="org.codehaus.classworlds.Launcher" fork="true" dir="@{basedir}" resultproperty="@{resultproperty}">
<jvmarg value="-Xmx512m" />
<classpath>
<fileset dir="${{maven.src.dir}/boot">
<include name="*.jar" />
</fileset>
<fileset dir="${{maven.src.dir}/lib">
<include name="*.jar" />
</fileset>
</classpath>
<sysproperty key="classworlds.conf" value="${{maven.src.dir}/bin/m2.conf" />
<sysproperty key="maven.home" value="${maven.src.dir}" />
<arg line="--batch-mode @{options} @{goal}" />
</java>
</sequential>
</macrodef>
From the above scratch 'attributes' are basic info about maven tasks.
Options : here we need to provide command line options to build task.
Goal : maven goal (clean, package, install)
Basedir : our pom.xml file path
resultproperty : it is optional.
<target>
exec executable="/bin/bash">
<arg value="${src.dir}/SAMPLE_MAVEN.sh"/>
</exec>
</target>
Today I came to know that we can call maven task from ant using 'marcodef', Its very easy to use and its worked for me . See the equavalent macrodef script for the above ant script
<target name="build.sw" depends="env, init, prepare">
<maven basedir="${pom.dir}" goal="clean" resultproperty="maven.build.result" options="-e -Dspring.root=${firware.build.root} -Dbuild.for.prod=false -Djavac.debug=true -Djavac.optimize=false"/>
<maven basedir="${pom.dir}" goal="package" resultproperty="maven.build.result" options="-e -Dspring.root=${firware.build.root} -Dbuild.for.prod=false -Djavac.debug=true -Djavac.optimize=false"/>
</target>
<!--
This is the macro definition for maven Ant task
-->
<macrodef name="maven">
<attribute name="options" default="" />
<attribute name="goal" />
<attribute name="basedir" />
<attribute name="resultproperty" default="maven.result" />
<element name="args" implicit="true" optional="true" />
<sequential>
<java classname="org.codehaus.classworlds.Launcher" fork="true" dir="@{basedir}" resultproperty="@{resultproperty}">
<jvmarg value="-Xmx512m" />
<classpath>
<fileset dir="${{maven.src.dir}/boot">
<include name="*.jar" />
</fileset>
<fileset dir="${{maven.src.dir}/lib">
<include name="*.jar" />
</fileset>
</classpath>
<sysproperty key="classworlds.conf" value="${{maven.src.dir}/bin/m2.conf" />
<sysproperty key="maven.home" value="${maven.src.dir}" />
<arg line="--batch-mode @{options} @{goal}" />
</java>
</sequential>
</macrodef>
From the above scratch 'attributes' are basic info about maven tasks.
Options : here we need to provide command line options to build task.
Goal : maven goal (clean, package, install)
Basedir : our pom.xml file path
resultproperty : it is optional.
Friday, June 18, 2010
VIJava
Recently I am trying to integrate VIJava to my project, ohh .. Sorry I didn't tell about what is VIJava... VIJava is a opensource Java project, using this we can manage a VMServer/ESXi/ESX/vCenter thru java programming. We can get VM instances info, re-configure Vm, powerOn, powerOff ... and lot more actions.
We can remotely manage VM in very secure and efficient way. I tried to powerOn, powerOff, Reset, getvmconfigs, getVMTasks of my VM instance. It is really good API in Java , Even performance is also not bad. For more details check here
We can remotely manage VM in very secure and efficient way. I tried to powerOn, powerOff, Reset, getvmconfigs, getVMTasks of my VM instance. It is really good API in Java , Even performance is also not bad. For more details check here
Thursday, June 3, 2010
Secure Linux/UNIX access with PuTTY.
Everybody knows connect to a Linux system using putty password based auth, its very common approach to access linux system. However this password based auth is not secure, they are still open to brute-force attacks from anywhere on the internet.
So here I am explaining another auth method 'public key authtentication'.
Required tools : You need to download following files from Putty. These are simple '.exe' files and you need not to install. Just copy these exe files into one dir and you can run directly these files.
1. PuTTY.exe — Secure Shell client
2. PuTTYgen.exe — SSH public/private key generator.
Now follow the below steps
Step 1 : First you need to generate keypair(publickey and privatekey) using 'PuTTYgen.exe'(double click it), it will display one window to generate keys. The key pair is generated using a random number generator with the help of RSA/DSA algorithms. This will create a private key and a public key. The public key generated will be used for identity purpose. These both files will have the same file name and the public key is saved with “.pub” extension.
The Password/Passphrase you entered is used to encrypt your private key. If you left the password field blank, the key will not be encrypted. The contents of the 'comment' field are stored with your key, and displayed each time you are prompted for the key's password.
See the image for clarification

Give the passphrase and save the private key.
Step 2 : Upload the public key into targer server(the linux machine you want to connect thru putty). Login to the target server using password based auth and goto '.ssh/authorized_keys'(with in the user profile for e.g root user /root/.ssh), If the dir '.ssh' it not there then create dir and edit the file authorized_keys(using vi authorized_keys). copy the public key into clipbaord from and paste it into authorized_keys(see below image).

Step3 : Now connect to linux system usning 'PuTTy.exe'(double click it), It will prompt you one window to enter server details and private key.
see the image

It will prompt putty window(see below image) and will ask you login name.

Enter the login and passphrase
So here I am explaining another auth method 'public key authtentication'.
Required tools : You need to download following files from Putty. These are simple '.exe' files and you need not to install. Just copy these exe files into one dir and you can run directly these files.
1. PuTTY.exe — Secure Shell client
2. PuTTYgen.exe — SSH public/private key generator.
Now follow the below steps
Step 1 : First you need to generate keypair(publickey and privatekey) using 'PuTTYgen.exe'(double click it), it will display one window to generate keys. The key pair is generated using a random number generator with the help of RSA/DSA algorithms. This will create a private key and a public key. The public key generated will be used for identity purpose. These both files will have the same file name and the public key is saved with “.pub” extension.
The Password/Passphrase you entered is used to encrypt your private key. If you left the password field blank, the key will not be encrypted. The contents of the 'comment' field are stored with your key, and displayed each time you are prompted for the key's password.
See the image for clarification
Give the passphrase and save the private key.
Step 2 : Upload the public key into targer server(the linux machine you want to connect thru putty). Login to the target server using password based auth and goto '.ssh/authorized_keys'(with in the user profile for e.g root user /root/.ssh), If the dir '.ssh' it not there then create dir and edit the file authorized_keys(using vi authorized_keys). copy the public key into clipbaord from and paste it into authorized_keys(see below image).
Step3 : Now connect to linux system usning 'PuTTy.exe'(double click it), It will prompt you one window to enter server details and private key.
see the image
It will prompt putty window(see below image) and will ask you login name.
Enter the login and passphrase
Wednesday, June 2, 2010
Mail issue in Java
Yesterday I got an issue with sending mails in java. If the mail contains any japanese chars it displaying Q.M(?). We know If we provide encoding as UTF-8 prob will solve, but eventhough we provided encoding the issue is not resolved, While debugging I got a clue that the content still usnig another encoding, Finally A quick googling its resolved.
The problomatice code line is
MimeMessageHelper helper = new MimeMessageHelper(message, true);
Corrected code line is
MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
The problomatice code line is
MimeMessageHelper helper = new MimeMessageHelper(message, true);
Corrected code line is
MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
Wednesday, May 26, 2010
Java compilation issue with Eclipse settings
Today I got an interesting error while running my sample java appliaction. Error is
Access restriction: The method createJPEGEncoder(OutputStream) from the type JPEGCodec is not accessible due to
restriction on required library C:\Program Files\Java\jdk1.6.0_11\jre\lib\rt.jar
Access restriction: The method getDefaultJPEGEncodeParam(BufferedImage) from the type JPEGImageEncoder is not accessible due to
restriction on required library C:\Program Files\Java\jdk1.6.0_11\jre\lib\rt.jar
Access restriction: The method setJPEGEncodeParam(JPEGEncodeParam) from the type JPEGImageEncoder is not accessible due to
restriction on required library C:\Program Files\Java\jdk1.6.0_11\jre\lib\rt.jar ImageUtil.java.
One of my java application program importing Sun default package "com.sun.image.codec.jpeg.JPEGCodec" which is in C:\Program Files\Java\jdk1.6.0_11\jre\lib\rt.jar.
Upto yesterday its worked for me without any issues except some warning messages, Suddenly today I am unable to run the application and getting above error.
A quick googling Its resolved with small setting modification in eclipse.
Solution :
1. Go to Project properties
2. Expand Java Compiler and Click on Errors/Warnings
3. Click Enable project specific settings.
4. Expand Depricated and restricted API
5. Change forbidden reference(access rules) setting as warning or ignore.
Now try to run the java application.
Access restriction: The method createJPEGEncoder(OutputStream) from the type JPEGCodec is not accessible due to
restriction on required library C:\Program Files\Java\jdk1.6.0_11\jre\lib\rt.jar
Access restriction: The method getDefaultJPEGEncodeParam(BufferedImage) from the type JPEGImageEncoder is not accessible due to
restriction on required library C:\Program Files\Java\jdk1.6.0_11\jre\lib\rt.jar
Access restriction: The method setJPEGEncodeParam(JPEGEncodeParam) from the type JPEGImageEncoder is not accessible due to
restriction on required library C:\Program Files\Java\jdk1.6.0_11\jre\lib\rt.jar ImageUtil.java.
One of my java application program importing Sun default package "com.sun.image.codec.jpeg.JPEGCodec" which is in C:\Program Files\Java\jdk1.6.0_11\jre\lib\rt.jar.
Upto yesterday its worked for me without any issues except some warning messages, Suddenly today I am unable to run the application and getting above error.
A quick googling Its resolved with small setting modification in eclipse.
Solution :
1. Go to Project properties
2. Expand Java Compiler and Click on Errors/Warnings
3. Click Enable project specific settings.
4. Expand Depricated and restricted API
5. Change forbidden reference(access rules) setting as warning or ignore.
Now try to run the java application.
Thursday, May 13, 2010
Java compilation issue with ant script
How to compile java using ANT ? Everybody knows java compilation using ant scripts. I thought you are already familiar with ant build scripts to compile java .Yesterday i got a requirement like compile different packages folders at a time. Due to some inter dependencies in these folders I need to compile these dirs in one shot.A quick googling I got solution and its worked for me. Let me explain how it can be coded.
1. The basic ant script to compile java files in one folder is
<javac srcdir="${src}"
destdir="${build}"
classpath="xyz.jar"
debug="on" />
Above script compiles all .java files under the ${src} directory, and stores the .class files in the ${build} directory. If your code using any thirdparty jars, you need to specify in classpath and and compiling with debug information is on.
2. Ant script to compile java files with some extra logic is
<javac srcdir="${src}"
destdir="${build}"
includes="mypkg/p1/**,mypkg/p2/**"
excludes="mypkg/p1/testpkg/**"
classpath="xyz.jar"
debug="on"/>
Above script compiles .java files under the ${src} directory, and stores the .class files in the ${build} directory. The classpath used includes xyz.jar, and debug information is on. Only files under mypkg/p1 and mypkg/p2 are used. All files in and below the mypkg/p1/testpkg directory are excluded from compilation.
3. Ant script to compile multiple source directories at one shot is
<javac srcdir="${src}:${src2}"
destdir="${build}"
includes="mypkg/p1/**,mypkg/p2/**"
excludes="mypkg/p1/testpkg/**"
classpath="xyz.jar"
debug="on"/>
This can also be represented using nested as follows
<javac destdir="${build}"
classpath="xyz.jar"
debug="on">
<src path="${src}"/>
<src path="${src2}"/>
<include name="mypkg/p1/**"/>
<include name="mypkg/p2/**"/>
<exclude name="mypkg/p1/testpkg/**"/>
</javac>
1. The basic ant script to compile java files in one folder is
<javac srcdir="${src}"
destdir="${build}"
classpath="xyz.jar"
debug="on" />
Above script compiles all .java files under the ${src} directory, and stores the .class files in the ${build} directory. If your code using any thirdparty jars, you need to specify in classpath and and compiling with debug information is on.
2. Ant script to compile java files with some extra logic is
<javac srcdir="${src}"
destdir="${build}"
includes="mypkg/p1/**,mypkg/p2/**"
excludes="mypkg/p1/testpkg/**"
classpath="xyz.jar"
debug="on"/>
Above script compiles .java files under the ${src} directory, and stores the .class files in the ${build} directory. The classpath used includes xyz.jar, and debug information is on. Only files under mypkg/p1 and mypkg/p2 are used. All files in and below the mypkg/p1/testpkg directory are excluded from compilation.
3. Ant script to compile multiple source directories at one shot is
<javac srcdir="${src}:${src2}"
destdir="${build}"
includes="mypkg/p1/**,mypkg/p2/**"
excludes="mypkg/p1/testpkg/**"
classpath="xyz.jar"
debug="on"/>
This can also be represented using nested
<javac destdir="${build}"
classpath="xyz.jar"
debug="on">
<src path="${src}"/>
<src path="${src2}"/>
<include name="mypkg/p1/**"/>
<include name="mypkg/p2/**"/>
<exclude name="mypkg/p1/testpkg/**"/>
</javac>
Subscribe to:
Posts (Atom)