Tuesday, March 17, 2009

CSV Files to XML

Comma Separated Value files (CSV) are one of the most common file exchange formats seen. It is a "flat" format, where typically each row has the same format. Each field, or data item, is separated from the others by a comma, and fields containing commas are quoted. DataDirect XML Converters are high-performance Java and .NET data conversion components that support converting of CSV to XML and XML to CSV.
CSV Import and Export

CSV Import/Export is a feature of almost every program that deals with tabular data, from accounting programs like Intuit's Quicken to office programs such as Microsoft Excel. It is a very old format, dating to the earliest days of computing. Even Radio Shack's TRS-80 model I used CSV data in DATA statements.

But in spite of the ubiquity of the CSV data format, there is a surprising number of variations in implementations. For this reason, the DataDirect XML Converters implementation offers several switches which can customize the behavior for your specific application.
Convert CSV to XML

The following options are supported in the DataDirect XML Converter CSV converter precisely because they are unspecified in the real world, and vary between applications.

* Whether the first row of the CSV data contains the names of the fields, or they are known by the sending and receiving applications implicitly
* How commas within values are handled in CSV files
* How quotes within quoted values are handled in CSV files. Are they doubled to escape them, or is there a special escape character, such as a backslash?
* Whether single or double quotes are used
* Whether runs of consecutive but empty fields should be ignored
* What encoding is used — Windows1252, ISO-8859-1 or US-ASCII are the most common
* What line ending is used — CR/LF from Windows, LF from Unix/Linux, or CR from the Macintosh are often seen

TSV Files

A close cousin to CSV files are TSV, or Tab Separated Value files. These are a common export format from spreadsheets also. There is a separate DataDirect XML Converter for these, but it actually is just the CSV Converter in disguise, since either can be converted to the other by changing the definition of the separator character from comma to tab.
CSV Sample File

Use the following sample CSV file for use in trying out DataDirect XML Converters:


Using the above file, a tiny Java, C# or VB.Net program can quickly transform the input CSV to XML, or convert XML to CSV. For example, the following Java program converts the above CSV sample file into XML and writes the output to the console.
import java.io.*;
import javax.xml.transform.stream.*;
import com.ddtek.xmlconverter.*;
public class CSVDemo {
public static void main(String[] args) throws Throwable {
ConverterFactory factory = new ConverterFactory();
ConvertToXML toXML = factory.newConvertToXML("converter:CSV:first=yes");
OutputStreamWriter w = new OutputStreamWriter(System.out, "US-ASCII");
toXML.convert(new StreamSource(args[0]), new StreamResult(w));
}
}

This would create the following output (with some parts removed).


XML to CSV

Going from XML to CSV is just as important, and the code is just as small. It takes no special schema, and it doesn't even take XQuery or XSLT. Anything immediately under the root element becomes the rows, and anything under that becomes the values between the commas. In the above example, switching to the ConvertFromXML class and writing the sample XML in would produce the initial CSV file.

Just like the EDI converters and other converters in the DataDirect XML Converters suite, CSV (and TSV) converters are fully bidirectional.
How To Use CSV Files

CSV files often are used as a bridge between older applications and newer ones. Having a tool that transparently reads and writes CSV format files in your toolbox can be very valuable. So whether you have to merge inventory data coming from an outside vendor into your database or publish a list of financial figures for your accountants, being able to bridge these two worlds is the purpose of the DataDirect XML Converters. You can get started with directly accessing CSV data from your Java or .NET applications by downloading a free trial of DataDirect XML Converters today.

Monday, March 16, 2009

A simple way to read an XML file in Java

This is the simplest way to read data from an XML file into a Java program. I have also included some basic error checking, so you can directly cut-paste this code with a few changes ofcourse. All you have to do is change the XML tags within the program to match those that are present in your XML file.

XML File



Program Output

Root element of the doc is book
Total no of people : 3
First Name : Kiran
Last Name : Pai
Age : 22
First Name : Bill
Last Name : Gates
Age : 46
First Name : Steve
Last Name : Jobs
Age : 40

Program Listing

The Java program to read the above XML file is shown below. Go through the program twice and you will understand all its parts. It may look intimidating at first sight, but believe me its very simple.

