Monday, 5 December 2011

Specifying EntityManagementFactory in xml

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> 
        <property name="persistenceUnitName" value=my_persistanceunit"/> 
        <property name="dataSource" ref="dataSource"/> 
        <property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml"/> 
        <property name="loadTimeWeaver"> 
            <bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/> 
        </property> 
        <property name="jpaVendorAdapter"> 
            <bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">               
                <property name="showSql" value="true"/>  
                <property name="generateDdl" value="false"/> 
                <property name="database" value="ORACLE"/> 
            </bean> 
        </property> 
    </bean>

persistance.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
  <!-- <persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
             version="2.0">-->
  <persistence-unit name="my_persistanceunit" transaction-type="RESOURCE_LOCAL">
    <description>my oracle db Persistence Unit</description>
    <class>com.my.MyEntityClass</class>
    <properties>
  </persistence-unit>
</persistence>

Use -javaagent:.lib/spring-instrument-3.0.4.RELEASE.jar  as commandline argument

Wednesday, 23 November 2011

What is J2EE and how is it different from Java?

"Java" refers to both a language and a platform. The runtime and libraries that comprise the platform are based on the Java language and come in 3 flavors:
Java SE (Standard Edition): Formerly J2SE but renamed to Java Standard Edition when the Java 2 convention was dropped with the release of Java 5 (formerly J2SE 1.5). It contains a good all-around mix of general purpose libraries including JDBC (Java Database Connectivity), JNDI (Java Naming Directory Interface), RMI (Remove Method Invocation), AWT, and Swing.
Java EE (Enterprise Edition): Formerly J2EE (see above). It includes Java Standard Edition plus most of the other Java technologies including JavaMail, Activation, JAXB (Java API for XML Binding), Servlets, JSF (Java Server Faces), JMS (Java Messaging Service), EJB (Enterprise Java Beans), and others. Most of the APIs are very component-oriented and are intended to provide pluggable interfaces for business components to form robust, distributed internet applications.
Java ME (Micro Edition): Formerly J2ME. It includes most of Java SE and some additional APIs for handheld devices.
Java Enterprise Edition is based on Java, but includes a larger set of libraries than Java Standard Edition, which to most people is synonymous with the word "Java." Note that many of the technologies featured in Java Enterprise Edition are available separately and can be added to the Java Standard Edition platform as needed.

Sunday, 18 September 2011

JSP Life Cycle

Following diagram shows the different life cycle stages of jsp. Broadly, these stages can be classified into three.
  • Instantiation
  • Request Processing
  • Destruction






Instantiation:
When a web container receives a jsp request (may be first or subsequent), it checks for the jsp’s servlet instance. If no servlet instance is available or if it is older than the jsp, then, the web container creates the servlet instance using following stages.
  • Translation
  • Compilation
  • Loading
  • Instantiation
  • Initialization
Translation:
Web container translates (converts) the jsp code into a servlet code. This means that jsp is actually a servlet. After this stage, there is no jsp, everything is a servlet. This task will create a complete jsp page, by considering all included components. Here on, the static content and dynamic contents are treated differently. The resultant is a java class instead of an html page (which we wrote). This is how the structure of a jsp compiled into a java class will be.
package org.apache.jsp.WEB_002dINF.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class firstJsp_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {
  private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
  ............
  ............
  public Object getDependants() {
    return _jspx_dependants;
  }
  public void _jspInit() {
 ............
 ............
  }
  public void _jspDestroy() {
 ............
 ............
  }
  public void _jspService(HttpServletRequest request,
    HttpServletResponse response)
        throws java.io.IOException, ServletException {
 ............
 ............
  }
 ............
 ............
}
Compilation:
The generated servlet is compiled to validate the syntax. As it is a java class, the compilation is done using javac command. This will generate the byte code to be run on JVM.
Loading:
The compiled byte code is loaded by the class loader used by web container. This is a standard process of using any java class.
Instantiation:
In this step, instance of the servlet class is created so that it can serve the request.
Initialization:
Initialization is done by calling the jspInit() method. This is one time activity at the start of the initialization process. Initialization will make the ServletContext and ServletConfig objects available. One can access many attributes related to the web container and the servlet itself. After initialization the servlet is ready to process requests.
Request Processing:
Entire initialization process is done to make the servlet available in order to process the incoming request. jspService() is the method that actually processes the request. It prints the response in html (any other) format, using ‘out’ object.
Destroy:
Whenever the server is shutting down or when the server needs memory, the server removes the instance of the servlet. The destroy method jspDestroy() can be called by the server after initialization and before or after request processing. Once destroyed the jsp needs to be initialized again.
Just to summarize, web container handles incoming requests to a jsp by converting it into a servlet and then by using this servlet to generate the response. Also when the server shuts down, the container needs to clear the instances.
Controlling Life Cycle:
In above discussion, we understood that the jsp initialization phase happens when the first request hits the web container. This might take more time to present the response to the first user of jsp. It should be possible to keep initialized servlets ready to receive first request and immediately return response. This can be achieved by using the attributes provided by web and application server. The attribute can be “load-on-startup”, “pre compile” etc.

