Thursday, July 30, 2009

Java Source Code to validate XML with XSD

In this article, we are going to learn the source code to validate an XML with an existing XSD.

An XSD (XML schema definition) describes the structure of an XML document. The purpose of an XML Schema is to define the legal building blocks of an XML document

However, without going into much details of XML and XSD, please see the below code to validate an XML with a given XSD.

The XML and XSD which we are using here are SampleXML.xml and SampleXSD.xsd.

import java.io.File;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;


public class XMLVaildationWithXSD {

XMLVaildationWithXSD(){

}

public static void main(String[] args) {
XMLVaildationWithXSD xmlValidationWithXSD = new XMLVaildationWithXSD();
xmlValidationWithXSD.validate();
}

private void validate() {
try{
// parse an XML document into a DOM tree
DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = parser.parse(new File("./SampleXML.xml"));
// create a SchemaFactory capable of understanding WXS schemas
SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
// load a WXS schema, represented by a Schema instance
Source schemaFile = new StreamSource(new File("./SampleXSD.xsd"));
Schema schema = factory.newSchema(schemaFile);
//Schema schema = factory.newSchema(new File("./QoSMCSO.xsd"));
// create a Validator instance, which can be used to validate an instance document
Validator validator = schema.newValidator();
// validate the DOM tree
try {
//validator.validate(new DOMSource(document));
validator.validate(new StreamSource(new File("./SampleXML.xml")));
System.out.println("XML is valid");
} catch (SAXException e) {
System.out.println("instance document is invalid!"+e.getMessage());
e.printStackTrace();
}catch(Exception exp){
exp.printStackTrace();
}
}catch(ParserConfigurationException pcex){
System.out.println("ParserConfigurationException Message:: "+pcex.getMessage());
pcex.printStackTrace();
}catch(SAXException sexp) {
System.out.println("SAXException Message:: "+sexp.getMessage());
sexp.printStackTrace();
}catch(Exception e){
System.out.println("Message: ");
e.printStackTrace();
}
}

}

Tuesday, July 7, 2009

How to get the attribute of elements of an XML using DOM Parsing

In my earlier article, I have given you the code how to parse the XML file to extract the data onto it. It shows you how to extract the element name and their values.

This article enlightens you how to extract the attribute of an element, if any, which I missed out earlier.


However, we are using classes of the org.w3c.dom package which comes with JDK1.6 only. We are going to use getAttributes() method of Node class which will return a object of NamedNodeMap class.


The below program will list down all the attributes’ name and values.

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Attr;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class DOMXMLParser {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db;
Document xmlDoc;
Node node = null;
DOMXMLParser() {

}

private void getXMLDoc() {
try {
db = dbf.newDocumentBuilder();
xmlDoc = db.parse(new File("Company.xml")); // Input XML
} catch (ParserConfigurationException pce) {
System.out.println("ParseConfigurationException Encountered While Building The XML Document");
pce.printStackTrace();
} catch (IOException ioe) {
System.out.println("IO Excpetion Encountered While Reading In XML File !!!");
ioe.printStackTrace();
} catch (SAXException se) {
System.out.println("SAX/Parse Exception Encountered While Parsing XML File !!!");
se.printStackTrace();
} catch (IllegalArgumentException iae) {
System.out.println("IllegalArgumentException !!! Check If File Passed Is Null ... ");
iae.printStackTrace();
}
}

private void parseXMLFile() {
System.out.println("Root Element: " + xmlDoc.getDocumentElement().getNodeName());
System.out.println("Root Element Value: " + xmlDoc.getDocumentElement().getNodeValue());
NodeList nl = xmlDoc.getChildNodes(); //get the nodelist containing all the nodes
for (int ctr = 0; ctr < nl.getLength(); ctr++) {
getSystemComponents(nl.item(ctr)); // item method is used to get the node out of nodelist
}
}



private void getSystemComponents(Node n) {
System.out.println("Current Element: " + n.getNodeName());
if (n.hasChildNodes()) {
System.out.println("Has Child Nodes");
NodeList nodeList = n.getChildNodes();
for (int ctr = 0; ctr < nodeList.getLength(); ctr ++) {
getSystemComponents(nodeList.item(ctr)); //Recursive call to get the details of a node
}
}
// Code to extract the attributes of a node, if any
NamedNodeMap attributes = (NamedNodeMap)n.getAttributes();
if(attributes!=null){
for (int g = 0; g < attributes.getLength(); g++) {
Attr attribute = (Attr)attributes.item(g);
System.out.println(" Attribute: " + attribute.getName() + " with value " +attribute.getValue());
}
}
}



public static void main(String args[]) {
DOMXMLParser parser = new DOMXMLParser();
parser.getXMLDoc();
parser.parseXMLFile();
}
}

