Thursday, December 4, 2008

Subselects in database queries

While inserting records into a table A, if a need arises to fill a column with value from a table B, then use the following sql

insert into "CLASSICCARS"."EMPLOYEE"
(
"EMPLOYEENUMBER",
"OFFICECODE"

)
values
(
1703,
(select max(officecode) from classiccars.OFFICE)
)

Thursday, November 20, 2008

Helpful Unix commands - Part 2

- When shell script complains of ^M character which is a windows character
sh: /opt/tmp/testPerson.sh: /usr/bin/ksh^M: bad interpreter: No such file or directory

Reason is there may be DOS linefeeds in your file. Convert the file to Unix linefeeds, either by copying the file using ASCII mode FTP, or one of:

tr -d '\r' < script > script.new

perl -pi -e 's/\r$//;' script

dos2unix < script > script.new



-To Change permissions
chmod 775 <>
chmod -R 775 <> [for recursive]


-To Move Files from One server to another
scp username@servername:/opt/tmp/filename filename


To connect to B server from A server
From A server type
ssh username@serverB


-To check if a directory exist

if [ -d mydir ]
then
echo "Directory found"
else
echo "Directory not found"
fi


-To check if a file exists

#(-f === if file exists)
if test -f $TMP;
then
if test ! -w $TMP ;
then
printf the temp file $TMP exists and cannot be overwritten aborting >&2
exit 192
fi
fi


- To copy a file
cp -p <> <>
- To copy a directory
cp -p -R <> <>

- To remove a file
rm <>
- To remove a directory
rm -d -R <,filename>>


- To find out if perl or bash or sh file exists
which perl
which bash
which sh


- To find out the version of linux
cat /etc/redhat-release

- To change group name of a file
chgrp <> <>

Thursday, October 9, 2008

Pancakes

Ingredients:
2 cups plain flour
1.5 or 2 cups milk
2 eggs
2 tablespoon sugar
3 teaspoon baking soda
60g melted and cooled butter or ghee
some more butter or ghee for cooking

Serves: about 8 pancakes

Procedure:
Mix the four and sugar together in a vessel
In a bowl, mix the milk, eggs, baking soda and melted butter or ghee
Make a well in the flour. Gradually add the milk mixture to the well in flour and keep mixing to form a smooth batter
Keep aside the batter for about 10 mins

In a pan, add some butter or ghee and spread it nicely
Keep the flame in low heat
Pour the batter to the pan in small circles.
When bubbles start to appear on top, toss the pancake and cook the other side
Pancakes ready!
Serve hot. Can also be served with golden syrup or coconul milk + sugar

Tuesday, September 2, 2008

What Kevin says...

6 yrs

kevin: can you put the lumpic channel on tv
translated as: can you put the Olympic channel on tv

kevin: don't change the channel, its just the abatisan
translated as: don't change the channel, its just the advertisement

kevin: they are singing the national anshum on tv
translated as: they are singing the national anthem on tv

kevin: i accidentally delicate the picture
translated as: i accidentally delete the picture

Wednesday, August 13, 2008

Querying a date column in database

To query a date column, use

select * from person_table where date_of_birth >= to_date('01/01/2000', 'dd/MM/yyyy')

Thursday, July 24, 2008

Querying date with java and sql

Two ways to query a date:
1. by formatting and querying as a string
2. by to_date sql function

public List getPersonList(Timestamp startDate, Timestamp endDate)
{
String startDateStr = new SimpleDateFormat("yyyy-MM-dd hh24:mm:ss").format(startDate);
String endDateStr = new SimpleDateFormat("yyyy-MM-dd hh24:mm:ss").format(startDate);

List toReturn = new ArrayList();
StringBuffer personQuery = new StringBuffer();
personQuery.append("select user from User as user ");

if(startDate != null && endDate != null)
{
registrationGrowthQuery.append(" where activationSentTime >= '" + startDateStr + "' and activationSentTime <= '" + endDateStr + "'");

registrationGrowthQuery.append(" where activationSentTime >= to_date("+startDate+", 'yyyy-MM-dd hh24:mm:ss') and activationSentTime <= to_date("+endDate+", 'yyyy-MM-dd hh24:mm:ss')");
}

Thursday, June 19, 2008

Google Map Example

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>

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/

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>

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);
}

}

}

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>

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

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

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);

Alert struts error messages

To alert struts error messages in JSP's