Elements of jsp are specified like an element in html or xml, i.e. with opening and closing tags. There are many types of elements in jsp. Here is the list of these elements.
  • Directives
  • Scriptlets
  • Actions
  • Expressions
  • Comments
  • Declarations
  • Template Text
These elements change the servlet generated by the container. Definitely these are used to change the behavior of dynamic contents of a jsp. Let us see each of these elements in detail:
Directives:
These affect the overall structure and behavior of a jsp.  There are three types of directives
  • Page: Usually specified at the beginning of page and affects the entire page. Examples are import, extends, session, info, isErrorPage, language, errorPage, autoFlush, contentType, buffer, isThreadSafe.
  • Syntax : <%@page attributename=”value”%>
e.g. <%@page  import=”java.lang.io”%>
  • Include: Include another file in this jsp. During translation phase of jsp, this file is included and complete jsp is prepared. This is a static include, the dynamic include is discussed later. In static include, the file is inserted in the jsp, while in dynamic include the request is forwarded to the included page to include execution response.
Syntax  : <%@include file=”filename”%>
e.g. <%@include file=”com.constants”%>
  • Taglib: This directive is used to make custom tag library use possible. In this directive, the prefix and uri are identified.
Syntax : <%taglib Uri=”path” prefix=”prefixToBeUsed”%> 
e.g. <%taglib Uri=”WEB-INF/mytaglib.tld” prefix=”mytaglib”%>
Scriptlets:
Scriptlets are the Java statements included in jsp. To differentiate these contents, the statements are included in <%…………%>. When the translation activity happens, these snippets are inserted in the jspService() method. As the service method is executed on each request, these snippets are also executed for each request. When you are using the jsp variables in these scriptlets, you need to keep this thing in mind that this code is executed at server side. Hence those variables needs to be available at the server side. Any mix up of client side variable in scriptlet will result in compilation problem or garbage value processing.
Actions:
Actions are taken when a request hits a jsp page. So, the actions are request processing instructions to the web/servlet container. Below are the jsp action examples with their use.
  • <jsp:include>: Dynamic inclusion of a page. The response of the included page is included in final response.
  • <jsp:forward>: Redirecting request to n different page. In include, the response is not committed, while here, the response is committed and a new request is sent.
  • <jsp:param>: Parameters to be passed inside include and forward tags to make available of the new jsp page through request object.
  • <jsp:useBean>: Integrating java beans with jsp page to transfer data through these beans and request objects.
  • <jsp:getProperty> and <jsp:setProperty>: Along with useBean, these are getter/setter methods of the attributes.
  • <jsp:plugin>: Browser will execute an applet or a bean based on this tag.
Expressions:
Evaluate the expression and send the value as a part of response to client. The expression inside this tag <%……%> is evaluated and just the result is sent back to the client as a string.
Comments:
Used to comment code in jsp. There are two options. First option tag used is <%– Comment –%>. This comment will be ignored by the web container and no code will be sent in response. That means comments are not transferred over network, and the amount of data sent over network is reduced. Second syntax is html comments <!-comment –>. Container treats it as an html and sends it to the client.
Declarations:
Using this, we can declare the class level variables, methods and classes. These declarations are initialized when the JSP is initialized. The scope of initialization is class level. Class level variable means the translation phase keeps these variables outside the service method at class level. Hence once set these attributes are available in each request to service method. The syntax used is -
<%! String name = “Jsp Tutorial”; %>
Template Text:
This is other than the jsp code. The fillers that are used sometimes to define the look and feel of the page presented. This code can be html, xml, wml or text.
<H1>ABC</H1>
To Summarize, above elements are to be used when we write a jsp page. There are different uses of each element. We need to use the correct element after understanding the response they will generate.