Source Code to write into a file-Java

In this section, I will give you the code how to write into the file using all possible classes of the java.io package.


The classes I am using here are:

BufferWriter, BufferedOutputStream, OutputStream, DataOutputStream, FileWriter, FileOutputStream,PrintWriter, PrintStream.


The below code tells you all possible way of writing into the file using the above classes.

import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.PrintStream;
import java.io.Writer;
import java.io.File;

public class FileWrite {

/** Creates a new instance of FileWrite */
public FileWrite() {
}
String stringTobeWritten = "This is line to be written";

private void writeBufferWriter(){
try{
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("ReadMeBufferedWriter.txt",true));
bufferedWriter.write(stringTobeWritten);
bufferedWriter.close();
}catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}


private void writeBufferedOutputStream(){
try{
BufferedOutputStream bufferedOutput = new BufferedOutputStream(new FileOutputStream("ReadMeBufferedOutputStream.txt"));
bufferedOutput.write(stringTobeWritten.getBytes());
bufferedOutput.write("\n".getBytes());
bufferedOutput.write(65); // the byte representation [Ascii code] of 'A'
bufferedOutput.close();
}catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}


private void writeOutputStream(){
try{
FileOutputStream fos = new FileOutputStream("ReadMeFileOutputStream.txt");
Writer out = new OutputStreamWriter(fos,"UTF8");
out.write(stringTobeWritten);
out.close();
}catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}



private void writeDataOutputStream(){
try{
FileOutputStream fos = new FileOutputStream("ReadMeDataOutputStream.txt");
DataOutputStream dos = new DataOutputStream(fos);
int ch = 65;
dos.writeChar(ch); // Writing Character ascii of A
dos.writeBytes(stringTobeWritten); // writing string
dos.close();
}catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}



private void writeFileWriter(){
try{
FileWriter fw = new FileWriter("ReadMeFileWriter.txt");
fw.write(stringTobeWritten+"\n");
fw.close();
}catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}


private void writeFileOutputStream(){
try{
FileOutputStream fos = new FileOutputStream("ReadMeFileOutputStream.txt");
fos.write(stringTobeWritten.getBytes());
fos.close();
}catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}

private void writePrintWriter(){
try{
PrintWriter printWriter = new PrintWriter("ReadMePrintWriter.txt");
printWriter.write(stringTobeWritten);
printWriter.write(stringTobeWritten.toCharArray()); // Character Array
printWriter.write("\n");
printWriter.write('C'); //Character
printWriter.write(65); // Ascii of 'A'
printWriter.close();
}catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}


private void writePrintStream(){
try{
File file = new File("ReadMePrintStream.txt");
PrintStream p = new PrintStream(new FileOutputStream(file, false));
p.println(stringTobeWritten);
p.close();
}catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}



public static void main(String argd[]) {
FileWrite fileWriter = new FileWrite();
fileWriter.writeBufferWriter();
fileWriter.writeBufferedOutputStream();
fileWriter.writeOutputStream();
fileWriter.writeDataOutputStream();
fileWriter.writeFileWriter();
fileWriter.writeFileOutputStream();
fileWriter.writePrintWriter();
fileWriter.writePrintStream();
}

}


Any suggestions/feedback appreciated.

Monday, July 6, 2009

Java Source Code to read from and write into a properties files

In many of applications we are developing in many of our live projects, we might find that there are different environments that we use while development phase, testing phase and production phase.

The paths, the input file and output file locations etc are varying in different environments and we generally build three different jars/wars/ears for three different environments.


However, if we use a file which contains the locations which can vary from environment to environment, we can easily build a single archive file and deploy into the environment with environment specific files.


These environment specific files can be achieved using Properties class of the java.util package and the files are called properties file.


Though I have given example of the environment, we can use heavily in each applications where there may be a susceptible change required frequently.


