Wednesday, September 14, 2011

XPath Tutorial


Hi All,
Please i have small description of the XPath Parser usage in Java instead of the DOM or SAX parsers. The XPath language provides a simple, concise syntax for selecting nodes from an XML document. XPath also provides rules for converting a node in an XML document object model (DOM) tree to a boolean, double, or string value.



Below i have written  a Simple XPath Tutorial program in java
import javax.xml.xpath.*;

public static void main(String args[]){
          String xmlString = "<employees>"+
                                         "<employee> "+
"<name>"+
"Johny"+
"</name>"+
"<name>"+
"Williams"+
"</name>"+
"</employee>"+
"</employees>" ;
try{
//To get an instance of the XPathFactory object itself.

XPathFactory xPathFactory = XPathFactory.newInstance();
// Create an instance of XPath from the factory class

XPath xPath = xPathFactory.newXPath();
String expression = "/employees/employee/name";
// Compile the expression to get a XPathExpression object.
XPathExpression xpathExpression = xPath.compile(expression);
//Evaluate the expression against the XML Document to get the result.
Object result = xpathExpression.evaluate(new InputSource(new StringReader(xmlString)));


}catch(XPathExpressionException e){
e.printStackTrace();
}
}


The above program will give the name of all the employees in the xml Document.

  • If at all you need only the first employee name pass the expression value as :-

                  String expression = "/employees/employee[1]/name"; 
                  will return only the first employee name.

  • If you need to pass a document instead of an xmlString then follow the below process for reading the xml document.
       String  xmlFile = "TestFile.xml";
        Document xmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile);
At the lat pass the only xmlDocument to evaluate() method instead of 
xmlString See Below:-
xPathExpression.evaluate(xmlDocument, returnType);
//returnType can be any of the QNames available in XPath Package:-
//XPathConstants.STRING, XPathConstants.NUMBER, XPathConstants.BOOLEAN, 
//XPathConstants.NODE and XPathConstants.NODESET. 

                              OR
      XPathReader reader = new XPathReader("src\\com\\javabeat\\tips\\xpath\\projects.xml"); 
reader.read(expression, XPathConstants.STRING)

// To get a xml attribute.
String expression = "/projects/project[1]/@id";
System.out.println(reader.read(expression, 
XPathConstants.STRING) + "\n");

// To get a child element's value.
expression = "/projects/project[2]/name";
System.out.println(reader.read(expression, 
XPathConstants.STRING) + "\n");

// To get an entire node
expression = "/projects/project[3]";
NodeList thirdProject = (NodeList)reader.read(expression,
XPathConstants.NODESET);
traverse(thirdProject);

public static void traverse(NodeList rootNode){
for(int index = 0; index < rootNode.getLength();index ++){
Node aNode = rootNode.item(index);
if (aNode.getNodeType() == Node.ELEMENT_NODE){
NodeList childNodes = aNode.getChildNodes();
if (childNodes.getLength() > 0){
System.out.println("Node Name-->" + aNode.getNodeName() +" , Node Value-->" + aNode.getTextContent());
}
traverse(aNode.getChildNodes());
}
}
}



Tuesday, September 6, 2011

Creation Of PDF Document in JAVA

Here i'm giving a simple program for creating a pdf document using java.
Prerequsite jars are :-
iText.jar


Remark:
  1. Once a document is created you can add some meta information.
  2. You can also set the headers/footers.
  3. You have to open the document before you can write content.
  4. You can only write content (no more meta-formation!) once a document is opened.
  5. When you change the header/footer on a certain page, this will be effective starting on the next page.
  6. After closing the document, every listener (as well as its OutputStream) is closed too.
Below is the main program:-
import com.itextpdf.text.*;

