javax.xml.xpath package provides support for executing XPath expressions against a given XML document. The XPath expressions can be compiled for performance reasons, if it is to be reused.
By the way, the XPath APIs in JAXP are designed to be stateless, which means every time you want to evaluate an XPath expression, you also need to pass in the XML document. Often, many XPath expressions are evaluated against a single XML document. In such a case, it would have been better if the XPath APIs in JAXP were made stateful by passing the XML document once. The underlying implementation would then have had a choice of storing the XML source in an optimized fashion (say, a DTM) for faster evaluation of XPath expressions.
Sample XML to evaluate the XPath expressions :
<?xml version="1.0"?>
<employees>
<employee>
<name>e1</name>
</employee>
<employee>
<name>e2</name>
</employee>
</employees>
Code to evaluate the xml:
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class XpathTest
{
public void parseXml()throws Exception{
//parse an XML to get a DOM to query
DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
dbfactory.setNamespaceAware(true);
dbfactory.setXIncludeAware(true);
DocumentBuilder parser = dbfactory.newDocumentBuilder();
Document doc = parser.parse(new File("data.xml"));
//get an XPath processor
XPathFactory xpfactory = XPathFactory.newInstance();
XPath xpathprocessor = xpfactory.newXPath();
//set the namespace context for resolving prefixes of the Qnames
//to NS URI, if the xpath expresion uses Qnames. XPath expression
//would use Qnames if the XML document uses namespaces.
//xpathprocessor.setNamespaceContext(NamespaceContext nsContext);
//create XPath expressions
String xpath1 = "/employees/employee";
XPathExpression employeesXPath = xpathprocessor.compile(xpath1);
String xpath2 = "/employees/employee[1]";
XPathExpression employeeXPath = xpathprocessor.compile(xpath2);
String xpath3 = "/employees/employee[1]/name";
XPathExpression empnameXPath = xpathprocessor.compile(xpath3);
//execute the XPath expressions
System.out.println("XPath1="+xpath1);
NodeList employees = (NodeList)employeesXPath.evaluate(doc, XPathConstants.NODESET);
for (int i=0; i<employees.getLength(); i++) {
System.out.println(employees.item(i).getTextContent());
}
System.out.println("XPath2="+xpath2);
Node employee = (Node)employeeXPath.evaluate(doc, XPathConstants.NODE);
System.out.println(employee.getTextContent());
System..out..println("XPath3="+xpath3);
String empname = empnameXPath.evaluate(doc);
System.out.println(empname);
}
}
Thursday, August 30, 2007
Evaluating XML's XPath Expressions
Posted by
Hari
at
3:05 AM
2
comments
Caching static and semi-static data in JSP
A JSP is a combination of different sections. For example, the basic sections that a JSP contains are header, footer, navigation and body sections. These sections are generally independent of each other and most of these sections are either static or semi-static. For example, product categories in navigation bar do not change frequently. When you call a JSP, it process all data (static, semi-static and dynamic content) on every request but what we actually require to process is just the dynamic content.
So how can we avoid unnecessary static or semi-static data processing in JSP on every user request?
The recipe for this problem is to identify and cache static and semi-static sections in JSP. Cache should be refreshed at certain times depending up on data refreshing policy. If the data is fully static, you don't have to refresh it but it is a good practice to refresh after every day or week to make sure that any changes are reflected in JSP. A typical example of fully static data section is footer section in your JSP. If the data is semi-static, you should refresh the cache often depending upon its state change policy. An example for semi-static data sections in JSP is header or navigation sections. And some of the body sections also may be semi-static. You can identify and cache them accordingly to improve performance.
we have used free and well-implemented caching code oscache from opensymphony.com in this sample. You can see information on this at www.opensymphony.com/oscache. The below code shows the usage of caching in JSP subsections using oscache.
Code:
<%@ page import="com.cookbook.servlet.helper.*" %>
<%@ taglib uri="oscache" prefix="cache" %>
<cache:cache>
<%! public String getItems(){
ItemsHelper helper = new ItemsHelper();
List list = helper.getAllItems();
StringBuffer body = new StringBuffer();
if(list != null && list.size()>0){
ListIterator iter = list.listIterator();
body.append("<TABLE border=\"1\"><TBODY>");
while (iter.hasNext()) {
Item item = (Item) iter.next();
body.append("<TR>");
body.append("<TD>");
body.append(item.getName());
body.append("</TD>");
body.append("<TD>");
body.append(item.getDesc());
body.append("</TD>");
body.append("</TR>");
}
body.append("</TBODY></TABLE>");
}
return body.toString();
}
%>
Discussion:
You can cache any section of your JSP as shown in the above code. You can also give the location of cache store as application or session scope parameter in the oscache tag. The default is application scope. You should be careful when you use session scope in a clustered environment where the session data could be stored as persistent sessions depending upon configuration. There will be overhead involved in persistent sessions if the session data is huge.
In order to utilize oscache, all you need to do is just download the zip file from opensymphony.com/oscache, unzip it and place oscache.jar in /web-inf/lib directory, place oscache.properties and taglib.tld files in web-inf directory and configure web.xml file for this tag library as follows.
<taglib>
<taglib-uri>oscache</taglib-uri>
<taglib-location>/WEB-INF/oscache.tld</taglib-location>
</taglib>
You can also configure other caching properties in oscache such as cache capacity and type of algorithm in oscache.properties file.
Posted by
Hari
at
12:48 AM
0
comments
Labels:
jsp
Wednesday, August 29, 2007
String replace in a File
This is the code to replace the existing String with the given String in a given file present in the given directory.
Code:
public void replaceStringInFile(File dir, String fileName, String match, String replacingString){
try {
File file = new File(fileName);
if(file.isDirectory()||!file.exists()){
//the fileName specified is not a file hence returning.
return;
}
file = new File(dir, fileName);
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
long fpointer = randomAccessFile.getFilePointer();
String lineData = "";
while((lineData =randomAccessFile.readLine()) != null){
fpointer = randomAccessFile.getFilePointer() - lineData.length()-2;
if(lineData.indexOf(match) > 0){
System.out.println("Changing string in file "+file.getName());
randomAccessFile.seek(fpointer);
randomAccessFile.writeBytes(replacingString);
// if the replacingString has less number of characters than the matching string line then enter blank spaces.
if(replacingString.length() < style="color: rgb(153, 0, 0);">int difference = (lineData.length() - replacingString.length())+1;
for(int i=0; i < style="color: rgb(51, 51, 255);">" ");
}
}
}
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} catch (Exception ex){
ex.printStackTrace();
}
}
Posted by
Hari
at
4:11 AM
2
comments
Labels:
Files
Friday, August 24, 2007
Time Scheduling in Java
Some Applications need to execute certain jobs and tasks at an exactly a perticular time or at regular time intervals. Let us see how to schedule the tasks to achieve that functionality, for this purpose java provides a standerd API Timer in java.util package, Now we will see how Java developers can implement such a requirement using the standard Java Timer API.
A Sample Code To use Timer:
import java.util.Timer;
import java.util.TimerTask;
public class Remainder {
Timer timer;
public Remainder ( int seconds ) {
timer = new Timer ( ) ;
timer.schedule ( new TimerTask(){
public void run ( ) {
System.out.println ( "Your scheduled Task Starts...." ) ;
timer.cancel ( ) ; //Terminate the Timer after task completion
}
} , seconds*1000 ) ;
}
public static void main (String args[]){
System.out.println ( "Before schedule task." ) ;
new Remainder ( 5 ) ;
System.out.println ( "Task scheduled." ) ;
}
}
Posted by
Hari
at
12:19 AM
0
comments
Labels:
scheduling
Wednesday, August 22, 2007
Working with Online xml
Some times we required to access the xml files which are present at online or working with another site it is required to access the data through the xml.This artical deals how to work with online xml file.The below sample code parse the xml file throuth the given URL String and returns the DOM Document.Then we can access the xml file using that document.
Code:
import java.io.InputStream;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class DOMProvider{
public Document getDocument(String strUrl)throws Exception{
URL url=new URL(strUrl);
InputStream in=url.openStream();
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
Document document=builder.parse(in);
return document;
}
}
After getiing the document from getDocument() if you want to get retrive entire node list that can be done by
NodeList nodeList=document.getElementsByTagName("NameofTheNode");
By these all the node will come in that Node List.If you want to retrive the attributes with in that Node,that can be done by
Node node= nodeList.item(indx);
NamedNodeMap attrs=node.getAttributes();
String value=nnm.getNamedItem("AttributeNamewithinthatNode").getNodeValue();
Sample Work:
http://www.w3schools.com/xml/note.xml is in the form of
to work with the above xml as:
Code:
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Test{
public static void main(String[] args)throws Exception{
DOMProvider test=new DOMProvider();
Document doc=test.getDocument("http://www.w3schools.com/xml/note.xml");
Node node=doc.getDocumentElement();
System.out.println("Root Node: "+node.getNodeName());
NodeList list=node.getChildNodes();
int childsLen=list.getLength();
for(int index=0;index
Node tag=list.item(index);
if(tag.getNodeType()==Node.ELEMENT_NODE){
NodeList val=tag.getChildNodes();
int vallen=val.getLength();
System.out.println("Tag Name: "+tag.getNodeName());
for(int i=0;i
if(val.item(i)!=null)
System.out.println("Tag Value: "+val.item(i).getNodeValue());
}
System.out.println();
}
}
}
}
OutPut:
Root Node: note
Tag Name: to
Tag Value: Tove
Tag Name: from
Tag Value: Jani
Tag Name: heading
Tag Value: Reminder
Tag Name: body
Tag Value: Don't forget me this weekend!
Posted by
Hari
at
3:44 AM
0
comments
Labels:
xml
ZIP Files in Java
The ZIP file format has become extremely popular for the distribution and storage of files. ZIP files allow for compression, making transporting a set of files from one location to another faster.Depending on the source file types being compressed, ZIP files can provide significant space savings. ZIP archives can also maintain the directory structure of files that are compressed, making the ZIP format a formidable file transport mechanism.
The java.util.zip package allows for the programmatic reading and writing of the ZIP and GZIP formats.Learning how to use the offerings of the java.util.zip package might best be facilitated via example.
The below example FileZip class has only one method makeZip(), takes two parameters,
String Array- Pass the files paths as strings which you want to Zip.
String - The target zip file name to save as.
Code:
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;
import java.util.zip.Deflater;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipFiles {
public String makeZip(String[] filesToZip,String zipFileName){
byte[] buffer = new byte[18024];
if(!zipFileName.endsWith(".zip")){
zipFileName+=".zip";
}
try {
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFileName)));
// Set the compression ratio
out.setLevel(Deflater.DEFAULT_COMPRESSION);
// iterate through the array of files, adding each to the zip file
int filesSiz=filesToZip.length;
for (int i = 0; i < style="color: rgb(0, 153, 0);">// Associate a file input stream for the current file
File file2Zip=new File(filesToZip[i].toString());
InputStream in = new BufferedInputStream(new FileInputStream(file2Zip));
// Add ZIP entry to output stream.
String fileExctNm=filesToZip[i].substring(filesToZip[i].lastIndexOf("/")+1);
out.putNextEntry(new ZipEntry(fileExctNm));
// Transfer bytes from the current file to the ZIP file
int len;
while ((len = in.read(buffer)) > 0)
{
out.write(buffer, 0, len);
}
// Close the current entry
out.closeEntry();
// Close the current file input stream
in.close();
}
// Close the ZipOutPutStream
out.close();
}
catch (IllegalArgumentException iae) {
iae.printStackTrace();
}
catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
return new File(zipFileName).toString();
}
}
Posted by
Hari
at
2:22 AM
2
comments
Labels:
zip
Tuesday, August 21, 2007
Receive Application Errors via Yahoo Messenger
Logging application events is a central part of many applications. Most of our applications do some sort of logging, using a variety of mechanisms. When things go wrong, the first course of action is usually to get hold of the application log file and go through its contents.
Someone supporting live, deployed applications would probably appreciate the importance of getting notified of application errors as early as possible. It is much better to be proactive dealing with errors, rather than waiting to hear from the customer that something seems to have gone wrong.
How about getting notified immediately, by utilizing an instant messenger client like Yahoo Messenger? (Read More..)
Posted by
Hari
at
2:49 AM
0
comments
Labels:
log4j