import java.io.File;
import org.w3c.dom.Document;
import org.w3c.dom.*;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class ReadAndPrintXMLFile{

public static void main (String argv []){
try {

DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse (new File("book.xml"));

// normalize text representation
doc.getDocumentElement ().normalize ();
System.out.println ("Root element of the doc is " +
doc.getDocumentElement().getNodeName());


NodeList listOfPersons = doc.getElementsByTagName("person");
int totalPersons = listOfPersons.getLength();
System.out.println("Total no of people : " + totalPersons);

for(int s=0; s

Node firstPersonNode = listOfPersons.item(s);
if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){


Element firstPersonElement = (Element)firstPersonNode;

//-------
NodeList firstNameList = firstPersonElement.getElementsByTagName("first");
Element firstNameElement = (Element)firstNameList.item(0);

NodeList textFNList = firstNameElement.getChildNodes();
System.out.println("First Name : " +
((Node)textFNList.item(0)).getNodeValue().trim());

//-------
NodeList lastNameList = firstPersonElement.getElementsByTagName("last");
Element lastNameElement = (Element)lastNameList.item(0);

NodeList textLNList = lastNameElement.getChildNodes();
System.out.println("Last Name : " +
((Node)textLNList.item(0)).getNodeValue().trim());

//----
NodeList ageList = firstPersonElement.getElementsByTagName("age");
Element ageElement = (Element)ageList.item(0);

NodeList textAgeList = ageElement.getChildNodes();
System.out.println("Age : " +
((Node)textAgeList.item(0)).getNodeValue().trim());

//------


}//end of if clause


}//end of for loop with s var


}catch (SAXParseException err) {
System.out.println ("** Parsing error" + ", line "
+ err.getLineNumber () + ", uri " + err.getSystemId ());
System.out.println(" " + err.getMessage ());

}catch (SAXException e) {
Exception x = e.getException ();
((x == null) ? e : x).printStackTrace ();

}catch (Throwable t) {
t.printStackTrace ();
}
//System.exit (0);

}//end of main


}

There are better implementations of reading XML files which would work for any XML file. The above one would require a few changes every time the XML tag names change. But this is much more simpler than the other programs.

Tuesday, March 10, 2009

The Purpose of the Marker Interface

One of the "clean" features of the Java programming language is that it mandates a separation

between interfaces (pure behavior) and classes (state and behavior). Interfaces are used in Java to

specify the behavior of derived classes.

Often you will come across interfaces in Java that have no behavior. In other words, they are just

empty interface definitions. These are known as marker interfaces. Some examples of marker

interfaces in the Java API include:


- java,lang.Cloneable
- java,io.Serializable
- SingleThreadMode
- java.util.EventListener

Marker interfaces are also called "tag" interfaces since they tag all the derived classes into a category

based on their purpose. For example, all classes that implement the Cloneable interface can be cloned

(i.e., the clone() method can be called on them). The Java compiler checks to make sure that if the

clone() method is called on a class and the class implements the Cloneable interface. For example,

consider the following call to the clone() method on an object o:


SomeObject o = new SomeObject();
SomeObject ref = (SomeObject)(o.clone());

If the class SomeObject does not implement the interface Cloneable (and Cloneable is not

implemented by any of the superclasses that SomeObject inherits from), the compiler will mark this

line as an error. This is because the clone() method may only be called by objects of type "Cloneable."

Hence, even though Cloneable is an empty interface, it serves an important purpose.
--------------------------------------------------------------------------------------------------------
java programming language
interface is nothing but the collection of methods with empty implementations and constants variables

( variables with static and final declarations ). All the methods in an interface are "public and abstract"

by default. Since interfaces are abstract in nature so they can not be directly instantiated. To define

the methods of an interface the keyword "implements" is used. Interfaces are similar to abstract

classes but the major difference between these two is that interface have all the methods abstract

while in case of abstract classes must have at least one abstract method. Interface combines the two

functionality (template and multiple inheritance) of C++ language into one (in itself).

Interface Definition
visibility mode interface interfaceName{
constant variable declarations
abstract method declarations
}

e.g.

public interface RacingCar{
public void startcar (int Obj);
public void changegear (int Obj);
public void incrrace (int Obj);
public void stopcar (int Obj);
}

Marker Interface

In java language programming, interfaces with no methods are known as marker interfaces. Marker

interfaces are Serializable, Clonable, SingleThreadModel, Event listener. Marker Interfaces are

implemented by the classes or their super classes in order to add some functionality.

e.g. Suppose you want to persist (save) the state of an object then you have to implement the

Serializable interface otherwise the compiler
will throw an error. To make more clearly understand the concept of marker interface you should go

through one more example.

Suppose the interface Clonable is neither implemented by a class named Myclass nor it's any super

class, then a call to the method clone() on Myclass's object will give an error. This means, to add this

functionality one should implement the Clonable interface. While the Clonable is an empty interface but

it provides an important functionality.

Difference between Interfaces and abstract classes ?