Implicit object are those objects which are available in jsp by default. Developer does not need to declare these objects, the web container creates them. What would be rational behind creation of such objects? Why would thecontainer create these objects? Can we not work without these objects? We will try to find answers to these questions in this article.
Web container executes the JSP page as a servlet. Servlet operates in request – response model. All objects, that are associated with any servlet by default, are part of this implicit object group. Each servlet has information related to the container’s environment, the servlet itself, the interaction session with user, definitely the request and response, etc. This information along with information related to the jsp page itself, is made available to the jsp via the implicit objects. The following is a list of jsp implicit objects:
  • request
  • response
  • pageContext
  • session
  • application
  • out
  • config
  • page
  • exception
Let us look at these objects in detail.
request:
  • Request object represents the request made by a client to the servlet.
  • This request is passed as an instance of javax.servlet.HttpServletRequest object.
  • This is an input parameter to the jspService() method.
  • Contains http header, request attributes, session etc.
response:
  • It represents the response generated by the servlet.
  • This is an instance of javax.servlet.HttpServletResponse class.
  • This is another input parameter to the jspService() method of the generated servlet.
pageContext:
  • Using this object, we can interact with the servlet container.
  • It is an instance of javax.servlet.jsp.PageContext class.
  • Container can manage page attributes like error pages, forwarding pages and including pages using this object.
session:
  • Represents the session between client and servlet (server).
  • Instance of HttpSession class.
  • Can be used to store attributes applicable to user session and not request.
application:
  • It is an instance of ServletContext class.
  • Used to share data amongst servlets, jsps and html pages in an application.
out:
  • This object is used to send output to the client.
  • It is an instance of javax.servlet.jsp.JspWriter class.
  • Based on the content type defined, the output will be generated.
  • Some of the methods available are print, println, flush, etc.
config:
  • This represents the servlet configuration.
  • It is an instance of javax.servlet.ServletConfig class.
page:
  • Represents the instance of generated servlet – “this”.
exception:
  • It is an instance of java.lang.Throwable class.
  • It encapsulates the exception thrown by the servlet.
  • If the jsp contains page directive for error page, then this exception is forwarded to that page.
To summarize, implicit objects are available in the jsp by default, and these objects can be used to serve a definite purpose which would otherwise be difficult.

A JSP works using http request – response model. Client browser sends a http request to the web container which is handled by the servlet from JSP. The request is executed by jspService() method and generated response is sent back. This transaction involves many data objects, which are used to encapsulate specific data. These objects may contain business data or environment data. It is important to define the extent of data sharing allowed by these objects. Defining scope of these object puts restriction on sharing of these objects in this request-response cycle. In addition to this, the request itself can be forwarded or redirected before generating final response. In this article, we will look as these request processing aspects. Following four main points are discussed in detail.
  • Scope
  • Include
  • Forward
  • Redirect
Scope:
Scope attribute defines the context in which any object will be available. Based on this availability information, we can use different objects. In a Jsp, there are following four scopes identified.
  • page: page maps to the jspService() method of generated servlet. Hence an object with page scope is available in service method only.
  • request: Request originates from a client browser and is executed in the jspService() method of generated servlet, to result in a response. Objects with this scope are available as long as the request object is available. These objects can be retrieved from the request object using getAttribute method.
  • session: This scope is larger than the request scope. Session scope lasts as long as the user session exists. Similar to request scope, these objects can also be retrieved using getAttribute method.
  • application: In this scope, the object is bound to ServletContext object. This scope is higher than the session scope and the object will get shared amongst different sessions of same user or sessions of different users. Here also ‘getAttribute’ method can be used to retrieve the object.
The scope goes on increasing in sequence from page, request, session to application.
Include:
Jsp components are included to increase reuse of code. We can include these components using either static include or using dynamic include. Static include is implemented using <%@include file=”filename”%> syntax. This include inserts the contents of included file in the jsp. Thus a new jsp is created after all inclusions. Requests are handled by the servlet generated from this new jsp. There is no other change in request-response model. Here the file can be html, jsp, image, etc.
Dynamic include is different from static include in many aspects. It is implemented using <jsp:include page=”filename”/> action element. While translating the jsp, container converts this include into a method call. During runtime, the method will be executed to render the page. This included page will have access to all implicit objects of the parent jsp. Only html and jsp pages can be included using this method.
Forward:
<jsp:forward page=”url”/> is used to forward request to another page. Target page will execute the request and send response to client. Attributes to be forwarded to target page can also be included in this tag.
Redirect:
In this scenario, the request will be redirected to a new resource. HttpServletResponse object’s sendRedirect() method is used to implement this. In redirect, the response of first request is returned to client browser and browser issues a new request all together.







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();
            }
        }     

    } 