This will not only reduce the time to code each time, it will also reduce the cost for any changes required [if can be incorporated with properties files].

The code here does nothing but reading from properties file (SampleProperties.properties) and writing specific values into the properties file. Please see the entries and the outputs of the Properties file.

The properties file can be written in notepad and has to be saved with .properties extension.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class SampleProperties {
private Properties props;
private File fName = new File("./SampleProperties.properties");
public SampleProperties() {
props = new Properties();
try {
FileInputStream fis = new FileInputStream(fName);
props.load(fis);
} catch (FileNotFoundException fNFE){
fNFE.printStackTrace();
} catch (IOException iOEx){
iOEx.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}
public String getPathProperties(String propName) {
String retProp=new String("");
retProp = props.getProperty(propName);
return retProp;
}

public void setPathProperties(String propName,String propValue) {
try {
props.setProperty(propName,propValue);
props.store(new FileOutputStream(fName),"Updated");
props.load(new FileInputStream(fName));
} catch (FileNotFoundException fNFE) {
fNFE.printStackTrace();
} catch (IOException iOEx) {
iOEx.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}

public static void main(String[] args) {
SampleProperties sampleProps = new SampleProperties();
System.out.println("Value of key1 "+sampleProps.getPathProperties("key1"));
sampleProps.setPathProperties("key2","value2");
sampleProps.setPathProperties("key4","value4");
}
}
//End of class



SampleProperties.properties

Inputs:

Entries in the properties:


key1=value1
key2=value_Diff
key3=value3

Output (result of the writing into the properties file):

key4=value4
key3=value3
key2=value2
key1=value1



Hope you all will find it useful.

Java Source code to extract the disk space status for drives

JDK 1.6 introduces new functionalities to extract the disk space status for a particular drive. Check it out.


The following program will list out the details of the status for a particular drive.

/*
Class to deal with disk spaces
JDK 1.6 Compatible
*/

import java.io.File;
import java.text.DecimalFormat;

public class DiskSpace {
public static void main(String[] args){

File file = new File("D:\\");
DecimalFormat df = new DecimalFormat("##.##");

long totalSpace = file.getTotalSpace();
long usableSpace = file.getUsableSpace();
long freeSpace = file.getFreeSpace();

File drives[] = File.listRoots();

System.out.println("The drives available are: ");

// Loop through the drive list and display the drives.
for (int index = 0; index < drives.length; index++) {
System.out.println(drives[index]);
}

// Convert it to GigaBytes
double valueGBTotalSpace = (double) totalSpace / 1024 / 1024 / 1024;
double valueGBUsableSpace = (double) usableSpace/ 1024 / 1024 / 1024;
double valueGBFreeSpace = (double) freeSpace/ 1024 / 1024 / 1024;
double valueGBUsedSpace = (double) (totalSpace - freeSpace)/ 1024 / 1024 / 1024;



System.out.println("Total space in " + file + " partition is "+df.format(valueGBTotalSpace));
System.out.println("Total Usable space available in " + file + " partition is "+df.format(valueGBUsableSpace));
System.out.println("Total Free space available in " + file + " partition is "+df.format(valueGBFreeSpace));
System.out.println("Total Used space available in " + file + " partition is "+df.format(valueGBUsedSpace));
}
}


Hope you all will find it useful.

Java Source Code for extracting the folder and file details of a given drive/folder

Hi,


Today I am going to tell you the source code for extracting the each and every details of the files and folder of a given folder. Like in C:\ drive contains many folder as well as files; the folder in turn contains the files too. The below program will list out the details of all that files and folder.


Note: If you try to do it with C:\ drive, it might take longer time to complete the process as for most of the cases, it will contain Program Files, which itself contains thousands of the files and folders.


The source code as follows:

import java.io.File;

public class FileDetails {

FileDetails() {

}

private static void getFileDetails(File folder) {
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File under " + folder + " -> " + listOfFiles[i].getName());
} else if (listOfFiles[i].isDirectory()) {
System.out.println("Directory under " + folder + " -> " + listOfFiles[i].getName());
getFileDetails(listOfFiles[i]); // Recursive call of the directory to find out the files under that
}
}
}

public static void main(String[] args) {
FileDetails fileDetails = new FileDetails();
String directory = new String("C://");
File folder = new File(directory);
fileDetails.getFileDetails(folder);
}
}

Total Pageviews