Tuesday, March 3, 2009

Application Server Vs Web Server

I have been bugged with this question many a times so finally i have decided to write a small blog entry on the same.
An Application Server (like Glassfish) is more sophisticated and complex (read intelligent) when compared with a Web Server (like Tomcat). A Web server is based on HTTP request-response model and generally acts as a web container for JSP's and Servlets. You give it a request and back comes the reply.
On the other hand, an Application Server can be used to serve business logic to applications programs, generally in a n-tier architecture (n>2), through any number of protocols (HTTP, HTTPS, IIOS/SSL). It is this capability of an appserver to cater the needs of a separate business layer in a 3-tier architecture through a component API (like EJB's) that makes enterprise level applications far more scalable. By separating the business logic from presentation layer, we make the business logic reusable between and within applications. Moreover, an application server manages its own resources. It takes care of other important issues like Transaction Management, Security, Database Connection Pooling, Clustering, Scalability and Messaging etc. A web server cannot provide these.
An Application server like Glassfish also provides the administrator with something known as Glassfish Admin Console, using which he/she can easily manage and utilize various resources like Connection Pools, JavaMail Sessions. More on this coming up soon.
Generally, all application servers contain a web server in them or you can say that a web server is a small subset of what comprises of an Application Server. Generally, all application server comes with two types of containers:
• Web Container
• EJB(Enterprise JavaBeans) Container
Difference b/w Glassfish & Tomcat in Arun Gupta's words,
- Tomcat is only a JSP/Servlet container. Everything else such as Web services, all the "Web 2.0" style processing, etc need to be installed in the container. Because it's only JSP/Servlet container, it's light-weight.
- Glassfish is a full Java EE 5 compliant App server. JSP/Servlet is just one component of Java EE 5, then there is Enterprise Java Beans, Web services, XML Binding, Security, Reliability, Transactions, Clustering, High Availability, Fault Tolerance and such enterprise features. GlassFish comes pre-bundled and pre-configured to handled those. In case of Tomcat, you need to install additional software for each of these components.
As a matter of fact, i'm an avid follower of Glassfish and strongly recommend Glassfish to developers worldwide, various reasons pamper me to do so:
• It is Open Source
• It's supported, maintained & developed by Sun Microsystems and others too.
• It is fully Java EE 5 compliant and any new technology as and when introduced (even in future), GF will support that also.

Monday, March 2, 2009

Simple form client Validation in JavaScript

function mywholeform(){
document.myform.username.style.background = 'white';
document.myform.pwd.style.background = 'white';
document.myform.firstname.style.background = 'white';
document.myform.lastname.style.background = 'white';
document.myform.email.style.background = 'white';
document.myform.phno.style.background = 'white';

if(checkUserName())
{
alert("-enter valid data-");
document.myform.username.focus()
return false;
}else if(checkPwd()){
alert("-enter valid data-");
document.myform.pwd.focus()
return false;
}else if(checkUserFirstName())
{
alert("-enter valid data-");
document.myform.firstname.focus()
return false;
}else if(checkUserLastName())
{
alert("-enter valid data-");
document.myform.lastname.focus()
return false;
}
else if(checkEmail()){
alert("-enter valid data-");
document.myform.email.focus()
return false;
}else if(checkPhno()){
alert("-enter valid data-");
document.myform.phno.focus()
return false;
}

else{
alert("- u have enterd valid data-");
return true;
}
}
function checkUserName(){
var name=document.myform.username.value;

if (name == "")
{

alert("-1-");
document.myform.username.style.background = 'Yellow';
return true;
}

else if ((name.length < 4) || (name.length > 10))
{
alert("-2-");
document.myform.username.style.background = 'Yellow';
return true;
}else if (name.match(/[\<\>!@#\$%^&\*,]+/i) ) {
document.myform.username.style.background = 'Yellow';
alert("-3-");

return true;

}else if (name.match(/[\<\>!@#\$%^&\*,]+/i) ) {
document.myform.username.style.background = 'Yellow';
alert("-3-");

return true;
}


else return false;
}
function checkPwd(){
var pwd=document.myform.pwd.value;

if (pwd == "")
{
alert("-4-");
document.myform.username.style.background = 'white';
document.myform.pwd.style.background = 'Yellow';
return true;
}

else if ((pwd.length < 4 ) || (pwd.length > 10))
{
alert("-5-");
document.myform.username.style.background = 'white';
document.myform.pwd.style.background = 'Yellow';
return true;

}
else if (pwd.match(/[\<\>!@#\$%^&\*,]+/i) )
{
alert("-6-");
document.myform.username.style.background = 'white';
document.myform.pwd.style.background = 'Yellow';
return true;
}

else if (!((pwd.search(/[a-z]+/) > -1) && (pwd.search(/[A-Z]+/) > -1) && (pwd.search(/[0-9]+/) > -1)))
{
alert("-7-");

return true;

}
else return false;

}
function checkUserFirstName(){

var name=document.myform.firstname.value;

if (name == "")
{
alert("-8-");
document.myform.username.style.background = 'white';
document.myform.pwd.style.background = 'white';
document.myform.firstname.style.background = 'Yellow';
return true;
}

else if ((name.length < 4) || (name.length > 10))
{
alert("-9-");
document.myform.username.style.background = 'white';
document.myform.pwd.style.background = 'white';
document.myform.firstname.style.background = 'Yellow';
return true;
}else if (name.match(/[\<\>!@#\$%^&\*,]+/i) ) {

alert("-10-");
document.myform.username.style.background = 'white';
document.myform.pwd.style.background = 'white';
document.myform.firstname.style.background = 'Yellow';
return true;

}else if (name.match(/[\<\>!@#\$%^&\*,]+/i) ) {

alert("-11-");
document.myform.username.style.background = 'white';
document.myform.pwd.style.background = 'white';
document.myform.firstname.style.background = 'Yellow';
return true;
}


else return false;
}
function checkUserLastName(){

var name=document.myform.lastname.value;

if (name == "")
{
alert("-12-");
document.myform.username.style.background = 'white';
document.myform.pwd.style.background = 'white';
document.myform.firstname.style.background = 'white';
document.myform.lastname.style.background = 'Yellow';
return true;
}

else if ((name.length < 4) || (name.length > 10))
{
alert("-13-");
document.myform.username.style.background = 'white';
document.myform.pwd.style.background = 'white';
document.myform.firstname.style.background = 'white';
document.myform.lastname.style.background = 'Yellow';
return true;
}else if (name.match(/[\<\>!@#\$%^&\*,]+/i) ) {

alert("-14-");
document.myform.username.style.background = 'white';
document.myform.pwd.style.background = 'white';
document.myform.firstname.style.background = 'white';
document.myform.lastname.style.background = 'Yellow';
return true;

}else if (name.match(/[\<\>!@#\$%^&\*,]+/i) ) {

alert("-15-");
document.myform.username.style.background = 'white';
document.myform.pwd.style.background = 'white';
document.myform.firstname.style.background = 'white';
document.myform.lastname.style.background = 'Yellow';
return true;
}


else return false;
}

function checkEmail(email){
var email=document.myform.email.value;

if (email == "")
{
alert("-16-");
document.myform.username.style.background = 'white';
document.myform.pwd.style.background = 'white';
document.myform.firstname.style.background = 'white';
document.myform.lastname.style.background = 'white';
document.myform.email.style.background = 'Yellow';

return true;
}

else if ((email.length < 6 ) || (email.length > 20))
{
alert("-17-");
document.myform.username.style.background = 'white';
document.myform.pwd.style.background = 'white';
document.myform.firstname.style.background = 'white';
document.myform.lastname.style.background = 'white';
document.myform.email.style.background = 'Yellow';

return true;

}

else if (email.match(/[\<\>!#\$%^&\*,]+/i))
{
alert("-18-");
document.myform.username.style.background = 'white';
document.myform.pwd.style.background = 'white';
document.myform.firstname.style.background = 'white';
document.myform.lastname.style.background = 'white';
document.myform.email.style.background = 'Yellow';

return true;
}client


else return false;
}
function checkPhno(phno){
var phno=document.myform.phno.value;
if (phno == "")
{
alert("-19-");
document.myform.username.style.background = 'white';
document.myform.pwd.style.background = 'white';
document.myform.firstname.style.background = 'white';
document.myform.lastname.style.background = 'white';
document.myform.email.style.background = 'white';
document.myform.phno.style.background = 'Yellow';

return true;
}
else if (isNaN(parseInt(phno)))
{
alert("-20-");
document.myform.username.style.background = 'white';
document.myform.pwd.style.background = 'white';
document.myform.email.style.background = 'white';
document.myform.phno.style.background = 'Yellow';
return true;
}

else if (!(phno.length == 10))
{
alert("-21-");
document.myform.username.style.background = 'white';
document.myform.pwd.style.background = 'white';
document.myform.firstname.style.background = 'white';
document.myform.lastname.style.background = 'white';
document.myform.email.style.background = 'white';
document.myform.phno.style.background = 'Yellow';
return true;
}
else return false;
}