<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();
}

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

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.

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);
}
}

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

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();
}

}

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" />

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")

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>

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";

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())

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

Disable right click menu

To disable right click menu, can use the following script

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

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();

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);
}
}

}

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();
}
}

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>

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);

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" />

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");
}
}

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();

}

}

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

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" />

Tuesday, May 27, 2008

Dynamically Add or Remove HTML elements

<HTML>
<HEAD>
<script type="text/javascript">

var sequence = 0;

function addTextBox()
{
var dynDiv = document.getElementById('dynamicDiv');
var newDiv = document.createElement("DIV");
var newDivIdName = 'Div'+sequence;
newDiv.setAttribute('id',newDivIdName);
var newSpan = document.createElement('SPAN');

addField(newSpan,{ type :"text", name :"test"+sequence, value:"test"+sequence , size:30 });
addField(newSpan,{ type :"button", name :"delete"+sequence, value:"delete", id:"delete"+sequence });

newDiv.appendChild(newSpan);
dynDiv.appendChild(newDiv);

var deleteButton = document.getElementById('delete'+sequence);
deleteButton.onclick=function()
{
removeTextBox(newDivIdName);
}

sequence++;
}



function addField(form,json)
{
var inp=document.createElement("input");
for(var i in json)
{
inp[i]=json[i];
}
form.appendChild(inp);
}


function removeTextBox(divNum)
{
var dynDiv = document.getElementById('dynamicDiv');
var obj = document.getElementById(divNum);
dynDiv.removeChild(obj);
}

</script>

</HEAD>


<BODY>
<form name="testForm">
<div id="dynamicDiv">
<span>

<input type="text" name="address1" value="test"/>
<input type="button" name="Add" value="Add" onclick="addTextBox();" />
</span>
</div>

</form>
</BODY>

</HTML>

Thursday, May 1, 2008

What Kevin says...

4 yrs

twinkle twinkle little star

how I wonder what you are
appa daddy world so high
like a diamond in the sky

5.5 yrs

shopkeeper: how old are you?
kevin: half and a five

kevin: mum do you eat cows? At school my friend said she ate a cow!

Working with collections

If we have to iterate a Collection in struts and were required to pass back the object values from the collection as hidden fields to be set in the form, we would get an ArrayIndexOutofBounds exception. This is because we cannot set the collection as is. We need a special handling to add the objects to the collection from the jsp to form like the example given below.

Create a class called CustomList as follows