public class DataIntoPDF{


public static void main(String args[]){
//create a document
Document PDFDocument = new Document(PageSize.A4,50,50,50,50);
try{
//pdfwriter instance for writing the data to a file.FileOutput writes the data using output stream to the file specified.If the file doesn't exists throws file not found exception.
PdfWriter pdfWriter  = PdfWriter.getInstance(PDFDocument, new FileOutputStream("E:/pdfData.pdf"));
//add meta information to document
pDFDocument.addAuthor("Anand Kumar");
pDFDocument.addCreator("Anand Kumar");
pDFDocument.addSubject("PDF Creation");
pDFDocument.addCreationDate();
pDFDocument.addTitle("PDf Creation");
PDFDocument.open();
                        String dataToPDF  = 
                                        "Anand Kumar,
                                            " +
 Information only
                                           " +
"Nothing Confidential," +
"
                                                   Just Follow,
                                                  " +
"
                                     Address– " +
"Not Mine Write your Own 
                                      ";

Paragraph p = new Paragraph(dataToPDF);
PDFDocument.add(p);
//Adds a new page to the existing document
PDFDocument.newPage();
Image image = getImageFromResource("/PathtoImage/ImageFile");
Chunk imageChunk = new Chunk(image,-5,0);
PDFDocument.add(imageChunk);
}catch(DocumentException de){
de.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
PDFDocument.close();

}


//For Image resource
private static Image getImageFromResource(String URI){
Image image = null;
try{
image = Image.getInstance(URI);
}catch(IOException ioe){
de.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
return image;
}


}

If any modifications are appreciated.
Thankyou.......................!!!!!!!!!!!!!!!!:-)

Wednesday, July 27, 2011

Excel Creation Using JAVA

Creating the Excel using JAVA


POI terminology

The key terms associated with Jakarta POI are as follows:

  • POIFS (Poor Obfuscation Implementation File System): Java APIs for reading and writing OLE (Object Linking and Embedding) 2 compound document formats
  • HSSF (Horrible Spreadsheet Format): Java API to read Microsoft Excel
  • HDF (Horrible Document Format): Java API to read and write Microsoft Word 97
  • HPSF (Horrible Property Set Format): Java API for reading property sets using (only) Java

Create an Excel document

The Jakarta POI API can be used to create an Excel document programmatically. The important steps involved are:

  • Create a workbook: HSSFWorkbook workbook = new HSSFWorkbook();
  • Create a new worksheet in the workbook and name the worksheet "Java Excels": HSSFSheet sheet = workbook.createSheet("Java Excels");
  • Create a new row in the sheet: HSSFRow row = sheet.createRow((short)0);
  • Create a cell in the row: HSSFCell cell = row.createCell((short) 0);
  • Put some content in the cell: cell.setCellValue("Have a Cup of XL");
  • Write the workbook into the filesystem: workbook.write(fileOutputStream);

The key steps in reading the Excel sheet are as follows:

  • Create a new Excel document reference: HSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(fileToBeRead));.
  • Refer to the sheet: By default, the first sheet in the Excel document is at reference 0: HSSFSheet sheet = workbook.getSheetAt(0);. A sheet can also be referred to by name. Let's assume that the Excel sheet has the default name "Sheet1". It can be referred to as follows:HSSFSheet sheet = workbook.getSheet("Sheet1");.
  • Refer to a row: HSSFRow row = sheet.getRow(0);.
  • Refer to a cell in the row: HSSFCell cell = row.getCell((short)0);.
  • Get the values in that cell: cell.getStringCellValue();.

A Practical Example

Let's concentrate on just the interesting steps of Jakarta POI usage:

  • Create a new Excel document: workbook = new HSSFWorkbook();
  • Make a worksheet in that document and give the worksheet a name:sheet = workbook.createSheet("Java Class Info");
  • Set the first three columns' widths:sheet.setColumnWidth((short)0,(short)10000 );
  • Create the header line: HSSFRow row = sheet.createRow((short)0);
  • Create and set font and cell style:
       HSSFFont font = workbook.createFont();    font.setColor(HSSFFont.COLOR_RED);    font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);    // Create the style       HSSFCellStyle cellStyle= workbook.createCellStyle();       cellStyle.setFont(font); 
  • Use the cell style:
          HSSFCell cell = row.createCell((short) 0);       cell.setCellStyle(cellStyle);       cell.setCellType(HSSFCell.CELL_TYPE_STRING);       cell.setCellValue("Class Name "); 
  • Write the output file:
          FileOutputStream fOut = new FileOutputStream(outputFile);       // Write the Excel sheet       workbook.write(fOut);       fOut.flush();       // Done deal. Close it.       fOut.close(); 

