Create a div with id = googleMap
<tr>
<td colspan=2 >
<table border=1>
<tr>
<td>
<div id="googleMap" style="width: 550px; height: 450px"></div>
</td>
</tr>
</table>
<td colspan=1 class="sidebar">
</td>
</tr>
Send the AJAX call to the server to retrieve map data
var request = GXmlHttp.create();
request.open("GET", "http://myserver:8080/MapServlet?method=getGoogleMap", true);
// the getGoogleMap method should be implemented on the server side to retrieve the lat and lng from database and populate the result as an XML and return back to front end
request.onreadystatechange = function()
{
if (request.readyState == 4)
{
if (request.status == 200)
{
var response = request.responseText;
if (response == '<%= MapServlet.ERROR_NO_DATA %>')
{
alert('<bean:message key="errors.map.notInDatabase"/>');
}
else
{
var xmlDoc = GXml.parse(response);
// obtain the array of markers and loop through it
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++)
{
var lat = parseFloat(GXml.value(markers[i].getElementsByTagName("lat")[0]));
var lng = parseFloat(GXml.value(markers[i].getElementsByTagName("lng")[0]));
var point = new GLatLng(lat, lng);
var html = GXml.value(markers[i].getElementsByTagName("stnName")[0]);
createMarker(point, html);
}
}
}
function createMarker(point, html)
{
var map = new GMap2(document.getElementById("map"));
map.setCenter(point, 3);
var marker = createInfoMarker(gLatLng, html);
map.addOverlay(marker);
GEvent.addListener(marker, "click", function()
{
marker.openInfoWindowHtml(html);
});
}
Sample XSD for creating the above map xml
<xs:element name="MapObject">
<xs:complexType>
<xs:sequence>
<xs:element name="marker" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="lat" type="xs:string" />
<xs:element name="lng" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
Thursday, June 19, 2008
Create own domian names for pc
To add our own domain name to our pc, we may do the following:
On a Windows XP machine you can find your HOSTS file in the “C:\Windows\System32\drivers\etc” directory.
Windows 2000, it’s ” c:\winnt\system32\drivers\etc\hosts”. And on Linux, it’s just “/etc/hosts”.
Open it up in a text editor, and add the following lines:
127.0.0.1 mydomain.com.localhost
and Reboot
Now you can access the url http://mydomain.com.localhost/
On a Windows XP machine you can find your HOSTS file in the “C:\Windows\System32\drivers\etc” directory.
Windows 2000, it’s ” c:\winnt\system32\drivers\etc\hosts”. And on Linux, it’s just “/etc/hosts”.
Open it up in a text editor, and add the following lines:
127.0.0.1 mydomain.com.localhost
and Reboot
Now you can access the url http://mydomain.com.localhost/
Hibernate basic examples
Example shows basic hibernate usage:
person.hbm.xml
<hibernate-mapping>
<class name="com.test.model.Person" table="person" >
<id name="personId" type="int">
<column name="person_id" />
<generator class="sequence">
<param name="sequence">NEXT_PERSON_ID</param>
<param name="parameters">INCREMENT BY 1 START WITH 1</param>
</generator>
</id>
<property name="personAge" type="java.lang.Integer">
<column name="person_age" />
</property>
<property name="personName" type="string">
<column name="person_name" length="3" not-null="true" />
</property>
<property name="personDateOfBirth" type="date">
<column name="person_dob" length="4" />
</property>
<property name="updateTime" type="timestamp">
<column name="update_time" length="3594" />
</property>
We ca also properties to fetch another table data lazily as:
<property name="personRoles" lazy="false" type="string" >
<formula>
(select pr.person_role from PersonRole pr where pr.person_id=person_id)
</formula>
</property>
One to Many mapping returning a List
<list name="personRoles" lazy="true" fetch="select" inverse="true">
<key>
<column name="person_id" />
<column name="person_role" />
</key>
<list-index column="role_seq" base="1"/>
<one-to-many class="com.test.model.PersonRole" />
</list>
One to Many mapping returning a Set
<set name="personRoles" order-by="role_seq" lazy="true" fetch="select" inverse="true">
<key>
<column name="person_id" />
<column name="person_role" />
</key>
Model class to represent this would be as follows:
public class Person implements java.io.Serializable
{
private int personId;
private Integer personAge;
private String personName;
private Date personDateOfBirth;
private Date updateTime;
// setters and getters
}
DAO to access the persistence layer
class PersonDAOHibernateImpl extends PersonDAO
{
public List<Person> getPersonList()
{
try
{
beginTransaction();
Session session = getSession();
List<Person> instList = session.createCriteria(Person.class)
.addOrder(Order.desc("personId"))
.list();
commitTransaction();
return instList;
}
catch(Exception e)
{
rollbackTransaction();
return Collections.emptyList();
}
}
Some other kind of queries we can use are:
To get a specific name list
List<Person> instList = session.createCriteria(Person.class)
.add(Restrictions.eq("personName", Integer.valueOf(personName)))
.addOrder(Order.desc("personId"))
.list();
can also use this clause in above query where we have a composite id
.add(Restrictions.eq("id.name", Integer.valueOf(personName)))
or
Query q = getSession().createQuery("select personName from Person");
List<Person> personList = q.list();
or if we need to make a join on another table say for example called PersonRoles
Criteria c = session.createCriteria(Person.class)
.add(Restrictions.eq("id.name", Integer.valueOf(personId)))
.setFetchMode("roles", FetchMode.JOIN)
.createAlias("roles", "personRoles", CriteriaSpecification.LEFT_JOIN)
.addOrder(Order.asc("id.personId"))
.addOrder(Order.asc("personRoles.id.roleName"))
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
or we can create a plain sql statement and query
String updatePerson =
" update person " +
" SET person_name = 'ABC' " +
" WHERE person_id = ? ";
Session session = getSession();
beginTransaction();
Connection conn = session.connection();
PreparedStatement pstmt = conn.prepareStatement(updatePerson);
pstmt.setInt(1, personId);
pstmt.execute();
pstmt.close();
Couple of helpful Ant tasks
<target name="hibernatetool" description="Run Hibernate Tool" unless="hibernate.skip" depends="">
<mkdir dir="${src.resources.hibernate.generated}" />
<echo message="ANT HEAP SIZE = ${env.ANT_OPTS}" />
<taskdef name="hibernatetool" classname="org.hibernate.tool.ant.HibernateToolTask" classpathref="hibernatetools.path" />
<hibernatetool destdir="${src.resources.hibernate.generated}" templatepath="${src.resources.hibernate}">
<jdbcconfiguration
revengfile="${src.resources.hibernate}/hibernate.reveng.xml"
configurationfile="${src.resources.hibernate}/hibernate.cfg.xml"
packagename="${package.name}" />
<hbm2hbmxml/> <!-- This regenerates the hbm mapping files -->
<!-- <hbm2cfgxml/> This cretaes a hibernate.cfg.xml file -->
</hibernatetool>
</target>
<target name="hbm2java" description="Run Hibernate Tool" unless="hibernate.skip" depends="">
<taskdef name="hibernatetool" classname="org.hibernate.tool.ant.HibernateToolTask"
classpathref="hibernatetools.path"
/>
<hibernatetool destdir="${src.resources.hibernate.generated}">
<configuration>
<fileset dir="${src.resources.hibernate.generated}">
<include name="**/Person*.hbm.xml" />
</fileset>
</configuration>
<hbm2java jdk5="false" ejb3="false" />
</hibernatetool>
</target>
hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<!-- Bind the getCurrentSession() method to the thread, session-per-conversation -->
<property name="current_session_context_class">org.hibernate.context.ThreadLocalSessionContext</property>
<property name="hibernate.connection.url">jdbc:informix-sqli:myhostname:myportnumber/mydatabasename:INFORMIXSERVER=myservername</property>
<property name="hibernate.connection.username">myusername</property>
<property name="hibernate.connection.password">mypassword</property>
<property name="hibernate.connection.release_mode">auto</property>
<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<property name="hibernate.connection.driver_class">com.informix.jdbc.IfxDriver</property>
<property name="dialect">org.hibernate.dialect.InformixDialect</property>
<property name="show_sql">true</property>
<!-- Connection Pool -->
<property name="hibernate.connection.pool_size">3</property>
<property name="hibernate.c3p0.min_size">1</property>
<property name="hibernate.c3p0.max_size">5</property>
<property name="hibernate.c3p0.timeout">1800</property>
<property name="hibernate.c3p0.max_statements">100</property>
<!-- Use EHCache as secondary cache-->
<property name="hibernate.cache.use_query_cache">true</property>
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<mapping resource="com/mytest/persistence/orm/hibernate/model/Person.hbm.xml" />
</session-factory>
</hibernate-configuration>
hibernate.reveng.xml
<hibernate-reverse-engineering>
<type-mapping>
<sql-type jdbc-type="5" hibernate-type="integer"/>
</type-mapping>
<table-filter match-catalog="mydatabasename" match-schema="informix" match-name="person" exclude="false" />
</hibernate-reverse-engineering>
person.hbm.xml
<hibernate-mapping>
<class name="com.test.model.Person" table="person" >
<id name="personId" type="int">
<column name="person_id" />
<generator class="sequence">
<param name="sequence">NEXT_PERSON_ID</param>
<param name="parameters">INCREMENT BY 1 START WITH 1</param>
</generator>
</id>
<property name="personAge" type="java.lang.Integer">
<column name="person_age" />
</property>
<property name="personName" type="string">
<column name="person_name" length="3" not-null="true" />
</property>
<property name="personDateOfBirth" type="date">
<column name="person_dob" length="4" />
</property>
<property name="updateTime" type="timestamp">
<column name="update_time" length="3594" />
</property>
We ca also properties to fetch another table data lazily as:
<property name="personRoles" lazy="false" type="string" >
<formula>
(select pr.person_role from PersonRole pr where pr.person_id=person_id)
</formula>
</property>
One to Many mapping returning a List
<list name="personRoles" lazy="true" fetch="select" inverse="true">
<key>
<column name="person_id" />
<column name="person_role" />
</key>
<list-index column="role_seq" base="1"/>
<one-to-many class="com.test.model.PersonRole" />
</list>
One to Many mapping returning a Set
<set name="personRoles" order-by="role_seq" lazy="true" fetch="select" inverse="true">
<key>
<column name="person_id" />
<column name="person_role" />
</key>
Model class to represent this would be as follows:
public class Person implements java.io.Serializable
{
private int personId;
private Integer personAge;
private String personName;
private Date personDateOfBirth;
private Date updateTime;
// setters and getters
}
DAO to access the persistence layer
class PersonDAOHibernateImpl extends PersonDAO
{
public List<Person> getPersonList()
{
try
{
beginTransaction();
Session session = getSession();
List<Person> instList = session.createCriteria(Person.class)
.addOrder(Order.desc("personId"))
.list();
commitTransaction();
return instList;
}
catch(Exception e)
{
rollbackTransaction();
return Collections.emptyList();
}
}
Some other kind of queries we can use are:
To get a specific name list
List<Person> instList = session.createCriteria(Person.class)
.add(Restrictions.eq("personName", Integer.valueOf(personName)))
.addOrder(Order.desc("personId"))
.list();
can also use this clause in above query where we have a composite id
.add(Restrictions.eq("id.name", Integer.valueOf(personName)))
or
Query q = getSession().createQuery("select personName from Person");
List<Person> personList = q.list();
or if we need to make a join on another table say for example called PersonRoles
Criteria c = session.createCriteria(Person.class)
.add(Restrictions.eq("id.name", Integer.valueOf(personId)))
.setFetchMode("roles", FetchMode.JOIN)
.createAlias("roles", "personRoles", CriteriaSpecification.LEFT_JOIN)
.addOrder(Order.asc("id.personId"))
.addOrder(Order.asc("personRoles.id.roleName"))
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
or we can create a plain sql statement and query
String updatePerson =
" update person " +
" SET person_name = 'ABC' " +
" WHERE person_id = ? ";
Session session = getSession();
beginTransaction();
Connection conn = session.connection();
PreparedStatement pstmt = conn.prepareStatement(updatePerson);
pstmt.setInt(1, personId);
pstmt.execute();
pstmt.close();
Couple of helpful Ant tasks
<target name="hibernatetool" description="Run Hibernate Tool" unless="hibernate.skip" depends="">
<mkdir dir="${src.resources.hibernate.generated}" />
<echo message="ANT HEAP SIZE = ${env.ANT_OPTS}" />
<taskdef name="hibernatetool" classname="org.hibernate.tool.ant.HibernateToolTask" classpathref="hibernatetools.path" />
<hibernatetool destdir="${src.resources.hibernate.generated}" templatepath="${src.resources.hibernate}">
<jdbcconfiguration
revengfile="${src.resources.hibernate}/hibernate.reveng.xml"
configurationfile="${src.resources.hibernate}/hibernate.cfg.xml"
packagename="${package.name}" />
<hbm2hbmxml/> <!-- This regenerates the hbm mapping files -->
<!-- <hbm2cfgxml/> This cretaes a hibernate.cfg.xml file -->
</hibernatetool>
</target>
<target name="hbm2java" description="Run Hibernate Tool" unless="hibernate.skip" depends="">
<taskdef name="hibernatetool" classname="org.hibernate.tool.ant.HibernateToolTask"
classpathref="hibernatetools.path"
/>
<hibernatetool destdir="${src.resources.hibernate.generated}">
<configuration>
<fileset dir="${src.resources.hibernate.generated}">
<include name="**/Person*.hbm.xml" />
</fileset>
</configuration>
<hbm2java jdk5="false" ejb3="false" />
</hibernatetool>
</target>
hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<!-- Bind the getCurrentSession() method to the thread, session-per-conversation -->
<property name="current_session_context_class">org.hibernate.context.ThreadLocalSessionContext</property>
<property name="hibernate.connection.url">jdbc:informix-sqli:myhostname:myportnumber/mydatabasename:INFORMIXSERVER=myservername</property>
<property name="hibernate.connection.username">myusername</property>
<property name="hibernate.connection.password">mypassword</property>
<property name="hibernate.connection.release_mode">auto</property>
<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<property name="hibernate.connection.driver_class">com.informix.jdbc.IfxDriver</property>
<property name="dialect">org.hibernate.dialect.InformixDialect</property>
<property name="show_sql">true</property>
<!-- Connection Pool -->
<property name="hibernate.connection.pool_size">3</property>
<property name="hibernate.c3p0.min_size">1</property>
<property name="hibernate.c3p0.max_size">5</property>
<property name="hibernate.c3p0.timeout">1800</property>
<property name="hibernate.c3p0.max_statements">100</property>
<!-- Use EHCache as secondary cache-->
<property name="hibernate.cache.use_query_cache">true</property>
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<mapping resource="com/mytest/persistence/orm/hibernate/model/Person.hbm.xml" />
</session-factory>
</hibernate-configuration>
hibernate.reveng.xml
<hibernate-reverse-engineering>
<type-mapping>
<sql-type jdbc-type="5" hibernate-type="integer"/>
</type-mapping>
<table-filter match-catalog="mydatabasename" match-schema="informix" match-name="person" exclude="false" />
</hibernate-reverse-engineering>
Wednesday, June 18, 2008
Spring basic examples
EXAMPLES USING Spring's ApplicationContext class gives support for application framework services.
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
public class PersonTest
{
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception
{
ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServlet().getServletContext());
//ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(config.getServletContext());
//ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
PersonHelper personHelper = (PersonHelper) context.getBean("PersonHelper");
List personList = (List)personHelper.getPersonList();
}
}
public class PersonHelper extends HibernateDaoSupport implements DatabaseHelperInterface
{
public List getPersonList() throws PersonDAOException
{
Session session = SessionFactoryUtils.getSession(this.getSessionFactory(), false);
List personList = new ArrayList();
try {
Query query = session.createQuery("from com.test.Person as person order by perosn.personName");
Iterator it = query.iterate();
while (it.hasNext()) {
Person person = (Person) it.next();
personList.add(person);
}
return personList;
}
catch (HibernateException ex)
{
throw new PersonDAOException("getPersonList(): " + ex.getMessage());
}
finally
{
try
{
session.close();
}
catch (HibernateException ex)
{
logger.fatal(ex);
}
}
}
}
import net.sf.hibernate.SessionFactory;
public interface DatabaseHelperInterface {
public SessionFactory getSessionFactory();
public void setSessionFactory(SessionFactory sessionFactory);
}
In applicationContext.xml
<bean id="sessionFactory" class="org.springframework.orm.hibernate.LocalSessionFactoryBean">
<property name="mappingResources">
<list>
<value>com/onerail/orion/common/hibernate/bean/Person.hbm.xml</value>
<value>com/onerail/orion/common/hibernate/bean/PersonRoles.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.connection.username">${hibernate.connection.username}</prop>
<prop key="hibernate.connection.password">${hibernate.connection.password}</prop>
<prop key="hibernate.connection.url">${hibernate.connection.url}</prop>
<prop key="hibernate.dialect">net.sf.hibernate.dialect.InformixDialect</prop>
<prop key="hibernate.connection.driver_class">${hibernate.connection.driver_class}</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.use_outer_join">true</prop>
<prop key="hibernate.transaction.factory_class">net.sf.hibernate.transaction.JDBCTransactionFactory</prop>
<prop key="hibernate.dbcp.minIdle">1</prop>
<!-- <prop key="hibernate.cache.use_query_cache">true</prop> -->
<!-- <prop key="hibernate.connection.pool_size">3</prop> -->
<!-- <prop key="hibernate.cache.provider_class">com.onerail.orion.common.hibernate.patch.OSCacheProvider</prop> -->
<prop key="hibernate.cglib.use_reflection_optimizer">false</prop>
<prop key="hibernate.c3p0.min_size">5</prop>
<prop key="hibernate.c3p0.max_size">20</prop>
<prop key="hibernate.c3p0.timeout">1800</prop>
<prop key="hibernate.c3p0.max_statements">50</prop>
</props>
</property>
</bean>
<!-- placeholderConfig loads extra configuration information which is placed into the expressions eg ${com.test.util.constants.dbUser} -->
<bean id="placeholderConfig"
class="com.onerail.orion.common.hibernate.config.HibernateProperties">
<property name="location"><value>classpath:config/runtime.properties</value></property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<!-- Spring AOP interceptor used to manage sessions -->
<bean id="hibernateInterceptor" class="org.springframework.orm.hibernate.HibernateInterceptor">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<bean id="hibernateDaoSupport" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces">
<value>com.onerail.orion.reservation.nontravelproducts.DatabaseHelperInterface,com.onerail.orion.reservation.nontravelftr.DatabaseHelperInterface2</value>
</property>
<property name="interceptorNames">
<list>
<value>hibernateInterceptor</value>
</list>
</property>
</bean>
<!-- To set properties that reference other beans <ref>, subelement of <property> is used as shown below -->
<bean id="PersonHelper" class="com.test.PersonHelper" scope="prototype">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
</beans>
In web.xml
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
package com.onerail.orion.common.hibernate.config;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import java.util.Properties;
public class HibernateProperties extends PropertyPlaceholderConfigurer
implements InitializingBean {
private static Logger logger = SystemLog.getLogger(HibernateProperties.class);
private static boolean started = false;
private static Properties prop = new Properties();
protected String resolvePlaceholder(String s, Properties properties) {
if (started == false) {
synchronized (prop) {
if (started == false)
{
Constants.purge();
prop.setProperty("hibernate.connection.username", Constants.getDbUser());
prop.setProperty("hibernate.connection.password", Constants.getDbPassword());
prop.setProperty("hibernate.connection.url", Constants.getDatabaseUrl());
prop.setProperty("hibernate.connection.driver_class", Constants.getDbDrivers());
started = true;
}
}
}
if (prop.get(s) != null)
return (String) prop.get(s);
return super.resolvePlaceholder(s, properties);
}
public void afterPropertiesSet() throws Exception {
}
}
EXAMPLES USING Spring's BeanFactory class gives configuration framework and basic functionality (bean managing)
public interface PersonIF
{
public String getPersonAddress(String name);
}
public class PersonImpl implements PersonIF
{
private String address;
private int age;
private PersonRole personRole;
public PersonImpl(int myAge)
{
this.age = myAge;
}
public PersonImpl(PersonRole personRole)
{
this.personRole = personRole;
}
public String getAddress(String name)
{
return DatabaseHelper.getAddress(name);
}
public void setAddress(String myAddress)
{
this.address = myAddress;
}
public String getPersonRole(String name)
{
return DatabaseHelper.getRoles(name);
}
public void setPersonRoles(String role)
{
this.role = role;
}
}
public class PersonRole
{
String roleName;
public String getRole()
{
return role;
}
public void setRole(String roleName)
{
this.roleName = roleName;
}
}
Add person.xml as follows:
<beans>
<beans>
<bean id="personBean" class="test.PersonImpl">
<constructor-arg><ref bean="personRoleBean"/></constructor-arg>
<property name="address">
<value>50 Grand Central Road</value>
</property>
<property name="personRole">
<ref local="personRoleBean"/>
</property>
</bean>
<bean id="personRoleBean" class="test.PersonRole"/>
</beans>
TEST class
public class PersonTest
{
public static void main(String args[]) throws Exception
{
try
{
Resource resource = new ClassPathResource("person.xml");
BeanFactory factory = new XmlBeanFactory(resource);
Person personBean = (Person)factory.getBean("personBean");
System.out.println(personBean.getAddress(args[0]));
}
catch(Exception e)
{
e.printStackTrace(e);
}
}
}
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
public class PersonTest
{
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception
{
ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServlet().getServletContext());
//ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(config.getServletContext());
//ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
PersonHelper personHelper = (PersonHelper) context.getBean("PersonHelper");
List personList = (List)personHelper.getPersonList();
}
}
public class PersonHelper extends HibernateDaoSupport implements DatabaseHelperInterface
{
public List getPersonList() throws PersonDAOException
{
Session session = SessionFactoryUtils.getSession(this.getSessionFactory(), false);
List personList = new ArrayList();
try {
Query query = session.createQuery("from com.test.Person as person order by perosn.personName");
Iterator it = query.iterate();
while (it.hasNext()) {
Person person = (Person) it.next();
personList.add(person);
}
return personList;
}
catch (HibernateException ex)
{
throw new PersonDAOException("getPersonList(): " + ex.getMessage());
}
finally
{
try
{
session.close();
}
catch (HibernateException ex)
{
logger.fatal(ex);
}
}
}
}
import net.sf.hibernate.SessionFactory;
public interface DatabaseHelperInterface {
public SessionFactory getSessionFactory();
public void setSessionFactory(SessionFactory sessionFactory);
}
In applicationContext.xml
<bean id="sessionFactory" class="org.springframework.orm.hibernate.LocalSessionFactoryBean">
<property name="mappingResources">
<list>
<value>com/onerail/orion/common/hibernate/bean/Person.hbm.xml</value>
<value>com/onerail/orion/common/hibernate/bean/PersonRoles.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.connection.username">${hibernate.connection.username}</prop>
<prop key="hibernate.connection.password">${hibernate.connection.password}</prop>
<prop key="hibernate.connection.url">${hibernate.connection.url}</prop>
<prop key="hibernate.dialect">net.sf.hibernate.dialect.InformixDialect</prop>
<prop key="hibernate.connection.driver_class">${hibernate.connection.driver_class}</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.use_outer_join">true</prop>
<prop key="hibernate.transaction.factory_class">net.sf.hibernate.transaction.JDBCTransactionFactory</prop>
<prop key="hibernate.dbcp.minIdle">1</prop>
<!-- <prop key="hibernate.cache.use_query_cache">true</prop> -->
<!-- <prop key="hibernate.connection.pool_size">3</prop> -->
<!-- <prop key="hibernate.cache.provider_class">com.onerail.orion.common.hibernate.patch.OSCacheProvider</prop> -->
<prop key="hibernate.cglib.use_reflection_optimizer">false</prop>
<prop key="hibernate.c3p0.min_size">5</prop>
<prop key="hibernate.c3p0.max_size">20</prop>
<prop key="hibernate.c3p0.timeout">1800</prop>
<prop key="hibernate.c3p0.max_statements">50</prop>
</props>
</property>
</bean>
<!-- placeholderConfig loads extra configuration information which is placed into the expressions eg ${com.test.util.constants.dbUser} -->
<bean id="placeholderConfig"
class="com.onerail.orion.common.hibernate.config.HibernateProperties">
<property name="location"><value>classpath:config/runtime.properties</value></property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<!-- Spring AOP interceptor used to manage sessions -->
<bean id="hibernateInterceptor" class="org.springframework.orm.hibernate.HibernateInterceptor">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<bean id="hibernateDaoSupport" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces">
<value>com.onerail.orion.reservation.nontravelproducts.DatabaseHelperInterface,com.onerail.orion.reservation.nontravelftr.DatabaseHelperInterface2</value>
</property>
<property name="interceptorNames">
<list>
<value>hibernateInterceptor</value>
</list>
</property>
</bean>
<!-- To set properties that reference other beans <ref>, subelement of <property> is used as shown below -->
<bean id="PersonHelper" class="com.test.PersonHelper" scope="prototype">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
</beans>
In web.xml
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
package com.onerail.orion.common.hibernate.config;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import java.util.Properties;
public class HibernateProperties extends PropertyPlaceholderConfigurer
implements InitializingBean {
private static Logger logger = SystemLog.getLogger(HibernateProperties.class);
private static boolean started = false;
private static Properties prop = new Properties();
protected String resolvePlaceholder(String s, Properties properties) {
if (started == false) {
synchronized (prop) {
if (started == false)
{
Constants.purge();
prop.setProperty("hibernate.connection.username", Constants.getDbUser());
prop.setProperty("hibernate.connection.password", Constants.getDbPassword());
prop.setProperty("hibernate.connection.url", Constants.getDatabaseUrl());
prop.setProperty("hibernate.connection.driver_class", Constants.getDbDrivers());
started = true;
}
}
}
if (prop.get(s) != null)
return (String) prop.get(s);
return super.resolvePlaceholder(s, properties);
}
public void afterPropertiesSet() throws Exception {
}
}
EXAMPLES USING Spring's BeanFactory class gives configuration framework and basic functionality (bean managing)
public interface PersonIF
{
public String getPersonAddress(String name);
}
public class PersonImpl implements PersonIF
{
private String address;
private int age;
private PersonRole personRole;
public PersonImpl(int myAge)
{
this.age = myAge;
}
public PersonImpl(PersonRole personRole)
{
this.personRole = personRole;
}
public String getAddress(String name)
{
return DatabaseHelper.getAddress(name);
}
public void setAddress(String myAddress)
{
this.address = myAddress;
}
public String getPersonRole(String name)
{
return DatabaseHelper.getRoles(name);
}
public void setPersonRoles(String role)
{
this.role = role;
}
}
public class PersonRole
{
String roleName;
public String getRole()
{
return role;
}
public void setRole(String roleName)
{
this.roleName = roleName;
}
}
Add person.xml as follows:
<beans>
<beans>
<bean id="personBean" class="test.PersonImpl">
<constructor-arg><ref bean="personRoleBean"/></constructor-arg>
<property name="address">
<value>50 Grand Central Road</value>
</property>
<property name="personRole">
<ref local="personRoleBean"/>
</property>
</bean>
<bean id="personRoleBean" class="test.PersonRole"/>
</beans>
TEST class
public class PersonTest
{
public static void main(String args[]) throws Exception
{
try
{
Resource resource = new ClassPathResource("person.xml");
BeanFactory factory = new XmlBeanFactory(resource);
Person personBean = (Person)factory.getBean("personBean");
System.out.println(personBean.getAddress(args[0]));
}
catch(Exception e)
{
e.printStackTrace(e);
}
}
}
Tuesday, June 17, 2008
XSD sample elements
Example shows how to create simple xsd elements
<xs:complexType name="PersonDetailObject">
<xs:sequence>
<xs:element name="PersonId" type="xs:string" minOccurs="0"/>
<xs:element name="Title" type="xs:string" minOccurs="0"/>
<xs:element name="FirstName" type="xs:string" minOccurs="0"/>
<xs:element name="MiddleName" type="xs:string" minOccurs="0"/>
<xs:element name="LastName" type="xs:string" minOccurs="0"/>
<xs:element name="AddressDetails" type="PersonAddressObject" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
Details of a person:-
<xs:element name="PersonRetrieve">
<xs:complexType>
<xs:sequence>
<xs:element ref="EducationInfo"/>
<xs:element name="PersonDetail" type="PersonDetailObject" minOccurs="0" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="EducationInfo">
<xs:complexType>
<xs:sequence>
<xs:element name="Degree" type="xs:string"/>
<xs:element name="University" type="xs:string"/>
<xs:element name="Specialization" type="xs:string" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:element>
Search for number of persons:-
<xs:element name="PersonSearch">
<xs:complexType>
<xs:sequence>
<xs:element ref="EducationInfo"/>
<xs:element name="PersonList" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element name="PersonSummary" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="PersonId" type="xs:string"/>
<xs:element name="LastName" type="xs:string" minOccurs="0"/>
<xs:element name="FirstName" type="xs:string" minOccurs="0"/>
<xs:element name="Email" type="xs:string" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="TotalRecordCount" type="xs:int"/>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name="PersonDetailObject">
<xs:sequence>
<xs:element name="PersonId" type="xs:string" minOccurs="0"/>
<xs:element name="Title" type="xs:string" minOccurs="0"/>
<xs:element name="FirstName" type="xs:string" minOccurs="0"/>
<xs:element name="MiddleName" type="xs:string" minOccurs="0"/>
<xs:element name="LastName" type="xs:string" minOccurs="0"/>
<xs:element name="AddressDetails" type="PersonAddressObject" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
Details of a person:-
<xs:element name="PersonRetrieve">
<xs:complexType>
<xs:sequence>
<xs:element ref="EducationInfo"/>
<xs:element name="PersonDetail" type="PersonDetailObject" minOccurs="0" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="EducationInfo">
<xs:complexType>
<xs:sequence>
<xs:element name="Degree" type="xs:string"/>
<xs:element name="University" type="xs:string"/>
<xs:element name="Specialization" type="xs:string" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:element>
Search for number of persons:-
<xs:element name="PersonSearch">
<xs:complexType>
<xs:sequence>
<xs:element ref="EducationInfo"/>
<xs:element name="PersonList" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element name="PersonSummary" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="PersonId" type="xs:string"/>
<xs:element name="LastName" type="xs:string" minOccurs="0"/>
<xs:element name="FirstName" type="xs:string" minOccurs="0"/>
<xs:element name="Email" type="xs:string" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="TotalRecordCount" type="xs:int"/>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
JSON with AJAX
Example shown to use AJAX and JSON to dynamically populate a dropist.
When droplist 1 is changed, droplist 2 get refreshed with data sent from the server through an AJAX call in a JSON format.
Droplist 1
<html:select property="personCode" onchange="getPersonType();">
<html:option value="" > </html:option>
<html:options property="personCodeList"/>
</html:select>
Droplist 2
<html:select property="personType">
</html:select>
<script>
function getPersonType()
{
var selBox = document.personViewForm.personCode;
var personCode = selBox.options[selBox.selectedIndex].value;
var url = "/Orion/ajax.do?method=getPersonType&personCode="personCode;
var jsonReq = new Json.Remote(url, {
async: false,
autoCancel:true,
onComplete : function(personTypeList){ populatePersonType(personTypeList);
}}).send();
}
function populatePersonType(personTypeList)
{
var selBox = document.personViewForm.personType;
selBox.options.length = 0 ;
selBox.options[0] = new Option("", "");
for(i=0, len=personTypeList.length ; i<len ; i++)
{
selBox.options[i+1] = new Option(personTypeList[i], personTypeList[i]);
}
}
</script>
import net.sf.json.JSONArray;
import org.apache.struts.action.Action;
public class AjaxAction extends Action
{
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
// this Action is not mapped to a form and does not use a JSP for view,
// thus form and mapping and not neccessary
try {
String method = request.getParameter("method");
if("getPersonType".equals(method))
{
doGetPersonType(request, response);
}
else{
// send an error if "no such method"
doTheExceptionThing(request, response);
}
} catch (Exception ex) {
doTheExceptionThing(request, response);
}
return null;
}
private void doGetPersonType(HttpServletRequest request, HttpServletResponse response)
throws IOException
{
String personCode = request.getParameter("personCode");
List<String> list = DatabaseHelper.getPersonTypeList(personCode);
JSONArray array = JSONArray.fromObject(list);
String s = array.toString();
response.setContentLength(s.length());
PrintWriter output = response.getWriter();
output.print(s);
output.close();
}
private void doTheExceptionThing(HttpServletRequest request, HttpServletResponse response) throws Exception {
// since this action is used by a background Javascript invocation, there's not much error to be sent
// or seen by the client. We'll just send a generic error message.
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("error");
}
}
Required libraries - json-lib-2.1-jdk15.jar, mootools.js
When droplist 1 is changed, droplist 2 get refreshed with data sent from the server through an AJAX call in a JSON format.
Droplist 1
<html:select property="personCode" onchange="getPersonType();">
<html:option value="" > </html:option>
<html:options property="personCodeList"/>
</html:select>
Droplist 2
<html:select property="personType">
</html:select>
<script>
function getPersonType()
{
var selBox = document.personViewForm.personCode;
var personCode = selBox.options[selBox.selectedIndex].value;
var url = "/Orion/ajax.do?method=getPersonType&personCode="personCode;
var jsonReq = new Json.Remote(url, {
async: false,
autoCancel:true,
onComplete : function(personTypeList){ populatePersonType(personTypeList);
}}).send();
}
function populatePersonType(personTypeList)
{
var selBox = document.personViewForm.personType;
selBox.options.length = 0 ;
selBox.options[0] = new Option("", "");
for(i=0, len=personTypeList.length ; i<len ; i++)
{
selBox.options[i+1] = new Option(personTypeList[i], personTypeList[i]);
}
}
</script>
import net.sf.json.JSONArray;
import org.apache.struts.action.Action;
public class AjaxAction extends Action
{
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception {
// this Action is not mapped to a form and does not use a JSP for view,
// thus form and mapping and not neccessary
try {
String method = request.getParameter("method");
if("getPersonType".equals(method))
{
doGetPersonType(request, response);
}
else{
// send an error if "no such method"
doTheExceptionThing(request, response);
}
} catch (Exception ex) {
doTheExceptionThing(request, response);
}
return null;
}
private void doGetPersonType(HttpServletRequest request, HttpServletResponse response)
throws IOException
{
String personCode = request.getParameter("personCode");
List<String> list = DatabaseHelper.getPersonTypeList(personCode);
JSONArray array = JSONArray.fromObject(list);
String s = array.toString();
response.setContentLength(s.length());
PrintWriter output = response.getWriter();
output.print(s);
output.close();
}
private void doTheExceptionThing(HttpServletRequest request, HttpServletResponse response) throws Exception {
// since this action is used by a background Javascript invocation, there's not much error to be sent
// or seen by the client. We'll just send a generic error message.
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("error");
}
}
Required libraries - json-lib-2.1-jdk15.jar, mootools.js
Monday, June 16, 2008
Utility Tools
- For screen capture - ZapGrab
- For using unix commands in windows - Open command window here (Microsoft PowerToys for Windows XP)
- For merging files - WinMerge
- For editing files - EditPlus
- For unix session - putty
- For latitude and longitude - Google Earth
- For using unix commands in windows - Open command window here (Microsoft PowerToys for Windows XP)
- For merging files - WinMerge
- For editing files - EditPlus
- For unix session - putty
- For latitude and longitude - Google Earth
Inspect an element through javascript
Javascript utility function to inspect an element and see the properties and methods attached to it.
function inspect(elm)
{
var str = "";
for (var i in elm)
{
str += i + ": " + elm.getAttribute(i) + "\n";
}
alert(str);
}
table = document.getElementById("tableMain");
inspect(table);
function inspect(elm)
{
var str = "";
for (var i in elm)
{
str += i + ": " + elm.getAttribute(i) + "\n";
}
alert(str);
}
table = document.getElementById("tableMain");
inspect(table);
Alert struts error messages
To alert struts error messages in JSP's
<script language="javascript">
var errors = '<html:errors/>';
if(errors != '')
alert(errors);
</script>
<script language="javascript">
var errors = '<html:errors/>';
if(errors != '')
alert(errors);
</script>
Uppercase a field value through javascript
To uppercase a field value through javascript:
<input type="text" name="personName" value="" onblur="javascript:toUpper(this);" />
function toUpper(cur){
cur.value=cur.value.toUpperCase();
}
<input type="text" name="personName" value="" onblur="javascript:toUpper(this);" />
function toUpper(cur){
cur.value=cur.value.toUpperCase();
}
Dynamically display a struts radio button
To dynamically display a radio button with struts iteration, use:
<logic:iterate id="row" name="SHIPPERS">
<html:radio property="expectedVia" value="value" idName="row"/>
<bean:write name="row" property="label"/>
</logic:iterate
<logic:iterate id="row" name="SHIPPERS">
<html:radio property="expectedVia" value="value" idName="row"/>
<bean:write name="row" property="label"/>
</logic:iterate
Preselect struts radio buttons
To preselect a struts radio button"
You can make the radio button checked by declaring the attribute corresponding to radio button as String and providing the default value in FormBean.
For example,
declare and define radio button attribute in FormBean
private String gender = "female";
Now in JSP
<html:radio property="gender" value="female">Female</html:radio>
<html:radio property="gender" value="male">Male</html:radio>
since the value of property gender matches with that of attribute gender in FormBean, the radio button with value female gets checked.
You can make the radio button checked by declaring the attribute corresponding to radio button as String and providing the default value in FormBean.
For example,
declare and define radio button attribute in FormBean
private String gender = "female";
Now in JSP
<html:radio property="gender" value="female">Female</html:radio>
<html:radio property="gender" value="male">Male</html:radio>
since the value of property gender matches with that of attribute gender in FormBean, the radio button with value female gets checked.
Create a HashSet
This example shows how to create a Set and add objects to it.
Unlike classes implementing the List interface, a Set class doesn't allow the same value to be stored twice.
import java.util.HashSet;
import java.util.Set;
public class HashSetExample {
/**
* Example method for using a Set
*/
public void hashSetExample() {
Set personType = new HashSet();
//Add the items to the Set
personType.add("student);
personType.add("employee);
personType.add("pensioner);
}
}
Unlike classes implementing the List interface, a Set class doesn't allow the same value to be stored twice.
import java.util.HashSet;
import java.util.Set;
public class HashSetExample {
/**
* Example method for using a Set
*/
public void hashSetExample() {
Set personType = new HashSet();
//Add the items to the Set
personType.add("student);
personType.add("employee);
personType.add("pensioner);
}
}
Some helpful Unix commands
VI COMMANDS
> Move cursor
> h (left) j (down) k (up) l (right)
> w Move forward one WORD.
> b Move BACK one word.
> e Move to END of word.
> ^ u Scroll UP a partial screen.
> ^ d Scroll DOWN a partial screen.
> ^ f Scroll FORWARD a full screen (page down).
> ^ b Scroll BACKWARD a full screen (page up).
> - Move up one line.
> [ret] Return, move down one line.
> 0 (zero) Move to BEGINNING of line.
> $ Move to END of line.
> G Go to END of file.
> n G Go to line number n.
>
> Search
> /text [RET] SEARCH for text.
> / [RET] CONTINUE search for previous text.
> ?text Search backwards for text.
>
> vi CHANGES
> s SUBSTITUTE for character.
> S SUBSTITUTE for line.
> i text [Esc] INSERT text before cursor.
> cw text [Esc] CHANGE word to text.
> c3w text [Esc] Change 3 words to text.
> C text [Esc] Change rest of line to text.
> cc text [Esc] Change line to text.
> x DELETE single character.
> r p REPLACE single character with p.
> R text [esc] Replace (type over) characters with text.
> dw DELETE word (4dw deletes 4 words).
> dd DELETE line (3dd deletes 3 lines).
> D DELETE from cursor to end of line.
> u UNDO last change (remember this one).
> U UNDO all changes to line (don't forget this one).
> s SUBSTITUTE character.
> S SUBSTITUTE lines.
> J JOIN lines.
> a text [Esc] ADD text after cursor.
> A text [Esc] ADD text to end of line.
> I text [Esc] INSERT text at start of line.
> o text [Esc] OPEN new line below with text.
> O text [Esc]: OPEN new line above with text.
> esc END an insert, replace command.
>
> vi SUBCOMMANDS
> :w fname WRITE (save) fname (default: to present file).
> ZZ EXIT the editor, saving all changes (same as :wq).
> :q! QUIT emphatically, do not save changes (! is your tool to insist;
useful after messing up (also :w temp).
> :e! Edit again previous file, i.e., revert to last saved version.
> :n Edit NEXT file (after vi file1 file2 ...).
> :f Show current FILE name and cursor line number.
>
>
> vi COPY and PASTE
> Y [RET] YANK (copy) current line.
> yy [RET] YANK (copy) current line.
> yw YANK (copy) next word.
> p PUT last thing yanked before cursor.
> P PUT last thing yanked after cursor.
> nb: you can have many buffers with stuff in them
>
i enter input mode before the cursor
I enter input mode at the start of the current line
a enter input mode after the cursor
A enter input mode at the end of the current line
o create a new line below the cursor and enter input mode on it
O create a new line above the cursor and enter input mode on it
/ pattern search forward through the document for the next occurrence of the pattern (or string of text)
? pattern search backward through the document for the next occurrence of the pattern (or string of text)
n repeat search in the same direction
N repeat search in opposite direction
f char search forward from the cursor in the current line for a single character (char)
F char search backward from the cursor in the current line for a single character (char)
; repeat single character search in either direction (f or F)
LESS COMMANDS
>less <>
>g first line
>shift g -> G bottom
>Ctrl u page up
>Ctrl d page down
>/ search
>q quit
....more Useful commands while viewing a file with 'more' or 'less':
scroll forward one page
^b (control-b) scroll backward one page
/ search for string
n find next occurence of string
N find previous occurence of string (search for string in opposite direction)*
g go to the beginning of the file*
G go to the end of the file*
v edit the current file with 'vi'*
:n go to the next file*
:p go to the previous file*
q quit
To enable bash
bash
To clear screen
CLEAR
To find a process
ps -ef | grep SUNW
ps -ef | grep SUNW* | grep app
To kill a process
kill -9 << process>>
FIND / GREP commands
-This command will avoid the printing of files without permission
find . -name *mylog.log* 2>/dev/null
grep "Exception:"
grep -i "vxcv" (ignores case)
-unzip tar
gunzip docs-Orion.tar.gz
tar -xvf docs-Orion.tar
-unjar
jar xf jar-file
-read the timestamp of a file
ls -al ./applications/j2ee-modules/WEB-INF/classes/config/runtime.properties
- compare two directories (pg - page by page)
diff -r ./firstwar ./secondwar | pg
- to get system date and time
date
- whoami
- id
- remove dir
rmdir -f * (forces remove all direc in that location)
rmdir docs-Orion
To go back to the prevoius directory
cd -
Go to home directory
cd ~ (or)
cd
Shows the latest files in order
- ls -alrt
- To sort a app process
ps -ef | grep app |sort
To remove files recursively from a dir
cd work
rm -rf *
If file is full, to check
du -sh *
To gzip files
gzip *2008*
Cronjobs
To check cronjobs
>crontab -l
We may read the result in reverse order
5 0 * * * /opt/home/server/bin/run_nfm.sh
(time is in reverse order - min hours day month year)
To check whether a user is available or not
cat /etc/passwd
> Move cursor
> h (left) j (down) k (up) l (right)
> w Move forward one WORD.
> b Move BACK one word.
> e Move to END of word.
> ^ u Scroll UP a partial screen.
> ^ d Scroll DOWN a partial screen.
> ^ f Scroll FORWARD a full screen (page down).
> ^ b Scroll BACKWARD a full screen (page up).
> - Move up one line.
> [ret] Return, move down one line.
> 0 (zero) Move to BEGINNING of line.
> $ Move to END of line.
> G Go to END of file.
> n G Go to line number n.
>
> Search
> /text [RET] SEARCH for text.
> / [RET] CONTINUE search for previous text.
> ?text Search backwards for text.
>
> vi CHANGES
> s SUBSTITUTE for character.
> S SUBSTITUTE for line.
> i text [Esc] INSERT text before cursor.
> cw text [Esc] CHANGE word to text.
> c3w text [Esc] Change 3 words to text.
> C text [Esc] Change rest of line to text.
> cc text [Esc] Change line to text.
> x DELETE single character.
> r p REPLACE single character with p.
> R text [esc] Replace (type over) characters with text.
> dw DELETE word (4dw deletes 4 words).
> dd DELETE line (3dd deletes 3 lines).
> D DELETE from cursor to end of line.
> u UNDO last change (remember this one).
> U UNDO all changes to line (don't forget this one).
> s SUBSTITUTE character.
> S SUBSTITUTE lines.
> J JOIN lines.
> a text [Esc] ADD text after cursor.
> A text [Esc] ADD text to end of line.
> I text [Esc] INSERT text at start of line.
> o text [Esc] OPEN new line below with text.
> O text [Esc]: OPEN new line above with text.
> esc END an insert, replace command.
>
> vi SUBCOMMANDS
> :w fname WRITE (save) fname (default: to present file).
> ZZ EXIT the editor, saving all changes (same as :wq).
> :q! QUIT emphatically, do not save changes (! is your tool to insist;
useful after messing up (also :w temp).
> :e! Edit again previous file, i.e., revert to last saved version.
> :n Edit NEXT file (after vi file1 file2 ...).
> :f Show current FILE name and cursor line number.
>
>
> vi COPY and PASTE
> Y [RET] YANK (copy) current line.
> yy [RET] YANK (copy) current line.
> yw YANK (copy) next word.
> p PUT last thing yanked before cursor.
> P PUT last thing yanked after cursor.
> nb: you can have many buffers with stuff in them
>
i enter input mode before the cursor
I enter input mode at the start of the current line
a enter input mode after the cursor
A enter input mode at the end of the current line
o create a new line below the cursor and enter input mode on it
O create a new line above the cursor and enter input mode on it
/ pattern search forward through the document for the next occurrence of the pattern (or string of text)
? pattern search backward through the document for the next occurrence of the pattern (or string of text)
n repeat search in the same direction
N repeat search in opposite direction
f char search forward from the cursor in the current line for a single character (char)
F char search backward from the cursor in the current line for a single character (char)
; repeat single character search in either direction (f or F)
LESS COMMANDS
>less <
>g first line
>shift g -> G bottom
>Ctrl u page up
>Ctrl d page down
>/ search
>q quit
....more Useful commands while viewing a file with 'more' or 'less':
^b (control-b) scroll backward one page
/
n find next occurence of string
N find previous occurence of string (search for string in opposite direction)*
g go to the beginning of the file*
G go to the end of the file*
v edit the current file with 'vi'*
:n go to the next file*
:p go to the previous file*
q quit
To enable bash
bash
To clear screen
CLEAR
To find a process
ps -ef | grep SUNW
ps -ef | grep SUNW* | grep app
To kill a process
kill -9 << process>>
FIND / GREP commands
-This command will avoid the printing of files without permission
find . -name *mylog.log* 2>/dev/null
grep "Exception:"
grep -i "vxcv" (ignores case)
-unzip tar
gunzip docs-Orion.tar.gz
tar -xvf docs-Orion.tar
-unjar
jar xf jar-file
-read the timestamp of a file
ls -al ./applications/j2ee-modules/WEB-INF/classes/config/runtime.properties
- compare two directories (pg - page by page)
diff -r ./firstwar ./secondwar | pg
- to get system date and time
date
- whoami
- id
- remove dir
rmdir -f * (forces remove all direc in that location)
rmdir docs-Orion
To go back to the prevoius directory
cd -
Go to home directory
cd ~ (or)
cd
Shows the latest files in order
- ls -alrt
- To sort a app process
ps -ef | grep app |sort
To remove files recursively from a dir
cd work
rm -rf *
If file is full, to check
du -sh *
To gzip files
gzip *2008*
Cronjobs
To check cronjobs
>crontab -l
We may read the result in reverse order
5 0 * * * /opt/home/server/bin/run_nfm.sh
(time is in reverse order - min hours day month year)
To check whether a user is available or not
cat /etc/passwd
Iterate a Map in jdk1.5
We can Iterate a Map in jdk1.5 as follows:
public void testGetPersonTypeConstants()
{
Collection personTypeCollection = new Collection();
try{
Map constMap = DatabaseHelper.getPersonTypeConstantsList();
for(Entryentry : constMap.entrySet() )
{
System.out.println(entry.getKey()+": "+entry.getValue());
personTypeCollection.add(entry.getValue());
return personTypeCollection;
}
catch(Exception e)
{
rollbackTransaction();
return Collections.emptyList();
}
}
public void testGetPersonTypeConstants()
{
Collection personTypeCollection = new Collection();
try{
Map
for(Entry
{
System.out.println(entry.getKey()+": "+entry.getValue());
personTypeCollection.add(entry.getValue());
return personTypeCollection;
}
catch(Exception e)
{
rollbackTransaction();
return Collections.emptyList();
}
}
Adding attribtes in XML Schema file
If you have troubles adding attribtes in XML Schema file, add extenstion="true" in Ant build file
<xjc schema="${schema.file}" binding="${bindings.file}" package="${package}" target="${jaxb.tmp.src}" extension="true" />
<xjc schema="${schema.file}" binding="${bindings.file}" package="${package}" target="${jaxb.tmp.src}" extension="true" />
To access MessageBundle.properties in java
We can access MessageBundle.properties in java as below:
for e.g. you have MessagesBundle_en.properties file undera /config directory in the project
Access it as below:
String messages = java.util.ResourceBundle.getBundle("config/MessagesBundle_" + language);
String text = messages.getString("confEmail.yourUserID")
for e.g. you have MessagesBundle_en.properties file undera /config directory in the project
Access it as below:
String messages = java.util.ResourceBundle.getBundle("config/MessagesBundle_" + language);
String text = messages.getString("confEmail.yourUserID")
To change the label value dynamically through javascript
We can change the label value dynamically through javascript as follows:
Trick is to make the span as an elementobject with an id
<SCRIPT language=JavaScript>
<!-- Begin
function checkrequired() {
var fields = 0
var i = 0
var empty = true
var fields = document.form1.length
var textvalue = ""
for (i = 0; i < fields ; i++) {
switch (document.form1.elements[i].type){
case "select-one" :
break;
case "select-multiple" :
if (document.form1.elements[i].selectedIndex != -1){
empty = false
}
break;
case "checkbox" :
if ( document.form1.elements[i].checked) {
empty = false
}
break;
default :
break;
}
}
if (!empty) {
document.form1.submit();
} else {
document.getElementById("errortext").innerHTML='Select one or more item';
return false;
}
}
// End -->
</SCRIPT>
<form name=form1 method="POST" action="check.asp">
<SPAN id=errortext>You must check at least one of the available domain
names below to continue.</SPAN><br>
<input type="checkbox" name="k1" value="astim" class="input">
<input type="checkbox" name="k2" value="whax" class="input">
<input onclick="return checkrequired();" type="image" SRC="ok.gif" border="0" name="submitit" >
</form>
Trick is to make the span as an elementobject with an id
<SCRIPT language=JavaScript>
<!-- Begin
function checkrequired() {
var fields = 0
var i = 0
var empty = true
var fields = document.form1.length
var textvalue = ""
for (i = 0; i < fields ; i++) {
switch (document.form1.elements[i].type){
case "select-one" :
break;
case "select-multiple" :
if (document.form1.elements[i].selectedIndex != -1){
empty = false
}
break;
case "checkbox" :
if ( document.form1.elements[i].checked) {
empty = false
}
break;
default :
break;
}
}
if (!empty) {
document.form1.submit();
} else {
document.getElementById("errortext").innerHTML='Select one or more item';
return false;
}
}
// End -->
</SCRIPT>
<form name=form1 method="POST" action="check.asp">
<SPAN id=errortext>You must check at least one of the available domain
names below to continue.</SPAN><br>
<input type="checkbox" name="k1" value="astim" class="input">
<input type="checkbox" name="k2" value="whax" class="input">
<input onclick="return checkrequired();" type="image" SRC="ok.gif" border="0" name="submitit" >
</form>
To move the cursor of a page to a certain location
We can move the cursor of a page to a certain location as indicated below:
Define within a <tr> tag, <a name="#pageTop"></a>
We can either achieve this through a href link as <a class="sub" href="#pageTop">Return Top Of Page</a>
Or
Achieve this through a javscript method as window.location.hash= "#pageTop";
Define within a <tr> tag, <a name="#pageTop"></a>
We can either achieve this through a href link as <a class="sub" href="#pageTop">Return Top Of Page</a>
Or
Achieve this through a javscript method as window.location.hash= "#pageTop";
Prevent Browser cache for window.open
To prevent Browser caches for window.open
- IF you close and open the browser, it would work fine, however to programtically prevent this, pass in the URL so that it contains a unique element as below:
function openCustomConfirm()
{
var randomTime = (new Date).getTime();
if (confirm("Do you want to view your details"))
{
window.open('/MyServer/PersonServletDispatcher?functionName=View&time='+randomTime,'_parent');
}
}
- To reload a page, use location.reload(). However, this depends upon the cache headers that your server sends. To change this, you need to alter the server configuration.
- A quick fix on the client is to change the page URI so that it contains a unique element, such as the current time.
- For example: location.replace(location.href+'?d='+new Date().valueOf())
If the location.href already contains a Query String, use: location.replace(location.href+'&d='+new Date().valueOf())
- IF you close and open the browser, it would work fine, however to programtically prevent this, pass in the URL so that it contains a unique element as below:
function openCustomConfirm()
{
var randomTime = (new Date).getTime();
if (confirm("Do you want to view your details"))
{
window.open('/MyServer/PersonServletDispatcher?functionName=View&time='+randomTime,'_parent');
}
}
- To reload a page, use location.reload(). However, this depends upon the cache headers that your server sends. To change this, you need to alter the server configuration.
- A quick fix on the client is to change the page URI so that it contains a unique element, such as the current time.
- For example: location.replace(location.href+'?d='+new Date().valueOf())
If the location.href already contains a Query String, use: location.replace(location.href+'&d='+new Date().valueOf())
Pass values between java and javascript
add java to javascript:-
<script type="text/javascript" xml:space="preserve">
document.getElementById("latitude").value="<%=latitude%>";
document.getElementById("longitude").value="<%=longitude%>";
alert(document.getElementById("longitude").value);
</script>
add javscript to java:-
<%
String selectForAdd;
selectForAdd = "javascript:document.personViewForm.PKpersonItemType.value='javascript:document.personViewForm.personType.value';";
selectForAdd += "document.personViewForm.PKpersonItemCode.value='javascript:document.personViewForm.personItemCode.value';";
selectForAdd +="document.personViewForm.PKpersonItemLang.value='javascript:document.personViewForm.personItemLang.value';";
selectForAdd +="document.personViewForm.pageMode.value='addChild';";
%>
Then we can send this variable in a button click
<input type="button" name="select" onClick="<%= selectForAdd%>" />
add strtus to javascript:-
<bean:define name="res" property="bkClasses" id="selectedClass"/>
<script>
oldBkClasses[oldBkClasses.length]='<bean:write name="selectedClass"/>';
</script>
To access a javascript value at the server end:-
create a hidden field on the jsp and set it with the desired value. This will be submitted to the server as a request parameter
<script type="text/javascript" xml:space="preserve">
document.getElementById("latitude").value="<%=latitude%>";
document.getElementById("longitude").value="<%=longitude%>";
alert(document.getElementById("longitude").value);
</script>
add javscript to java:-
<%
String selectForAdd;
selectForAdd = "javascript:document.personViewForm.PKpersonItemType.value='javascript:document.personViewForm.personType.value';";
selectForAdd += "document.personViewForm.PKpersonItemCode.value='javascript:document.personViewForm.personItemCode.value';";
selectForAdd +="document.personViewForm.PKpersonItemLang.value='javascript:document.personViewForm.personItemLang.value';";
selectForAdd +="document.personViewForm.pageMode.value='addChild';";
%>
Then we can send this variable in a button click
<input type="button" name="select" onClick="<%= selectForAdd%>" />
add strtus to javascript:-
<bean:define name="res" property="bkClasses" id="selectedClass"/>
<script>
oldBkClasses[oldBkClasses.length]='<bean:write name="selectedClass"/>';
</script>
To access a javascript value at the server end:-
create a hidden field on the jsp and set it with the desired value. This will be submitted to the server as a request parameter
Disable right click menu
To disable right click menu, can use the following script
document.oncontextmenu = function() {
return false;
}
document.oncontextmenu = function() {
return false;
}
Steps to make Tomcat run as Https
Steps to make Tomcat https are as below:
- Edit server.xml
Uncomment the below code in the XMl file
<Connector port="8443"
maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" disableUploadTimeout="true"
acceptCount="100" debug="0" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS" />
- open cmd window in C:\Program Files\Java\jdk1.5.0_08\bin
C:\Program Files\Java\jdk1.5.0_08\bin> keytool -genkey -alias tomcat -keyalg RSA (for Windows)
and follow the prompts
password = changeit (for both keystore password and key password for tomcat)
- other useful commands
keytool -help
keytool -delete -alias tomcat
- Edit server.xml
Uncomment the below code in the XMl file
<Connector port="8443"
maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" disableUploadTimeout="true"
acceptCount="100" debug="0" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS" />
- open cmd window in C:\Program Files\Java\jdk1.5.0_08\bin
C:\Program Files\Java\jdk1.5.0_08\bin> keytool -genkey -alias tomcat -keyalg RSA (for Windows)
and follow the prompts
password = changeit (for both keystore password and key password for tomcat)
- other useful commands
keytool -help
keytool -delete -alias tomcat
Bridge design pattern
The Bridge Pattern is used to separate out the interface from its implementation. Doing this gives the flexibility so that both can vary independently.
public class PersonViewAction extends ActionBase
{
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception
{
if (form.isBtnSave())
{
PersonHelper helper = new PersonHelper(form.getPerson);
helper.doUpdate();
Person person = helper.getPerson();
}
}
}
public class PersonHelper implements PersonHelperAbstractIF
{
private Person person = new Person();
private PersonAccessorIF personDelegate = new PersonAccessorXML();
public PersonHelper()
{
super();
}
public PersonHelper(Person person){
this.person = person;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
public List doSearch()throws Exception{
return personDelegate.getPersonSearchResults(this.person);
}
public void doRetrieve()throws ProcessingException{
this.person = personDelegate.retrievePersonProfile(this.person.getId);
}
public void doAdd() throws ProcessingException{
this.person = personDelegate.addPersonProfile(this.person)
}
public void doUpdate()throws ProcessingException{
this.person = personDelegate.updatePersonProfile(this.person);
}
public boolean doDelete(){
personDelegate.deletePersonProfile();
}
}
public interface PersonAccessorIF {
public Person retrievePersonProfile(Integer personId)throws ProcessingException;
public List getPersonSearchResults(Person person)throws Exception;
public Person addPersonProfile(Person person)throws ProcessingException;
public Person updatePersonProfile(Person person)throws ProcessingException;
}
public class PersonAccessorXML implements PersonAccessorIF{
public PersonAccessorXML(){
super();
}
public Person retrievePersonProfile(Integer personId)throws ProcessingException
{
// actual implementation - maybe send a XML message to another system
}
public List getPersonSearchResults(AgentProfile agent, MemberCustomerProfileSearchBean searchBean)throws ProcessingException, IOException{
return null;
}
public Person addPersonProfile(AgentProfile agent, MemberCustomerProfile customer){
return null;
}
public Person updatePersonProfile(AgentProfile agent, MemberCustomerProfile customer){
return null;
}
}
public class PersonAccessorDB implements PersonAccessorIF{
public Person retrievePersonProfile(AgentProfile agent, Integer customerId, Integer memberProfileId){
// different kind of implementation to PersonAccessorXML - maybe access the database to get the result
}
public List getPersonSearchResults(AgentProfile agent, MemberCustomerProfileSearchBean searchBean)throws ProcessingException, IOException{
return null;
}
public Person addPersonProfile(AgentProfile agent, MemberCustomerProfile customer){
return null;
}
public Person updatePersonProfile(AgentProfile agent, MemberCustomerProfile customer){
return null;
}
}
Now if we were to change the backend processing (say from sending XML message to another system TO say database access, we can easily change the functionality in the PersonHelper class by just modifying a line of code like below:
private PersonAccessorIF personDelegate = new PersonAccessorDB();
public class PersonViewAction extends ActionBase
{
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception
{
if (form.isBtnSave())
{
PersonHelper helper = new PersonHelper(form.getPerson);
helper.doUpdate();
Person person = helper.getPerson();
}
}
}
public class PersonHelper implements PersonHelperAbstractIF
{
private Person person = new Person();
private PersonAccessorIF personDelegate = new PersonAccessorXML();
public PersonHelper()
{
super();
}
public PersonHelper(Person person){
this.person = person;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
public List doSearch()throws Exception{
return personDelegate.getPersonSearchResults(this.person);
}
public void doRetrieve()throws ProcessingException{
this.person = personDelegate.retrievePersonProfile(this.person.getId);
}
public void doAdd() throws ProcessingException{
this.person = personDelegate.addPersonProfile(this.person)
}
public void doUpdate()throws ProcessingException{
this.person = personDelegate.updatePersonProfile(this.person);
}
public boolean doDelete(){
personDelegate.deletePersonProfile();
}
}
public interface PersonAccessorIF {
public Person retrievePersonProfile(Integer personId)throws ProcessingException;
public List getPersonSearchResults(Person person)throws Exception;
public Person addPersonProfile(Person person)throws ProcessingException;
public Person updatePersonProfile(Person person)throws ProcessingException;
}
public class PersonAccessorXML implements PersonAccessorIF{
public PersonAccessorXML(){
super();
}
public Person retrievePersonProfile(Integer personId)throws ProcessingException
{
// actual implementation - maybe send a XML message to another system
}
public List getPersonSearchResults(AgentProfile agent, MemberCustomerProfileSearchBean searchBean)throws ProcessingException, IOException{
return null;
}
public Person addPersonProfile(AgentProfile agent, MemberCustomerProfile customer){
return null;
}
public Person updatePersonProfile(AgentProfile agent, MemberCustomerProfile customer){
return null;
}
}
public class PersonAccessorDB implements PersonAccessorIF{
public Person retrievePersonProfile(AgentProfile agent, Integer customerId, Integer memberProfileId){
// different kind of implementation to PersonAccessorXML - maybe access the database to get the result
}
public List getPersonSearchResults(AgentProfile agent, MemberCustomerProfileSearchBean searchBean)throws ProcessingException, IOException{
return null;
}
public Person addPersonProfile(AgentProfile agent, MemberCustomerProfile customer){
return null;
}
public Person updatePersonProfile(AgentProfile agent, MemberCustomerProfile customer){
return null;
}
}
Now if we were to change the backend processing (say from sending XML message to another system TO say database access, we can easily change the functionality in the PersonHelper class by just modifying a line of code like below:
private PersonAccessorIF personDelegate = new PersonAccessorDB();
Friday, June 13, 2008
Using JSTL tags with struts and javascript
We can use jstl tag library and struts together to get rich programming
For this you need to import java.sun.com/jstl/core_rt" prefix="c" in your jsp
<c:set var="displayOption" value="${0}"/>
<nested:iterate id="serviceRepStn" name="resultList" property="stations" indexId="indexId">
<c:set var="displayOption" value="${indexId}"/>
<td>
<nested:text property="srrpStops" styleClass="stops" readonly="true"
styleId="stops${displayOption}"/>
</td>
//We can access the text element in javascript as below
var stopsCollect = document.forms[0].elements["stops${displayOption}"];
// If the text fields are dynamically generated and we do not know whether an array of srrpStops or single element will be passed to us in the request, we can handle it as below
var sum = 0;
var stopsCollect = document.forms[0].elements["stops${displayOption}"];
if(stopsCollect.length == undefined)
{
stopsCollect = document.forms[0].stops${displayOption-1};
if (!isNaN(parseFloat(stopsCollect.value)))
{
sum += parseFloat(stopsCollect.value);
alert("Sum : " + sum);
}
}
else
{
for (var i = 0; i < stopsCollect.length; i++)
{
if (!isNaN(parseFloat(stopsCollect[i].value)))
{
sum += parseFloat(stopsCollect[i].value);
}
}
}
For this you need to import java.sun.com/jstl/core_rt" prefix="c" in your jsp
<c:set var="displayOption" value="${0}"/>
<nested:iterate id="serviceRepStn" name="resultList" property="stations" indexId="indexId">
<c:set var="displayOption" value="${indexId}"/>
<td>
<nested:text property="srrpStops" styleClass="stops" readonly="true"
styleId="stops${displayOption}"/>
</td>
//We can access the text element in javascript as below
var stopsCollect = document.forms[0].elements["stops${displayOption}"];
// If the text fields are dynamically generated and we do not know whether an array of srrpStops or single element will be passed to us in the request, we can handle it as below
var sum = 0;
var stopsCollect = document.forms[0].elements["stops${displayOption}"];
if(stopsCollect.length == undefined)
{
stopsCollect = document.forms[0].stops${displayOption-1};
if (!isNaN(parseFloat(stopsCollect.value)))
{
sum += parseFloat(stopsCollect.value);
alert("Sum : " + sum);
}
}
else
{
for (var i = 0; i < stopsCollect.length; i++)
{
if (!isNaN(parseFloat(stopsCollect[i].value)))
{
sum += parseFloat(stopsCollect[i].value);
}
}
}
Create Underlines in Pdf
To add underlines to paragrahs in a pdf, can use idea below
import java.awt.Color;
import java.io.FileOutputStream;
import java.io.IOException;
import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;
public class AddUnderLines
{
public static void main(String[] args) throws Exception
{
System.out.println("Underline, Strike through,...");
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("underLinesPdf.pdf"));
document.open();
Chunk chunk = new Chunk("MyHeading");
chunk.setUnderline(0.2f, -2f);
Paragraph paragraph = new Paragraph("The following chunk is ");
paragraph.add(chunk);
document.add(paragraph);
Chunk chunk1 = new Chunk("myHeading");
chunk1.setUnderline(0.5f, 3f);
document.add(chunk1);
document.close();
}
}
import java.awt.Color;
import java.io.FileOutputStream;
import java.io.IOException;
import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;
public class AddUnderLines
{
public static void main(String[] args) throws Exception
{
System.out.println("Underline, Strike through,...");
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("underLinesPdf.pdf"));
document.open();
Chunk chunk = new Chunk("MyHeading");
chunk.setUnderline(0.2f, -2f);
Paragraph paragraph = new Paragraph("The following chunk is ");
paragraph.add(chunk);
document.add(paragraph);
Chunk chunk1 = new Chunk("myHeading");
chunk1.setUnderline(0.5f, 3f);
document.add(chunk1);
document.close();
}
}
Customize a button display
We can customize a button as below
<style type="text/css">
.button{background-color:#008800;text-decoration: none;color:#000000;font-size:10px;font-weight:bold;Border: 1px solid #333333;height:20px;margin-left:2px;}
</style>
<style type="text/css">
.button{background-color:#008800;text-decoration: none;color:#000000;font-size:10px;font-weight:bold;Border: 1px solid #333333;height:20px;margin-left:2px;}
</style>
Formatting date in java
To format a date in java
Calendar cal = Calendar.getInstance();
String myDate = new SimpleDateFormat("ddMMMyyyy").format(cal.getTime());
Similarly we can use a string to convert to Date
Date myOtherDate = new SimpleDateFormat("ddMMMyyyy").parse(dateString);
Calendar cal = Calendar.getInstance();
String myDate = new SimpleDateFormat("ddMMMyyyy").format(cal.getTime());
Similarly we can use a string to convert to Date
Date myOtherDate = new SimpleDateFormat("ddMMMyyyy").parse(dateString);
Scrollable Label
To make a ready only label using a textfield so that the label is scrollable, use the code below
<html:text style="border:0" name="fop" property="account" size="16" readonly="true" />
<html:text style="border:0" name="fop" property="account" size="16" readonly="true" />
Distinguish servlet requests
To find out if a servlet request button action is coming from a forward or not, use this code below
if( instForm.isBtnClose() )
{
// check if this "CLOSE==TRUE" comes from other pages;
if( null==request.getAttribute("javax.servlet.forward.servlet_path") )
{
return mapping.findForward("close");
}
}
if( instForm.isBtnClose() )
{
// check if this "CLOSE==TRUE" comes from other pages;
if( null==request.getAttribute("javax.servlet.forward.servlet_path") )
{
return mapping.findForward("close");
}
}
Thursday, June 12, 2008
Populate droplist dynamically through AJAX
Mechanism to make an ajax call from one drop list and populate another droplist
In JSP
Add a html select element as below
html:select name=somethingOne id=dropListOne onchange="retrieveDropTwoOptions()
html:select name=somethingTwo id=dropListTwo
function retrieveDropTwoOptions(){
dropListOne = document.getElementById('dropListOne');
if(dropListOne.selectedIndex==0){
document.getElementById('dropListTwo').options.length = 0;
document.getElementById('dropListTwo').options[i] = new Option("---", "", true);
return;
}
dropListOneCode = dropListOne.options[dropListOne.selectedIndex].value;
url='/MyServer/ajax.do?method=populateDropList' +
'&dropListOneCode=' + dropListOneCode ;
//Do the Ajax call
req = ajaxRequestSend(url, "GET", populateDropListTwoBox);
}
//Callback function
function populateDropListTwoBox(){
if (req.readyState == 4) { // Complete
if (req.status == 200) { // OK response
textToSplit = req.responseText;
myCode = document.getElementById('dropListTwo').value; // obtained from form
//Split the document
returnElements=textToSplit.split("\n")
//Process each of the elements
document.getElementById('dropListTwo').options.length = 0;
for ( var i=0; i valueLabelPair = returnElements[i].split(":")
if (myCode == valueLabelPair[0]) {
document.getElementById('dropListTwo').options[i] = new Option(valueLabelPair[1], valueLabelPair[0], true);
}
else {
document.getElementById('dropListTwo').options[i] = new Option(valueLabelPair[1], valueLabelPair[0]);
}
}
}
}
function ajaxRequestSend(url, method, callBackFunciton){
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
req.open(method, url, true);
req.onreadystatechange = callBackFunciton;
req.send(null);
return req;
}
In AjaxAction.java, we add a simple method to return a value
public class AjaxAction extends Action
{
//...
public void populateDropList()
{
StringBuffer body = new StringBuffer(":---\n");
//... get data from database
while (resultSet.next()) {
code = resultSet.getString("code") ;
desc = resultSet.getString("name") ;
body.append("\n").append(code).append(":").append(desc);
}
response.setContentType("text/plain");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write(body.toString());
response.getWriter().flush();
}
}
In JSP
Add a html select element as below
html:select name=somethingOne id=dropListOne onchange="retrieveDropTwoOptions()
html:select name=somethingTwo id=dropListTwo
function retrieveDropTwoOptions(){
dropListOne = document.getElementById('dropListOne');
if(dropListOne.selectedIndex==0){
document.getElementById('dropListTwo').options.length = 0;
document.getElementById('dropListTwo').options[i] = new Option("---", "", true);
return;
}
dropListOneCode = dropListOne.options[dropListOne.selectedIndex].value;
url='/MyServer/ajax.do?method=populateDropList' +
'&dropListOneCode=' + dropListOneCode ;
//Do the Ajax call
req = ajaxRequestSend(url, "GET", populateDropListTwoBox);
}
//Callback function
function populateDropListTwoBox(){
if (req.readyState == 4) { // Complete
if (req.status == 200) { // OK response
textToSplit = req.responseText;
myCode = document.getElementById('dropListTwo').value; // obtained from form
//Split the document
returnElements=textToSplit.split("\n")
//Process each of the elements
document.getElementById('dropListTwo').options.length = 0;
for ( var i=0; i
if (myCode == valueLabelPair[0]) {
document.getElementById('dropListTwo').options[i] = new Option(valueLabelPair[1], valueLabelPair[0], true);
}
else {
document.getElementById('dropListTwo').options[i] = new Option(valueLabelPair[1], valueLabelPair[0]);
}
}
}
}
function ajaxRequestSend(url, method, callBackFunciton){
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
req.open(method, url, true);
req.onreadystatechange = callBackFunciton;
req.send(null);
return req;
}
In AjaxAction.java, we add a simple method to return a value
public class AjaxAction extends Action
{
//...
public void populateDropList()
{
StringBuffer body = new StringBuffer(":---\n");
//... get data from database
while (resultSet.next()) {
code = resultSet.getString("code") ;
desc = resultSet.getString("name") ;
body.append("\n").append(code).append(":").append(desc);
}
response.setContentType("text/plain");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write(body.toString());
response.getWriter().flush();
}
}
Simple AJAX
Method to get make a simple ajax call and get a response
function openTermsAndConditions()
{
var selectedIndex = document.getElementById("planOptions").selectedIndex;
var selectedText = document.getElementById("planOptions").options[selectedIndex].text;
if(selectedText)
{
retrievePlanTermsURL(selectedText);
}
}
function retrievePlanTermsURL(planId)
{
url = '/MyServer/ajax.do?method=getPlanTermsAndConditionsURL' +
'&planId=' + planId;
//Do the Ajax call
req = ajaxRequestSend(url, "GET", openURL);
}
//Callback function
function openURL()
{
var termsURL = "";
if (req.readyState == 4) // Complete
{
if (req.status == 200) // OK response
{
termsURL = req.responseText;
document.getElementById("termcondURL").value = termsURL;
if(termsURL)
{
window.open(termsURL, "windowTermsAndConditions", "width=500,height=500");
}
}
}
}
function ajaxRequestSend(url, method, callBackFunciton){
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
req.open(method, url, true);
req.onreadystatechange = callBackFunciton;
req.send(null);
return req;
}
In AjaxAction.java, we add a simple method to return a value
public class AjaxAction extends Action
{
//...
private void getPlanTermsAndConditionsURL() throws Exception
{
String returnValue = DatabaseHelper.getSomeData();
response.setContentType("text/plain");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write(returnValue);
response.getWriter().flush();
}
}
In JSP, add an html select element with id =planOptions
function openTermsAndConditions()
{
var selectedIndex = document.getElementById("planOptions").selectedIndex;
var selectedText = document.getElementById("planOptions").options[selectedIndex].text;
if(selectedText)
{
retrievePlanTermsURL(selectedText);
}
}
function retrievePlanTermsURL(planId)
{
url = '/MyServer/ajax.do?method=getPlanTermsAndConditionsURL' +
'&planId=' + planId;
//Do the Ajax call
req = ajaxRequestSend(url, "GET", openURL);
}
//Callback function
function openURL()
{
var termsURL = "";
if (req.readyState == 4) // Complete
{
if (req.status == 200) // OK response
{
termsURL = req.responseText;
document.getElementById("termcondURL").value = termsURL;
if(termsURL)
{
window.open(termsURL, "windowTermsAndConditions", "width=500,height=500");
}
}
}
}
function ajaxRequestSend(url, method, callBackFunciton){
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
req.open(method, url, true);
req.onreadystatechange = callBackFunciton;
req.send(null);
return req;
}
In AjaxAction.java, we add a simple method to return a value
public class AjaxAction extends Action
{
//...
private void getPlanTermsAndConditionsURL() throws Exception
{
String returnValue = DatabaseHelper.getSomeData();
response.setContentType("text/plain");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write(returnValue);
response.getWriter().flush();
}
}
In JSP, add an html select element with id =planOptions
Nested Iterate tag
If you have a Collection in ActionForm and require to access them, we can use nested:iterate
<nested:iterate name="memberCustomerViewForm" property="addressList" >
<div>
<span class="leftBuffer"> </span>
<span class="generalInput">
<nested:text property="addressType" onblur="toUpper(this);" size="11" />
<nested:hidden property="addressId"/>
</span>
</nested:iterate>
Note
- do not use id=current in nested:iterate
- don't access like <nested:text name="current" property="addressType" />
<nested:iterate name="memberCustomerViewForm" property="addressList" >
<div>
<span class="leftBuffer"> </span>
<span class="generalInput">
<nested:text property="addressType" onblur="toUpper(this);" size="11" />
<nested:hidden property="addressId"/>
</span>
</nested:iterate>
Note
- do not use id=current in nested:iterate
- don't access like <nested:text name="current" property="addressType" />
Subscribe to:
Posts (Atom)