public class CustomList extends ArrayList {

private Class elementType;
private int maximumGrowSize;

public CustomList(Class elementType, int maximumGrowSize) {
this.elementType = elementType;
this.maximumGrowSize = maximumGrowSize;
}

public Object get(int index) {
while(index >= size()) {
if (index > maximumGrowSize) {
throw new RuntimeException("Cannot allow list to automatically grow beyond " + maximumGrowSize);
}
try {
add(elementType.newInstance());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return super.get(index);
}
}

In struts Action Form, we add

private List records = new CustomList(Person.class, 1000);
where Person.java is our model object which is populated in the collection

Sometimes we may have to display checkboxes next to each record to give the user option to delete selected records.
In such a case we handle the code as below:

<logic:iterate property="records">
<tr class="<%=rowClass%>" style="text-align:center">
<td>
<logic:checkbox property="delete" />
</td>
<td>
<logic:hidden property="personName"/>
<logic:write property="personName"/>
</td>
<td>
<logic:hidden property="personAge"/>
<logic:write property="personAge"/>
</td>
</tr>
</logic:iterate>


In the form, we can add a wrapper class to our Person object as shown below

public class PersonForm extends ActionForm
{

private List records = new CustomList(PersonWrapper.class, 1000);

public List getRecords()
{
return records;
}

public void setRecords(List records)
{
this.records = records;
}


public static class PersonWrapper extends Person
{

private boolean delete;

public boolean isDelete()
{
return delete;
}

public void setDelete(boolean delete)
{
this.delete = delete;
}
}

//....

}

Then in our struts Action class, we can get

public class PersonAction extends Action
{

List myRecords = actionForm.getRecords(); //This would have the the delete checkbox value as well in each row of the collection

for (PersonForm.PersonWrapper record : myRecords)
{
if (record.isDelete())
{
// do delete from database....

}
}

//...


//How to populate this result collection for display is as shown below

List<Person> results = databaseHelper.getAllPersonRecords();

if (results.size() > 0)
{
for (int i = 0, n = results.size(); i < n; i++)
{
PersonForm.PersonWrapper rec = new PersonForm.PersonWrapper();
try
{
PropertyUtils.copyProperties(rec, results.get(i));
}
catch (Exception e)
{
logger.error("Error copying Person beans!", e);
}
results.set(i, rec);
}
}

Wednesday, April 2, 2008

Cures from food

Almonds
Rich in protein, zinc, calcium, magnesium, potassium, phosphorus, vitamin E and antioxidants.
Food for the brain,heart, nervous system, digestion and blood pressure.

Asian greens
A great source of folate, antioxidant-rich, no fat, high in fibre, calcium, beta-carotene, potassium and vitamin C.

Apricots
Fresh or dried, a high source of dietary fibre and low GI. Relieve constipation and balance the nervous system. Contain vitamins A, B and C, iron, potassium and magnesium.

Avocados
Rich in omega 3 and essential amino acids. Also contains vitamins B6, C, K and folate. Use as a spread instead of butter.

Bananas
A convenient snack and rich in iodine, iron, zinc, potassium and folate, as well as vitamins A, B and E. Good for
treating diarrhoea.

Blueberries
One of the best antioxidant food sources you can eat; very rich in vitamin C, with half a punnet supplying the recommended daily requirement. A good source of fibre, vitamins B6 and E, potassium and bioflavonoids that assist in absorption of other fruits. Great for eyesight, healthy kidneys, strong blood capillaries and diarrhoea. Eat half a cup
every day.

Brazil nuts
An excellent source of selenium for assisting with fertility. They also contain protein, fibre, essential fatty acids, calcium, zinc and B vitamins.

Carrots
Rich in beta-carotene for good eyesight, they also treat heartburn, constipation and flatulence and are good for circulation, immunity, skin, hair and nails. One of the few vegetables that is more nutritious when cooked. Raw carrots inhibit activity of listeria by reducing the risk of food poisoning.

Cheese (hard block varieties, especially parmesan and tasty)
Excellent source of protein, calcium, magnesium, zinc and vitamins D and A. High in saturated fat, so eat in moderation.

Chickpeas and lentils
Highly nutritious, great for digestion, hypertension and diabetes. Low in fat, high in protein and fibre, a low-GI carbohydrate that contains iron, calcium, magnesium, zinc, B vitamins and essential fatty acids.

Dairy products˜low fat
(milk and yoghurt best sources)
Most absorbable source of calcium and contain all essential amino acids. Good source of protein. Milk is almost a complete food. Yoghurt aids digestion. Both are rich in magnesium, phosphorus, potassium and vitamins A, B and D. Hard cheeses are recommended during pregnancy.

Dark green vegetables
(broccoli, spinach, rocket)
An excellent source of folate, calcium and vitamin C. Low in fat, rich in fibre and a useful source of beta-carotene,
iron, magnesium and potassium. Use minimal water when cooking to retain nutritional value.

Dried fruit
Contain vitamins A, B3 and C, calcium, iron, phosphorus and potassium. Great high-fibre snack, especially prunes, dried apricots and pears.

Eggs
Nature’s own vitamin capsule and close to being a complete food. Higher in protein than chicken.
A great source of iodine, omega 3, zinc and vitamin D, as well as folate, iron, calcium, selenium, phosphorus, potassium and vitamin A.

Fennel
Well-known for its healing powers. Aids nausea, vomiting, bloating, stomach cramps and digestion and prevents flatulence. Seeds are the riches source of the plant.

Flaxseed oil
Rich in omega 3 and other essential fatty acids. Contains protein, fibre, calcium, vitamins B1, B3 and B6, magnesium, selenium and potassium. Aids constipation. Do not cook as it can turn rancid. Use in salad dressings, over steamed vegetables or sprinkle on yoghurt or cereal. Store in the refrigerator.

Garlic
Antibacterial and healing properties. Strengthens immune system, good for blood circulation, colds and flu
and general good health.

Ginger
Remedy for nausea and digestion troubles. Boosts circulation, metabolism and energy. Contains calcium, vitamin B5, magnesium, zinc and potassium.

Herbs (fresh)
Packed with protein, fibre, antioxidants, folate, iron, beta-carotene, calcium, vitamins A, B2, C and K, magnesium, phosphorus and potassium. The healthiest way to flavour foods, especially parsley, basil, mint and rosemary.

Lean meat
(beef, lamb and chicken)
Most absorbable source of iron, containing all essential amino acids. A great source of protein, zinc and vitamin B12.

Oats
The wonder grain. Highly nutritious, a great alternative to wheat and a wise breakfast option. A low-GI complex carbohydrate, and high in fibre, protein and essential fatty acids.

Also a good source of calcium, magnesium, potassium and folate. Vital to a healthy nervous system and useful for treating diabetes and mild depression.

Pears
A fabulous food for pregnancy. Calms the digestive system, cleanses, heals and is a good aid for constipation. They are also low GI.

Seafood
(salmon, mussels, canned sardines and tuna)
Important food source during pregnancy. Has the lowest level of saturated fat of all animal proteins.

Good source of zinc, iodine, omega 3 and vitamin B12. Also contains iron, calcium, vitamin B, potassium and phosphorus.

Sesame seeds

Very rich source of calcium, protein, vitamin E and fibre.
Good for the liver, kidneys, circulation and fatigue.

Sunflower seeds
Rich in omega 3 and dietary fibre, with traces of folate, iron, zinc, calcium, magnesium and selenium.

Tofu
The only non-animal source of complete protein. Low in saturated fat and free of cholesterol. Great source of iron, calcium, magnesium, phosphorus, potassium, B-group vitamins and dietary fibre. Tofu and tofu products should be eaten in moderation (2–3 servings a week are advised).

Wheatgerm
A fantastic source of zinc. It also contains protein, fibre, folate, vitamin B6, potassium and magnesium, as well as iron, calcium and essential fatty acids. For optimal health, have a tablespoon in smoothies or on your breakfast cereal every day.

Wholegrains
One of the best sources of B-group vitamins and folate. A low-GI carbohydrate, useful source of protein and dietary fibre. Also contain calcium, magnesium, zinc, selenium and potassium.

The following herbs are not superfoods for pregnancy. They are herbs that may help relieve certain health problems.

Mint
Good for: digestion, nausea, vomiting, circulation, heart palpitations. Can relieve stomach cramps and induce sleep.

Used in:
Stir-fries, Indian dishes, salads, salsas, marinades, tea infusions; goes with lamb, tomatoes, chickpeas and yoghurt.

Nutmeg:
Good for: nausea.

Used in: fresh nutmeg grated over cooked spinach, backed pumpkin, rice puddings or desserts made with ginger and honey.

Oregano:
Good for: Ear, nose, throat and lung infections, stimulates digestion.

Used in: Italian dishes, complements fish, lamb, chicken and tomatoes; use fresh or dried.

Parsley:
Good for: Anaemia, digestion, fluid retention, constipation, poor appetite, cleansing lungs, liver function, boosting immune system, useful source of iron and vitamin A

Used in: Tabbouli, salads, soups, casseroles, juices, goes well with fish, beans, eggs, garlic, lemons, lentils, pasta; best eaten fresh.

Rosemary:
Good for: Heart, bloody clotting, digestion, relieving indigestion and wind, rich source of antioxidants.

Used in: Great with lamb, chicken, pork, bread and potatoes; use fresh rosemary when chargrilling meats to counteract cancer-causing substances.

What Kevin says...

1.5 yrs
What did you eat for lunch?
Foar, mootae, chicka
translated as rice, egg and chicken

4 yrs
Press the ten dinosaurs
translated as "Lets pretend dinosaurs"

5 yrs
counting - nine, ten, eleven, eleventeen one, eleventeen two, eleventeen three....

to read - I am a snake. (fullstop)
read as - I am a snake fullpot

Friday, March 28, 2008

What vegetables contain...

Vitamin C - A key nutrient that the body needs to fight infection, heal wounds, and keep tissues healthy
- Corn (some)
- Cabbage (good)
- Pumpkins (good)
- Sweet Potato (good)
- Red Capsicum (very high)
- Beans (rich)
- Cauliflower (excellent)
- Spinach (excellent)
- Broccoli (several day's supply)
- Peas (excellent)
- Potato (excellent)

Dietary fibre - Essential for maintaining a healthy digestive system
- Pumpkins (some)
- Potato (some)
- Sweet Potato (some)
- Carrots (some)
- Cabbage (good)
- Cauliflower (good)
- Broccoli (good)
- Eggplant (good)
- Beans (good)
- Peas (best)
- Spinach (high)
- Corn (excellent)

Folate - a vitamin in the B-vitamin family that helps cells to mature and is needed before and after pregnancy to prevent birth defects.
- Cauliflower (some)
- Broccoli (good)
- Beans (good)
- younger carrots (more)
- Spinach (excellent)
- Corn (excellent)

Carbohydrate - a major source of energy in the diet.
- Peas (some)
- Corn (good)
- Potato (good)

Niacin - A form of vitamin B that raises the amount of HDL ("good") cholesterol in the blood
- Pumpkins (some)
- Peas (some)
- Corn (some)

Beta carotene - helps maintain smooth, soft disease-free skin
- Broccoli (good)
- Corn (some)
- Sweet Potato (rich)
- Red Capsicum (rich)
- Cabbage (excelent)
- Pumpkins (excellent)
- Spinach (excellent)
- Beans (excellent)
- Carrots (excellent)

Potassium - require this when we lose lots of body fluid
- Potato (some)
- Broccoli (good)
- edible-podded peas (good)
- Corn (excellent)


Iron - the oxygen-carrying component of the blood
- Peas (some)
- Broccoli (good)

What fruits contain...

Vitamin C - a key nutrient that the body needs to fight infection, heal wounds, and keep tissues healthy
- Grapes (some)
- Plums (moderate)
- Apple (good)
- Strawberries (good)
- Cherrires (good)
- Watermelon (good)
- Banana (lots)
- Rockmelon (lots)
- Mandarins (high)
- Lemons (excellent)
- Pineapple (excellent)
- Mango (excellent)
- Orange (excellent)

Dietary fibre - Essential for maintaining a healthy digestive system
- Grapes (some)
- Mango (some)
- Plums (moderate)
- Apple (good)
- Banana (good)
- Pineapple (good)
- Lemons (good)
- Mandarins (good)
- Cherrires (good)
- Orange (good)
- Pear (good)
- Watermelon (good)

Antioxidants - a vitamin or nutrient that may help prevent damage to the heart, arteries, and other tissues
- Apple

Folate - a vitamin in the B-vitamin family that helps cells to mature and is needed before and after pregnancy to prevent birth defects.
- Strawberrirs (some)

Carbohydrate - a major source of energy in the diet.
- Banana

vitamin B6 - a key nutrient that the body needs to break down proteins, carbohydrates, and fats in food for healthy blood, skin and nerves
- Banana (good)

beta carotene - helps maintain smooth, soft disease-free skin and gets converted to Vitamin A
- Orange (good)
- Watermelon (lots)
- Rockmelon (excellent)
- Mango (excellent)

Potassium - require this when we lose lots of body fluid
- Pear (low)
- Grapes (adequate)
- Banana (rich)

Tuesday, March 25, 2008

Select or Deselect a list of checkboxes

We may have a situation where we have a number of checkboxes generated dynamically and we need to either select them ALL or deselect them all at the same time
We can handle this in javascript as shown below

function setAllChecked(che)
{
cur = document.getElementsByName("checkBoxSelectAll");
if (che.checked)
{
for (i = 0; i < cur.length; i++)
{
cur[i].checked = true;
}
}

else
{
for (i = 0; i < cur.length; i++)
{
cur[i].checked = false;
}
}
}

<table cellpadding="2" cellspacing="2">
<th>
<input type=checkbox name="allSelect" onclick="setAllChecked(this)">
Select All
</th>

<nested:iterate property="records">
<tr>
<td>
<nested:checkbox property="select" styleId="checkBoxSelectAll" />
</td>
<td class="personName">
<nested:hidden property="personName"/>
<nested:write property="personName"/>
</td>
</tr>
</nested:iterate>
</table>

Wednesday, March 19, 2008

Scrollable table

We can add scrollbars to an html table by simply adding the below line of code to the table

<div style="border:1px solid; width:300px; height:400px; overflow:auto;">

Example

<div style="border:1px solid; width:300px; height:400px; overflow:auto;">
‎<table>
<tr>
<td>Data 1</td>
</tr>
<tr>
<td>Data 2</td>
</tr>
<tr>
<td>Data 3</td>
</tr>
</table>
</div>

The "height" attribute is very important in order for scrollbars to appear

Friday, February 15, 2008

JAXB Overview

JAXB is used to easily construct an xml message from Java objects and
the reverse i.e to construct Java objects from XMl message.
JAXB now comes standard with the Java Web Services Development Pack
(http://java.sun.com/webservices/downloads/webservicespack.html).


In this tip we can see how to use JAXB to generate a set of Java classes
from an XML Schema document using the JAXB binding compiler.
We can also see how to serialize an object to an XML file (marshalling)
and how to do the opposite: serialize an object from an XML
file (unmarshalling)

We require the following files
jaxb-api.jar
jaxb-impl.jar
jaxb-libs.jar
jaxb-xjc.jar
relaxngDatatype.jar
xsdlib.jar


Compile XML schema to Java classes

Here is a simple schema, Person.xsd, that can be used to generate a JAXB
class.

<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string" />
<xs:element name="age" type="xs:int" />
<xs:element name="address" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>

</xs:schema>

The schema defines a simple element named person. The person element has a complexType
that defines three properties: name (a String), age
(an integer), and address, (another String).

To bind this to a Java interface, invoke the XML binding
compiler. To do this you run the xjc command.
Use the following command-line syntax:

xjc -p <target_package> -d <dir> schema.xsd

where <target_package> is the name of the package for the
generated files, <dir> is the directory in which the
generated files will be placed, and schema.xsd is the input XML
schema. So, for example, run the following command in the
directory that contains Birthdate.xsd:

xjc -p com.mytest.example -d . Person.xsd

In response, the binding compiler generates a set of Java source
classes, all of which need to be compiled with javac.

Here, for example, is the PersonType interface:

package com.mytest.example;

public interface PersonType {

int getAge();
void setAge(int value);

java.lang.String getName();
void setName(ava.lang.String value);

java.lang.String getAddress();
void setAddress(java.lang.String value);

}

Along with this, the schema compiler also generates some vendor-specific implementations of those
interfaces and other supporting runtime classes.

After the binding compiler generates the necessary classes,
the next step is to compile the generated classes with javac.
Then you can start working with JAXB serialization.


Alternatively we can also compile the schema through an ant script as below:

<target name="compile_jaxb" depends="delete_jaxb_tmp, set_jaxb_path">
<echo message="Doing a clean compile"/>
<taskdef name="xjc" classname="com.sun.tools.xjc.XJCTask">
<classpath>
<fileset dir="${src}/WEB-INF/lib">
<include name="**/xalan.jar" />
</fileset>
<fileset dir="${src}/../lib/buildtime/jaxb1.0" >
<include name="**/*.jar" />
</fileset>
</classpath>
</taskdef>

<mkdir dir="${jaxb.tmp.src}"/>
<xjc schema="${schema.file}" binding="${bindings.file}" package="${package}" target="${jaxb.tmp.src}"/>

<mkdir dir="${jaxb.tmp.classes}"/>

<javac srcdir="${jaxb.tmp.src}"
destdir="${jaxb.tmp.classes}"
debug="on"
fork="true"
memoryInitialSize="128m"
memoryMaximumSize="192m">
<classpath>
<fileset dir="${src}/../lib/buildtime/jaxb1.0" >
<include name="**/*.jar" />
</fileset>
</classpath>
</javac>

<copy todir="${jaxb.tmp.classes}">
<fileset dir="${jaxb.tmp.src}" includes="**/*.properties, **/*.ser"/>
</copy>

<jar jarfile="${jaxb.tmp}/${jaxbJar.file}"
basedir="${jaxb.tmp.classes}"/>
</target>



<target name="delete_jaxb_tmp">
<echo message="Deleting the temp directory"/>
<delete dir="${jaxb.tmp}"/>
</target>

<target name="set_jaxb_path">
<property name="schema.root" value="${xmlSchemas.src}"/>
<property name="jaxbJar.file" value="jaxbPerson.jar"/>
<property name="schema.file" value="${schema.root}/Person.xsd"/>
<property name="bindings.file" value="${schema.root}/SubstitutionsV2.xjb"/>
<property name="package" value="com.onerail.orion.reservation.xml.messages.coreorion"/>
</target>


<target name="copy_jaxb_jar">
<echo message="Copying ${jaxbJar.file} into ${src}/WEB-INF/lib"/>
<copy file="${jaxb.tmp}/${jaxbJar.file}" todir="${src}/WEB-INF/lib"/>
</target>



Marshalling

public class TestPerson
{
ObjectFactory factory = new ObjectFactory();
Person personObj = factory.createPerson();
personObj.setName("Jane");
personObj.setAge("10");
personObj.setAddress("Martin Place, Sydney");

JAXBContext jaxbContext = JAXBContext.newInstance(
"com.mytest.example");
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
new Boolean(true));
marshaller.marshal(personObj, new FileOutputStream(
"personInstance.xml"));

}

Optionally, you can validate an object you are serializing
against a JAXB-generated content tree. To do that, use the
Validator object as follows:

Validator validator = jaxbContext.createValidator();
Validator.validate(person);

Here for example, is what a sample listing of an XML serialization of
a Person object looks like:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<person>
<name>Jane</name>
<age>10</age>
<address>Martin Place, Sydney</address>
</person>



Unmarshalling

Here is a code example that unmarshals data from an XML file to
a JAXB-generated instance:

import javax.xml.bind.*;

JAXBContext jc = JAXBContext.newInstance(
"com.mytest.example");
Unmarshaller unmarshaller = jc.createUnmarshaller();
unmarshaller.setValidating(true);
Peson instance = (Peson)unmarshaller.unmarshal(
new File("personInstance.xml"));

System.out.println("Name is: " + instance.getName());
System.out.println("Age is: " + instance.getAge());
System.out.println("Address is: " + instance.getAddress());

If setValidating() is set to true, the JAXB runtime API
validates the XML that contains the instance data against the
constraints specified by the XML schema that was submitted to
the binding compiler. If the data is invalid, the validation
fails and generates a runtime exception.

Utility method to convert a String XML to Object XML

public static final String JAXBCONTEXT_PACKAGE = "com.test.xml.messages.core"; // package where all generated JAXB classes exist

public static Object convStringToXmlObj(String toConvert) throws JAXBException, IOException
{
ByteArrayInputStream bais = new ByteArrayInputStream(toConvert.getBytes());

Unmarshaller unmarshaller = JAXBContext.newInstance(JAXBCONTEXT_PACKAGE).createUnmarshaller();
unmarshaller.setValidating(true);
Object toReturn = unmarshaller.unmarshal(bais);
bais.close();
return toReturn;
}

Utility method to convert a Object XML to String XML

public static String convXmlObjToString(Object toConvert) throws JAXBException, IOException
{

ByteArrayOutputStream baos = new ByteArrayOutputStream();

Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(toConvert, baos);

baos.close();

return baos.toString("UTF-8");
}

Utility method to convert a File to Object XML

public static Object convFileToXmlObj(String fileLocation) throws JAXBException, IOException
{
File file = new File(fileLocation);
byte[] b = new byte[(int) file.length()];
FileInputStream in = null;
try
{
in = new FileInputStream(file);
in.read(b, 0, b.length);
}
catch(java.io.FileNotFoundException e1)
{
logger.error("File not found");
}
catch(java.io.IOException e2)
{
logger.error("I/O Exception");
}
finally
{
if(in != null)
{
try
{
in.close();
}
catch(java.io.IOException e)
{
logger.error("I/O Exception");
}
}
}
return convStringToXmlObj(new String(b));
}



Wednesday, February 13, 2008

Show confirmation dialog box to the user using javascript

Many a times we need to ask a yes or no dialog box to the user. We can achieve this for instance using javascript.

Below is a simple script which is called in the onClick event of a button.

If user presses OK, the page will be submitted and continue process. If user presses NO, no action will take place and user remains on the same page.

<script type="text/javascript">
function confirmLeavePage()
{
return confirm("Any changes you have made may be lost. Please click the Cancel button to return to the page to save your changes or select OK to proceed without saving your changes");

}
</script>

<button onclick="if(!confirmLeavePage())return false;" name="aButton" type="submit">Next Page</button>

Thursday, January 17, 2008

To check whether a date is in the past using Javascript

With a valid date string format say mm/dd/yy, we can check whether a date is in the past or not using the javascript Date object.

<html:text property="trinDateStr" onblur="if(!checkDateNotInPast(this)){return false;}">

<script type="text/javascript">
function checkDateNotInPast(obj)
{
var vDate = Date.parse(obj);
var today = new Date().getTime();
if(vDate < today)
{
alert("Invalid: Date is in past");
obj.focus();
obj.select();
return false;
}
else
{
return true;
}
}
<script>