Thursday, March 29, 2007


XML Parsing using SAX Parser

Write a java class that extends DefaultHandler with following methods:

import org.xml.sax.*;
import org.xml.sax.helpers.*;

public class MyParser extends DefaultHandler {
public void startDocument( ) throws SAXException
public void endDocument( ) throws SAXException
public void startElement( String namespaceURI,
String localName,
String qName,
Attributes attr ) throws SAXException {
System.out.println( “Start element : “+localName);
for ( int i = 0; i <>
System.out.println( " ATTRIBUTE: " +
attr.getLocalName(i) +
" VALUE: " +
attr.getValue(i) );

public void endElement( String namespaceURI,
String localName,
String qName ) throws SAXException {

System.out.println( “End element : “+localName);
public void characters( char[] ch, int start, int length )
throws SAXException {

String val=null;
val = new String(ch, start, length);
System.out.println(“Characters :“+val);


Use above in your program as follows :
try {
// Create SAX 2 parser...
XMLReader xr = XMLReaderFactory.createXMLReader();
// Set the ContentHandler...
xr.setContentHandler( new QueryParser() );
// Parse the file...
InputSource is = new InputSource(new StringReader(Test.getXMLQueryString()));
xr.parse( is );

}catch ( Exception e ) {

Xslt for webRowSet to html

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="" xmlns:wrs="" version="1.0">
<xsl:template match="/">
<h2>Query Results</h2>
<h3> Total Count : <xsl:value-of select="count(wrs:webRowSet/wrs:data/wrs:currentRow)"/> </h3>
<table border="1">
<tr bgcolor="lightgray">
<xsl:for-each select="wrs:webRowSet/wrs:metadata/wrs:column-definition">
<th><xsl:value-of select="wrs:column-label"/></th>

<!-- fill in the table rows -->

<xsl:for-each select="wrs:webRowSet/wrs:data/wrs:currentRow">
<xsl:for-each select="wrs:columnValue">
<td><xsl:value-of select="."/></td>

Other important xslt:

If you have a xml like :
To print each value in a comma separated list :
<xsl:template match="/list">
<xsl:value-of select="val[1]"/>,
<xsl:value-of select="val[2]"/>,
<xsl:value-of select="val[3]"/>,

Oracle, SQL

To Display last record in a table

select * from (select rownum r, emp.* from emp) where r in (Select count(*) from emp)

Select a range :

select * from (select rownum rn, department_id,department_name from departments) where rn >= 11 and rn <= 20;

Tree Query :

To display A Employee supervisor tree, all possible combinations :

Select * from emp
Connected by prior emp_id = superviosor_id;

To display all employees of a particular supervisor (for e.g 101) :

Select * from emp
Connected by prior emp_id = superviosor_id;
Start with emp_id = 101;

Example of traversing through a tree table

SQL> select sample_number,parent_sample,text_id from sample
2 connect by prior sample_number=parent_sample
3 start with sample_number = 118;

Creating new tables/schema

1. Log into the console via http://targetted-database-host:1158/em. Authenticate as one of the DBA accounts.
2. Select the Administration tab.
3. Select the Storage Tablespaces link.
4. Ensure the Actions drop-down list is set to Add Datafile.
5. Press the Create button.
6. Specify a name for the tablespace. Will appear in uppercase in most locations.
7. Under Extent Management select locally managed.
8. Under Type select permanent with set as default... unchecked.
9. Under Status select read write.
10. Under Datafiles check the use big file tablespaces option.
11. Press the Add button down in the Datafiles section.
* Supply a File Name of the form basename01.dbf. As the database grows more files are likely to be added, thus the use of a sequence number.
* The File Directory should be defaulted already: e.g. /oracle/u02/oradata/sand/, or c:\oracle\oradata\10.2.0\lt50735\lt50735\
* Specify a File Size of 500 megabytes. Do not re-use an existing file.
* Under the Storage section select the Automatically extend... option. Set the increment option to 500 megabytes. Make sure maximum file size is set to Unlimited.
* Press the continue button to accept the file addition. The view returns to the tablespace entry screen.
12. Press the Ok button (upper-right) to create the new tablespace and file, placing it on-line for use.

Create user

$ sqlplus / as sysdba
create user myuser identified by password;
grant create session,create any table to myuser;
alter user myuser default tablespace ;
alter user myuser quota unlimited on ;

login sqlplus with myuser

create tables…, insert data.. ready to go

Implementing auto increment

Example Java Code :

String query = "BEGIN insert into Test(desc,timestamp) values (? , ?) returning id into ?; END;";

OracleCallableStatement cs = (OracleCallableStatement) conn.prepareCall(query);
cs.setDouble(1, "test");
cs.setTimestamp(2, time);
cs.registerOutParameter(3, OracleTypes.NUMBER );

Create sequence and trigger before using the above code as follows :

SQL> create sequence test_id_seq
2 start with 1
3 increment by 1
4 nomaxvalue;
Sequence created.

SQL> create trigger test_id_trigger
2 before insert on test
3 for each row
4 begin
5 select test_id_seq.nextval into from dual;
6 end;
7 /

Query to find gaps in sequence number in a table :

SELECT (before_gap+1) ||'-' || (after_gap-1)
FROM (SELECT seq_number after_gap, LAG(seq_number,1,0) OVER (ORDER BY seq_number) before_gap from seq_num_table)
WHERE before_gap != 0 AND after_gap - before_gap > 1
ORDER BY before_gap;

Monday, March 5, 2007

TechiScoop Part I(Multithreading)

Multi Threading

What is thread?
It's a light process, has its own copy of stack, but shares global variables with the processs. One process can have one or many threads. What this means is, a thread will have copy of their own local variables but it will share the global and variables declared with static keyword.

In multi-processor cpu, one can run multiple threads on more than one cpu simulteneously. So, improved performance for the application. Switching between thread is easier and faster than switching between processes. On a single processors, thread scheduling is done in such a way that, user gets feeling running things in parallel, actually, only one thread is running during a particular time slot.

Unprotected access of shared data may lead to program crahses, deadlocks.

How to write thread safe programs?
Use locks to access shared variables. Java programmers can write synchronized methods or make use of synchronized blocks in their program to avoid race conditions.


import java.util.HashMap;
import java.util.Map;

class MyCache {

protected static Map aCache=new HashMap();

public void Cache()
//do nothing

public synchronized Object getValue(String key)
return aCache.get(key);

public synchronized void setValue(String key, Object val)
aCache.put(key, val);

class SimpleThread extends Thread {
public SimpleThread(String str) {
public void run() {
String randstr[]={"Hello","motion","world","texas","india","cloud","tree","birds","ten","medal"};
for (int i = 0; i < 10; i++) {
System.out.println(i + " " + getName());
try {
MyCache c=new MyCache();
String key="key#"+i;
c.setValue(key, randstr[i]);
sleep((int)(Math.random() * 1000));
catch (InterruptedException e) {}
System.out.println("DONE! " + getName());

public class ThreadExample {

public static void main(String[] args) {
SimpleThread s[]=new SimpleThread[5];
for(int i=0;i<5;i++) {
String threadid="Thread"+i;
s[i]=new SimpleThread(threadid);

Sample output:

0 Thread0
0 Thread1
0 Thread2
0 Thread3
0 Thread4
1 Thread4
1 Thread2
2 Thread2
1 Thread3
1 Thread0
1 Thread1
2 Thread4
DONE! Thread0
DONE! Thread3
9 Thread1
DONE! Thread1

In the above example, the MyCache class has a static variable aCache. And its initialized along with its declaration(this make sures, only once its initialized). Now, the, two methodes get and set are synchronized, if they are not, then the output will generate NullPointerException. because, your program tries to access the shared cache simulteneously. Making the method synchronized resolved the problem of race-condition like this.