Friday, 29 July 2011

Java Preprocessor

If you do a google search for java preprocessor you are likely to get a pretty sparse set of results. There are a few projects out there that provide tools to solve this problem but I needed something with the following characteristics:
  1. C preprocessor like syntax with configurable macro prefix
  2. solid Ant integration
    • properties defined in build script visible to preprocessor
    • only process source files newer than target file
  3. open source license
Finally got frustrated enough to just write my own. The end result is a tool called javapp.jar and it is licensed under the GNU GPL.
The core processor logic is implemented in Python and runs under the Java runtime using Jython. I used an excellent lexical analysis module called Plex by Greg Ewing.
Using Python has the distinct advantage of reducing development time (~ 6 hours), but sadly there is a rather significant performance hit. Processing a large project (~ 100 files) for the first time can take upwards of two minutes! Subsequent builds should be much quicker since the ant task will only process source files newer than the destination file.

Downloading

The latest version is javapp-04.zip.


Getting Started

Extract the zip file and put javapp.jar somewhere Ant can find it. A good permanent spot is $ANT_HOME/lib.
Define and run the task:
<taskdef resource="javapp-defs.xml" />
 
<property name="os_version" value="4.2" />
 
<target name="preprocess">
   <javapp destdir="staging" prefix="//#">
      <fileset dir="src" includes="**/*.java" />
      <property name="poo" value="smelly" />
   </javapp>
</target>
Turns this:
public class Poo {
   public static void main(String[] args) {
      //#if defined(poo)
      System.out.println("Poo is ${poo}");
      //#else
      System.out.println("Poo is not defined");
      //#endif
 
      //#if ${os_version} == 4.1
      System.out.println("OS 4.1");
      //#elif defined(poo) and ${os_version} >= 4.2
      System.out.println("OS 4.2 and above");
      System.out.println("Ooooh; compound expressions");
      //#endif
   }
}
Into this:
public class Poo {
   public static void main(String[] args) {
 
      System.out.println("Poo is smelly");
 
 
 
      System.out.println("OS 4.2 and above");
      System.out.println("Ooooh; compound expressions");
 
   }
}

Thursday, 21 July 2011

Reading and writing Serializable objects

See following example :


/**
 *
 * @author prasobh
 */
import java.io.*;
import java.util.*;

public class ExerciseSerializable {

    public static void main(String... aArguments) {
        //  create a Serializable Map
        Map<Integer, String> names = new HashMap<Integer, String>();
        names.put(1, "prasobh");
        names.put(2, "mohanlal");
        names.put(3, "mammokka");



        try {
            //  use buffering
            OutputStream file = new FileOutputStream("names.store");
            OutputStream buffer = new BufferedOutputStream(file);
            ObjectOutput output = new ObjectOutputStream(buffer);
            try {
                output.writeObject(names);
            } finally {
                output.close();
            }
        } catch (IOException ex) {
            System.out.println("Exception " + ex);
        }

        // deserialize the quarks.ser file


        try {
            //use buffering
            InputStream file = new FileInputStream("names.store");
            InputStream buffer = new BufferedInputStream(file);
            ObjectInput input = new ObjectInputStream(buffer);
            try {
                //deserialize the List

                Map<Integer, String> recoverednames = (Map<Integer, String>) input.readObject();

                //display its data

                System.out.println("recoverednames: " + recoverednames);

            } finally {
                input.close();
            }
        } catch (ClassNotFoundException ex) {
            System.out.println("Exception " + ex);
        } catch (IOException ex) {
            System.out.println("Exception " + ex);
        }
    }
}




Saturday, 9 July 2011

Gradient buttons for android

 

Blue button

<?xml version="1.0" encoding="utf-8"?>
    <item android:state_pressed="true" >
        <shape>
            <solid
                android:color="#449def" />
            <stroke
                android:width="1dp"
                android:color="#2f6699" />
            <corners
                android:radius="3dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
    <item>
        <shape>
            <gradient
                android:startColor="#449def"
                android:endColor="#2f6699"
                android:angle="270" />
            <stroke
                android:width="1dp"
                android:color="#2f6699" />
            <corners
                android:radius="4dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
