Wednesday 17 August 2011

How to generating Excel file in Java ?

The ApacheSW Jakarta POI project, located at http://jakarta.apache.org/poi/ is a JavaSW library that allow you to manipulate Microsoft document formats. Within the POI project, POI-HSSF allows you to read, modify, and write Excel documents. The HSSF Quick Guide at http://jakarta.apache.org/poi/hssf/quick-guide.html is a great resouce for quickly getting up to speed with POI-HSSF.
Let's create a small Java class that writes some data to an Excel (xls) file. You can download the POI jar file from the Jakarta POI website and add it to your project, as illustrated below.

Please see the following class which generate a sample excel  :-

WriteExcelFile.java

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;

/**
 *
 * @author Prasobh.K
 */
public class WriteExcelFile {
   public static void main(String[] args) throws IOException {
        try {
            FileOutputStream fileOut = new FileOutputStream("sample.xls");
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet worksheet = workbook.createSheet("My Worksheet");

            // index from 0,0... cell A1 is cell(0,0)
            HSSFRow row1 = worksheet.createRow(0);

            HSSFCell cellA1 = row1.createCell( 0);
            cellA1.setCellValue("Hello");
            HSSFCellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setFillForegroundColor(HSSFColor.GOLD.index);
            cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            cellA1.setCellStyle(cellStyle);

            HSSFCell cellB1 = row1.createCell( 1);
            cellB1.setCellValue("Goodbye");
            cellStyle = workbook.createCellStyle();
            cellStyle.setFillForegroundColor(HSSFColor.LIGHT_CORNFLOWER_BLUE.index);
            cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            cellB1.setCellStyle(cellStyle);

            HSSFCell cellC1 = row1.createCell( 2);
            cellC1.setCellValue(true);

            HSSFCell cellD1 = row1.createCell( 3);
            cellD1.setCellValue(new Date());
            cellStyle = workbook.createCellStyle();
            cellStyle.setDataFormat(HSSFDataFormat
                    .getBuiltinFormat("m/d/yy h:mm"));
            cellD1.setCellStyle(cellStyle);

            workbook.write(fileOut);
            fileOut.flush();
            fileOut.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

Output




Reading Excel Files

Please see following example, which reads the sample.xls we already created.


ReadExcelFile.java

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

/**
 *
 * @author Prasobh.K
 */
public class   ReadExcelFile {
   public static void main(String[] args) throws IOException {
        try {
            FileInputStream fileInputStream = new FileInputStream("sample.xls");
            HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
            HSSFSheet worksheet = workbook.getSheet("My Worksheet");
            HSSFRow row1 = worksheet.getRow(0);
            HSSFCell cellA1 = row1.getCell(0);
            String a1Val = cellA1.getStringCellValue();
            HSSFCell cellB1 = row1.getCell(1);
            String b1Val = cellB1.getStringCellValue();
            HSSFCell cellC1 = row1.getCell(2);
            boolean c1Val = cellC1.getBooleanCellValue();
            HSSFCell cellD1 = row1.getCell(3);
            Date d1Val = cellD1.getDateCellValue();

            System.out.println("A1: " + a1Val);
            System.out.println("B1: " + b1Val);
            System.out.println("C1: " + c1Val);
            System.out.println("D1: " + d1Val);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

Output :

A1: Hello
B1: Goodbye
C1: true
D1: Wed Aug 17 14:58:31 IST 2011


Jar file used:

poi-3.6-20091214.jar






Tuesday 16 August 2011

How to show a generated PDF file with in the browser or outside the browser in windows?


You can suggest to the browser that it should show the PDF in a window rather than offering to download it via the Content-Disposition header:
response.addHeader("Content-Disposition", "inline");
The "inline" value suggests that the content be rendered inline (as opposed to the "attachment" value suggesting the browser offer to download it).
Once you've made the suggestion to the browser, the browser may or may not accept your suggestion, depending on its implementation and possibly its user preferences.Please see following lines of code :-



        String pdfFileName = "/pdf-test.pdf";
        String contextPath = getServletContext().getRealPath(File.separator);
        File pdfFile = new File(contextPath+"/"+pdfFileName);
         response.addHeader("Content-Disposition", "inline");
        response.setContentType("application/pdf");
        response.setContentLength((int) pdfFile.length());

        FileInputStream fileInputStream = new FileInputStream(pdfFile);
        OutputStream responseOutputStream = response.getOutputStream();
        int bytes;
        while ((bytes = fileInputStream.read()) != -1) {
            responseOutputStream.write(bytes);
        }

Saturday 6 August 2011

How to Generate XML in Java ?

See the following sample class:

GenerateXML.java

package opensourzesupport.xml

import java.io.PrintStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 *
 * @author Prasobh.K
 */
public class GenerateXML {

    public static void main(String[] args) {
        String documentToBeCreated = "myXMLDocument.xml";
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();


            // creating a new document
            Document myXMLDocument = builder.newDocument();

            //creating a root element
            Element rootElement = myXMLDocument.createElement("root");
            myXMLDocument.appendChild(rootElement);

            for (int i = 1; i <4; i++) {

                //creating a child root element
                Element childRootElement = myXMLDocument.createElement("childroot" + i);
                rootElement.appendChild(childRootElement);
                for (int j = 1; j < 10; j++) {
                    Element child = myXMLDocument.createElement("innerelement");
                    child.setTextContent("" + j);
                    childRootElement.appendChild(child);
                }

            }
            // The XML document we created above is still in memory
            // so we have to output it to a real file.
            // In order to do it we first have to create
            // an instance of DOMSource
            DOMSource source = new DOMSource(myXMLDocument);

            // PrintStream will be responsible for writing
            // the text data to the file
            PrintStream ps = new PrintStream(documentToBeCreated);
            StreamResult result = new StreamResult(ps);

            // Transformer instance, which we use to output the XML
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();

            // The actual output to a file goes here
            transformer.transform(source, result);
            System.out.println("Sucessfully created " + documentToBeCreated);
        } catch (Exception e) {
            System.out.println("Failed tro create xml" + e);
        }

    }
}


Output :

myXMLDocument.xml


<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
- <root>
- <childroot1>
  <innerelement>1</innerelement>
  <innerelement>2</innerelement>
  <innerelement>3</innerelement>
  <innerelement>4</innerelement>
  <innerelement>5</innerelement>
  <innerelement>6</innerelement>
  <innerelement>7</innerelement>
  <innerelement>8</innerelement>
  <innerelement>9</innerelement>
  </childroot1>
- <childroot2>
  <innerelement>1</innerelement>
  <innerelement>2</innerelement>
  <innerelement>3</innerelement>
  <innerelement>4</innerelement>
  <innerelement>5</innerelement>
  <innerelement>6</innerelement>
  <innerelement>7</innerelement>
  <innerelement>8</innerelement>
  <innerelement>9</innerelement>
  </childroot2>
- <childroot3>
  <innerelement>1</innerelement>
  <innerelement>2</innerelement>
  <innerelement>3</innerelement>
  <innerelement>4</innerelement>
  <innerelement>5</innerelement>
  <innerelement>6</innerelement>
  <innerelement>7</innerelement>
  <innerelement>8</innerelement>
  <innerelement>9</innerelement>
  </childroot3>
  </root>




Friday 5 August 2011

How to print a PDF Document in Java ?

For some time now I have searched for a way to print a PDF document from Java code. Up to now, I have had to shell out and invoke Acrobat from the command line but this hack has been painful to support in the field because of the multiple version of Acrobat and its quirks.
A new PDF Renderer project has recently been released on java.net which can in addition to rendering and viewing a PDF document, it can be used to print a PDF document. If you download the PDF Renderer you can run the jar to start a sample PDF viewer application which can print PDF documents. All the code listed below is inspired from the PDF Renderer sample application.

Use the following two classes :

 PDFPrinter.java

import com.sun.pdfview.PDFFile;
import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 *
 * @author Prasobh.K
 */
public class PDFPrinter {
    private String pdfFile= null;
    public PDFPrinter(String pdfFile){
        this.pdfFile = pdfFile;
    }
    public boolean doPrint(){
       boolean printSucessfull = true;
        try {
            File f = new File(pdfFile);
            FileInputStream fis = new FileInputStream(f);
            FileChannel fc = fis.getChannel();
            ByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
            PDFFile pdfFile = new PDFFile(bb); // Create PDF Print Page
            PDFPrintPage pages = new PDFPrintPage(pdfFile);

           // Create Print Job
            PrinterJob pjob = PrinterJob.getPrinterJob();
            PageFormat pf = PrinterJob.getPrinterJob().defaultPage();
            pjob.setJobName(f.getName());
            Book book = new Book();
            book.append(pages, pf, pdfFile.getNumPages());
            pjob.setPageable(book);

           // Send print job to default printer
            pjob.print();
        } catch (Exception e) {
            printSucessfull = false;
            System.out.println(e);
        }
       return printSucessfull;
    }
  
}

PDFPrintPage .java

import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;
import com.sun.pdfview.PDFRenderer;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;


/**
 *
 * @author Prasobh.K
 */
class PDFPrintPage implements Printable {
  private PDFFile file;
  PDFPrintPage(PDFFile file) {
    this.file = file;
  }

  public int print(Graphics g, PageFormat format, int index)
    throws PrinterException {
    int pagenum = index + 1;

    // don't bother if the page number is out of range.
    if ((pagenum >= 1) && (pagenum <= (file.getNumPages()))) {
      // fit the PDFPage into the printing area
      Graphics2D g2 = (Graphics2D)g;
      PDFPage page = file.getPage(pagenum);
      double pwidth = format.getImageableWidth();
      double pheight = format.getImageableHeight();

      double aspect = page.getAspectRatio();
      double paperaspect = pwidth / pheight;

      Rectangle imgbounds;

      if (aspect>paperaspect) {
        // paper is too tall / pdfpage is too wide
        int height= (int)(pwidth / aspect);
        imgbounds= new Rectangle(
          (int)format.getImageableX(),
          (int)(format.getImageableY() + ((pheight - height) / 2)),
          (int)pwidth,
          height
        );
      } else {
        // paper is too wide / pdfpage is too tall
        int width = (int)(pheight * aspect);
        imgbounds = new Rectangle(
          (int)(format.getImageableX() + ((pwidth - width) / 2)),
          (int)format.getImageableY(),
          width,
          (int)pheight
        );
      }

      // render the page
      PDFRenderer pgs = new PDFRenderer(page, g2, imgbounds, null, null);
      try {
        page.waitForFinish();
        pgs.run();
      } catch (InterruptedException ie) {}

      return PAGE_EXISTS;
    } else {
      return NO_SUCH_PAGE;
    }
  }
}


Jar file Used

PDFRenderer-0.9.0.jar
 















 

Thursday 4 August 2011

How to get the client information in a Servlet?

The hostname and IP Address of the client requesting the servlet can be obtained using the HttpRequest object. The following example shows how to get client ip address and hostname from a Servlet:
// This method is called by the servlet container to process a GET request.
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
 throws IOException {
    
        // Get client's IP address
        String ipAddress = req.getRemoteAddr(); // ip
    
        // Get client's hostname
        String hostname = req.getRemoteHost(); // hostname
    } 
A servlet can use getRemoteAddr() and getRemoteHost() to retrieve the client's IP Address and client's host name from a http requestion.
  • getRemoteAddr(): Returns the internet address of the client sending the request. When the client address is unknown, returns an empty string.
  • getRemoteHost(): Returns the host name of the client sending the request. If the name is unknown, returns an empty string. The fully qualified domain name (e.g. "xyzws.com") of the client that made the request. The IP address is returned if this cannot be determined.
If the client is using a proxy server, the real request to your servlets arrives from the proxy, and so you get the proxy's IP address.
Most proxy servers will send the request with an header like "x-forwarded-for", or something similar. That header will contain the 'real' IP address. Be aware that fortunately there are a lot of anonymous proxy servers and they do not pass any additional header (and sometimes they do not appear as proxy). For example,
// This method is called by the servlet container to process a GET request.
    public void doGet(HttpServletRequest req, HttpServletResponse resp) 
throws IOException {
    
        // Get client's IP address
        String ipAddress = req.getHeader("x-forwarded-for");
        if (ipAddress == null) {
            ipAddress = req.getHeader("X_FORWARDED_FOR");
            if (ipAddress == null){
                ipAddress = req.getRemoteAddr();
            }
        }     

    }