A Good Reference for the HSSFWorkBook is provided below:- http://poi.apache.org/spreadsheet/quick-guide.html

Friday, June 17, 2011

JAVA DLL BRIDGE

Hi All,
I made a small research in the java program , on how to call windows DLL files using Java program.
Actually this is task provided for me by the project Manager. In our project, there has been a requirement that, when the client clicks on a link.It must call the scanner machine, scan the Image selected by the client and paste it in some location in the system after scanning.

Dlls considered as a native application, not like any applications.
Using the dll libraries within the .Net framework is such an easy operation, just we need to load the library within the environment, initiate an object from it, then use it like any other object in the program.

Such an immediate operation does not exist for the java environment, so that there are some interfaces and frameworks has been built that allow java programmers to interact with dll libraries and use their functionality within java applications.
So, almost this has taken 3 days for me to get the solution. Might be more but have some reasons behind it. Coming directly to the solution.

Firstly, i have googled for loading the DLL files using JAVA program. They are providing the solution using the System.loadLibrary() or System.load(). But they din't worked out for me.In the middle got frustated might not be possible. Latter, thought that how come this will not come for me. After coming from office to home sat for 2 or 3 hours on the system googled it out. Came across JACOB . Thought this might work out for me for bringing the solution for my problem.
As the enviroment is not available at my home thought to implement it at the office.

Nex day went to the office, opened the same link.

The JACOB project is a generic COM bridge. It is licensed as open-source on sourceforge.net.
it is an ancronym for JAva COm Bridge. It only implements a generic bridge to call COM components from Java.
It is not the Java interface of Microsoft Office nor it supports directly its COM components
The way jacob is implemented is using JNI
and a c++ DLL designed for the windows platform. COM is a binary standard
defined by Microsoft as it hasn’t been ported over (as far as I know) to any
other platforms yet. Jacob is only a java bridge for COM which defines how
components talk to each other when they are on the same machine.

JACOB is a JAva-COm Bridge that allows you to call COM automation components from Java. It uses JNI internally to make native calls into COM and Win32 libraries. In simple words, you can now call any of the .dll file functions from Java and use the result in your Java program (provided you know which function to call)”, JNI is the Java Native Interface.
Written a program to invoke the DLL file using Jacob – JAva COm Bridge.

Made a Sample Project in Eclipse having a standalone java program. This program makes use of methods available in Jacob jar files. These methods make the java program to invoke the methods available in the dll file.

Pre-requisite before running the program are:-

Put Jacob.dll in the directory that Windows searches for the libraries(in my computer – “Windows/system32”).

Put Jacob.jar in my CLASSPATH or BuildPath.

Registered the user-defined DLL or my.DLL using the .net framework – located in my system at :- “C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727” through command prompt - C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727> RegAsm/codebase "E:/JARS/ImageAssembly/ImageAssembly.dll".

If the registration has been successfully done. There will not be any errors related to the

dll file. If the library is not registered, or not registered properly, an exception will be

thrown (ComFailException: Can't get object clsid from progid) .

Now write the java program to access the methods available in dll file.

> First load library using ActiveXComponent class available in Jacob.jar as below:-
Ex: ActiveXComponent comp = new

ActiveXComponent("ImageAssembly.CallScanner");
//Where ImageAssembly - Name of the dll file
CallScanner - Class name

Then call the Dispatch.call method of the Jacob.jar file. This returns a variant.Depending

on the return type of the method you are calling in the Dispatch.call - append respective

return type to Dispatch.call().
Ex:- Dispatch.call().toString();
Dispatch.call().toInt();

Now I’m able to access the methods available in the dll using the dispatch class methods available from Jacob jar.

Thanks a lot to JACOB for providing such a simple, efficient app.

If anybody wants the link here it is:-