</selector>
 

Red button

<?xml version="1.0" encoding="utf-8"?>
    <item android:state_pressed="true" >
        <shape>
            <solid
                android:color="#ef4444" />
            <stroke
                android:width="1dp"
                android:color="#992f2f" />
            <corners
                android:radius="3dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
    <item>
        <shape>
            <gradient
                android:startColor="#ef4444"
                android:endColor="#992f2f"
                android:angle="270" />
            <stroke
                android:width="1dp"
                android:color="#992f2f" />
            <corners
                android:radius="3dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
</selector>
 

Purple button

 

<?xml version="1.0" encoding="utf-8"?>
    <item android:state_pressed="true" >
        <shape>
            <solid
                android:color="#a276eb" />
            <stroke
                android:width="1dp"
                android:color="#6a3ab2" />
            <corners
                android:radius="3dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
    <item>
        <shape>
            <gradient
                android:startColor="#a276eb"
                android:endColor="#6a3ab2"
                android:angle="270" />
            <stroke
                android:width="1dp"
                android:color="#6a3ab2" />
            <corners
                android:radius="4dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
</selector>
 

Green button

<?xml version="1.0" encoding="utf-8"?>
    <item android:state_pressed="true" >
        <shape>
            <solid
                android:color="#70c656" />
            <stroke
                android:width="1dp"
                android:color="#53933f" />
            <corners
                android:radius="3dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
    <item>
        <shape>
            <gradient
                android:startColor="#70c656"
                android:endColor="#53933f"
                android:angle="270" />
            <stroke
                android:width="1dp"
                android:color="#53933f" />
            <corners
                android:radius="4dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
</selector>
 

Yellowbutton

<?xml version="1.0" encoding="utf-8"?>
    <item android:state_pressed="true" >
        <shape>
            <solid
                android:color="#f3ae1b" />
            <stroke
                android:width="1dp"
                android:color="#bb6008" />
            <corners
                android:radius="3dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
    <item>
        <shape>
            <gradient
                android:startColor="#f3ae1b"
                android:endColor="#bb6008"
                android:angle="270" />
            <stroke
                android:width="1dp"
                android:color="#bb6008" />
            <corners
                android:radius="4dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
</selector>
 

Blackbutton

<?xml version="1.0" encoding="utf-8"?>
    <item android:state_pressed="true" >
        <shape>
            <solid
                android:color="#343434" />
            <stroke
                android:width="1dp"
                android:color="#171717" />
            <corners
                android:radius="3dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
    <item>
        <shape>
            <gradient
                android:startColor="#343434"
                android:endColor="#171717"
                android:angle="270" />
            <stroke
                android:width="1dp"
                android:color="#171717" />
            <corners
                android:radius="4dp" />
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
</selector>
 
All text on the buttons will have the same styles we can define a style in strings.xml:

<style name="ButtonText">
    <item name="android:layout_width">fill_parent</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:textColor">#ffffff</item>
    <item name="android:gravity">center</item>
    <item name="android:layout_margin">3dp</item>
    <item name="android:textSize">30dp</item>
    <item name="android:textStyle">bold</item>
    <item name="android:shadowColor">#000000</item>
    <item name="android:shadowDx">1</item>
    <item name="android:shadowDy">1</item>
    <item name="android:shadowRadius">2</item>
</style>
 
Source code of an activity layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"
    android:orientation="vertical">
   <Button android:text="Button" android:id="@+id/button1" android:background="@drawable/btn_red" style="@style/ButtonText"></Button>
   <Button android:text="Button" android:id="@+id/button2" android:background="@drawable/btn_blue" style="@style/ButtonText"></Button>
   <Button android:text="Button" android:id="@+id/button3" android:background="@drawable/btn_purple" style="@style/ButtonText"></Button>
   <Button android:text="Button" android:id="@+id/button4" android:background="@drawable/btn_green" style="@style/ButtonText"></Button>
   <Button android:text="Button" android:id="@+id/button5" android:background="@drawable/btn_orange" style="@style/ButtonText"></Button>
   <Button android:text="Button" android:id="@+id/button6" android:background="@drawable/btn_black" style="@style/ButtonText"></Button>
</LinearLayout>