Error Scaffolding View Resolver - Grails

Today, while building a sample Grails application using the scaffolding approach, I encountered a new type of error, when running my Grails application. I had four domain classes and created a controller for each one of them. After the modelling of domain classes were complete, I added the following line of code inside my controller file to follow the scaffolding approach.
def scaffold = true
After this was done, when I executed the following command
grails run-app
I got the following exception on the screen;
C:\mygrails\demoapp>grails run-app
Welcome to Grails 1.3.7 - http://grails.org/
Licensed under Apache Standard License 2.0
Grails home is set to: C:\mygrails\grails

Base Directory: C:\mygrails\demoapp
Resolving dependencies...
Dependencies resolved in 989ms.
Running script C:\mygrails\grails\scripts\RunApp.groovy
Environment set to development
  [groovyc] Compiling 5 source files to C:\mygrails\demoapp\target\classes
mcat
Running Grails application..
Server running. Browse to http://localhost:8080/demoapp

2011-06-27 13:41:29,282 [http-8080-2] ERROR view.ScaffoldingViewResolver  - Error generating scaffolded view [/postDetails/index]: C:\mygrails\grails\src\grails\templates\scaffolding\index.gsp (The system cannot find the file specified)
java.io.FileNotFoundException: C:\mygrails\grails\src\grails\templates\scaffolding\index.gsp (The system cannot find the file specified)
        at java.io.FileInputStream.open(Native Method)
        at java.io.FileInputStream.(FileInputStream.java:120)
        at java.lang.Thread.run(Thread.java:662)
2011-06-27 13:41:34,669 [http-8080-2] ERROR view.ScaffoldingViewResolver  - Error generating scaffolded view [/postDetails/index]: C:\mygrails\grails\src\grails\templates\scaffolding\index.gsp (The system cannot find the file specified)
java.io.FileNotFoundException: C:\mygrails\grails\src\grails\templates\scaffolding\index.gsp (The system cannot find the file specified)
        at java.io.FileInputStream.open(Native Method)
        at java.io.FileInputStream.(FileInputStream.java:120)
        at java.lang.Thread.run(Thread.java:662)
2011-06-27 13:41:37,797 [http-8080-2] ERROR view.ScaffoldingViewResolver  - Error generating scaffolded view [/profileDetails/index]: C:\mygrails\grails\src\grails\templates\scaffolding\index.gsp (The system cannot find the file specified)
java.io.FileNotFoundException: C:\mygrails\grails\src\grails\templates\scaffolding\index.gsp (The system cannot find the file specified)
        at java.io.FileInputStream.open(Native Method)
        at java.io.FileInputStream.(FileInputStream.java:120)
        at java.lang.Thread.run(Thread.java:662)
After searching on this error in Google across multiple posts, I found that the cause of the error was the presence of the following additional line in each of my controller files
def index = { }
I removed this line from all the controller files and then retried running the demo grails application and it worked like a charm. If you have a similar ScaffoldingViewResolver issue for your Grails application, you can try this option out to see if it works for you.

Connect Grails with Oracle 11g Example Configuration

I developed a tiny web application in Grails that used HSQLDB by default and was wondering if it is possible to change the database to my Oracle 11g database. That would be neat and I can build more on Grails and at the same time use some of the powerful features offered by Oracle. It is very easy and straightforward to set up Grails to work with Oracle. However, you may encounter some exceptions during the configuration process and in this post I will explain how to setup Grails to work with your Oracle 11g database. Before we proceed any further, let me state the version of Grails and Oracle that I used for this tutorial.
Grails - 1.3.7
Oracle - 11.2.0.1.0
Java - 1.6

Follow the step by step guide provided below to setup any sample application developed on Grails to work with a Oracle Database;

Step-1: Inside your project folder, navigate to grails-app\conf and then edit the file DataSource.groovy in your favourite editor.This is what I initially changed for "datasource" and "development" sections.
dataSource {
    pooled = true
    driverClassName = "oracle.jdbc.driver.OracleDriver"
    username = "Enter User Name Here"
    password = "Enter Password Here"
}
development {
        dataSource {
            dbCreate = "update" // one of 'create', 'create-drop','update'
            url = "jdbc:oracle:thin:@ServerName:Port:SID"
        }
    }
Make sure you change the Server Name, Port and SID to suit to your needs.

Step-2: I tried "grails run-app" after doing this piece and I was greeted with the following exception.
Caused by: org.springframework.beans.factory.BeanCreationException: Error creati
ng bean with name 'transactionManager': Cannot resolve reference to bean 'sessio
nFactory' while setting bean property 'sessionFactory'; nested exception is org.
springframework.beans.factory.BeanCreationException: Error creating bean with na
me 'sessionFactory': Cannot resolve reference to bean 'hibernateProperties' whil
e setting bean property 'hibernateProperties'; nested exception is org.springfra
mework.beans.factory.BeanCreationException: Error creating bean with name 'hiber
nateProperties': Cannot resolve reference to bean 'dialectDetector' while settin
g bean property 'properties' with key [hibernate.dialect]; nested exception is o
rg.springframework.beans.factory.BeanCreationException: Error creating bean with
 name 'dialectDetector': Invocation of init method failed; nested exception is o
rg.springframework.jdbc.support.MetaDataAccessException: Error while extracting
DatabaseMetaData; nested exception is org.apache.commons.dbcp.SQLNestedException
: Cannot load JDBC driver class 'oracle.jdbc.driver.OracleDriver'
        ... 23 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creati
ng bean with name 'sessionFactory': Cannot resolve reference to bean 'hibernateP
roperties' while setting bean property 'hibernateProperties'; nested exception i
s org.springframework.beans.factory.BeanCreationException: Error creating bean w
ith name 'hibernateProperties': Cannot resolve reference to bean 'dialectDetecto
r' while setting bean property 'properties' with key [hibernate.dialect]; nested
 exception is org.springframework.beans.factory.BeanCreationException: Error cre
ating bean with name 'dialectDetector': Invocation of init method failed; nested
 exception is org.springframework.jdbc.support.MetaDataAccessException: Error wh
ile extracting DatabaseMetaData; nested exception is org.apache.commons.dbcp.SQL
NestedException: Cannot load JDBC driver class 'oracle.jdbc.driver.OracleDriver
To fix this problem ,I went to the following Oracle website link to pick the JAR file that will be required by the application. The file that I downloaded for my version of Java is ojdbc6.jar. After copying this file to the lib folder of the application, I tried starting the application again, and this time I got a different exception
Invocation of init method failed; nested exception is o
rg.codehaus.groovy.grails.orm.hibernate.exceptions.CouldNotDetermineHibernateDia
lectException: Could not determine Hibernate dialect for database name [Oracle]!
Step-3: To fix the Hibernate dialect exception, I added the following line under dataSource in my DataSource.groovy file.
dialect = "org.hibernate.dialect.Oracle10gDialect"
And that is all you have to do to connect Grails and Oracle. When you start the Grails application following this correction, it will be able to connect to Oracle automatically and start performing the basic CRUD operations (depending on your code). If you still get an exception after completing this part, post it to us with your Grails, Java and Oracle DB version. We will have a look.

NetBeans Create JUnit Test Suite Example Guide

You may be here because you are new to Netbeans and would like to know how to run Junit test cases in Netbeans as a test Suite. Often, it would be nice to group your JUnit test cases into a test Suite so that they can all be executed in one go, instead of triggering them one after another. To do this, you will have to create a Suite that points to the test cases (class files) that needs to be executed, and if you are using Netbeans, here is a step by step guide to define a test Suite in Netbeans to run your JUnit test cases. I have a Java project which contains two JUnit test class files for testing same methods, but they use different type of runners to run the test execution. To define a test Suite that combines both these class files into a suite, I followed the instructions as shown below in Netbeans;
1) Right Click your Project Name -> Select New -> Click on Other. When you do this, you will get a screen as shown below;
Create a JUnit Test Suite in Netbeans
Creating a JUnit Test Suite Using Netbeans
2) Make sure you select Junit and then select "Test Suite" under file types. Once you do this, you have to click on the Next button in the screen.

3) Under "Name and Location", enter "JUnitTestSuite" as your Class Name. Under "Generated Code" uncheck Test initializer and Test Finalizer Checkboxes and hit the Finish button on the page.

4) Netbeans will automatically create a test suite class file. A sample of the Suite file is shown below (this may differ for you depending on your test input files)
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)
@Suite.SuiteClasses({AdditionTestParametrized.class, AdditionTest.class})
public class JUnitTestSuite {

    @BeforeClass
    public static void setUpClass() throws Exception {
    }

    @AfterClass
    public static void tearDownClass() throws Exception {
    }
    
}
You may wish to change "@Suite.SuiteClasses" to include only specific files in your test suite. In my case, I had two JUnit test class files and Netbeans included both of them in the Suite file. Once you do this, you can run the Suite file which will automatically run the individual test unit files.

JUnit Parameterized Test Example Tutorial

In this blog post, we will provide a simple example that will explain how to create a Parameterized test in JUnit with code examples. We will take an example of a addition, where a method adds two integers and returns an integer as an output. We will also discuss how to write test cases automatically for this method in JUnit by using the Parameterized.class. For those who are new to Parametrization, it is a runner inside JUnit that will run the same test case with different set of inputs.To get started with parametrized testing in JUnit, we have to have a Java class with a method that adds two numbers and returns an integer back to the calling method. My class file is "Addition.java" and the code for the file is provided below;
public class Addition {
    public int AddNumbers(int a, int b){
        int c = a + b;
        return c; 
    }
}
You can refer to the JUnit test case file for this example, after you have created and compiled this file. The test case class file will be called AdditionTestParametrized.java and the code for this file is provided below;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(Parameterized.class)
public class AdditionTestParametrized {

    private int expected; 
    private int firstNumber; 
    private int secondNumber; 

    @Parameters 
    public static Collection<Integer[]> getTestParameters() {
       return Arrays.asList(new Integer[][] {
          {2, 1, 1},  
          {3, 2, 1},  
          {4, 3, 1},  
       });
    }

    public AdditionTestParametrized(int expected, 
       int firstNumber, int secondNumber) {
       this.expected = expected;
       this.firstNumber = firstNumber;
       this.secondNumber = secondNumber;
    }

    @Test
    public void sum() {
       Addition instance = new Addition();     
       System.out.println("About to execute a test case with inputs " + firstNumber + " and " + secondNumber);
       assertEquals("Failed Test Case",expected, instance.AddNumbers(firstNumber, secondNumber));
    } 
}

Now, if you run the JUnit test against the test class, you will find that it gets executed thrice based on the inputs and the results are returned back to you on the screen. To run a test class with Parameterized test runner, you have to make sure that the following points are met;
1) You have to include a @RunWith annotation with the Parametrized class as its argument. (Refer to the code example above)
2) You have to provide a method annotated with @Parameters. This method will supply the input values for the test to be executed.
3) You must provide a method with @Test annotation, that will be invoked by JUnit for testing.
Try giving a run on this example and let us know if you are stuck somewhere.

Selenium CSS Selector Wildcard Example - Part 2

In the previous post, we showed how to match an ID value by using wild cards in Selenium. In this post, we will provide some more methods that are available in Selenium to match tags with a specific pattern. On the same lines as of starts with type of matching, it is possible to match tags with a ends with a specific suffix or contains a specific pattern in its attribute value. Note that the operator used to match a specific prefix in CSS selector is ^. To find pattern matching a suffix or in the entire string, we have to use different operators as shown in the example below;

1) To match a tag that ends with a specific pattern (suffix)
We use the operator "$=" for this purpose. As an example, to match all 'INPUT' type tags that has an ID ending with '_selector', write the CSS selector code as shown below;
css=input[id$='_selector']

2) To match a tag that contains a specific pattern (in the entire value)
We use the wildcard '*=' for  this case. As an example, to match all 'INPUT' type tags that has an ID containing the word 'selector', write the CSS selector code as shown below;
css=input[id*='selector']

Just to recollect, if you want to match all tags with a prefix of 'selector_' you have to write your CSS Selector as shown below;
css=input[id^='selector_']

Selenium CSS Selector Wildcard Example

Yesterday, when trying to get a dynamic count of number of fields for a Ruby on Rails application, I stumbled across a scenario where I had to match the ID value for a HTML tag by using a wildcard pattern. The requirement was to get a count of number of ID tags matching a specific pattern and then update the last of that tag with a user provided value. I tried several examples using CSS selectors, and finally found out how to use wildcard for CSS selectors inside Selenium. I'm posting a Java code snippet of my selector code, that I passed to the getCssCount method of com.thoughtworks.selenium.DefaultSelenium class. 
int tagcount=selenium.getCssCount("css=input[id^='post_tags_attributes'][type='text']").intValue();
This code looks for "INPUT" tags with ID starting with post_tags_attributes and has a "type" attribute matching a value of "text". The operator '^' is a wild card that helps to mimic a "begins with" search on the ID attribute.

PNG to PDF Java Servlet Example - iText Tutorial

In this tutorial, we will extend our JPG to PDF conversion servlet code, to support PNG to PDF conversion. The servlet will accept a user uploaded PNG image document and convert this to PDF and stream it back to the user in the browser.This tutorial refers to a standalone PNG to PDF conversion example provided in our blog earlier. It is advised to refer to the tutorial before proceeding with the servlet example.This example provides only the code that needs to be modified from the initial servlet example. There are two components to this example;

1) Modifying the index.jsp file to support an option that enables the PNG to PDF change.
2) Writing code at the server end to write the PDF file to document and send it back to the browser.

The code snippets for each of these cases is provided below. You will have to append this code with the original example to get the conversion going. If you are stuck at any point, you can post it as a comment and we will be happy to fix it for you.The modification that needs to be done in index.jsp file is provided below;
  <select name="convertTo" id="convertTo" onChange="javascript:enableField()">
      <option>Tiff2Pdf</option>
      <option>Jpeg2Pdf</option>
      <option>Gif2Pdf</option> <!-- New Option to Capture Gif2Pdf conversion -->
      <option>Bmp2Pdf</option> <!-- Option to support BMP to PDF conversion -->
      <option>Png2Pdf</option> <!-- Option to convert PNG to PDF -->
  </select><br></br>
With this option included, the user will get a drop down option to select the conversion type we are after. This needs to be supported with some code in our servlet; the snippet that needs to be added to the existing code is provided below;
            //Check if PNG to PDF is opted as selection
            // PNG 2 PDF servlet example
            if (conversionType.equals("Png2Pdf")){
               Image tempImage=PngImage.getImage(FilePath);                     
               document.add(tempImage);
            }
Make sure that you include the following import declaration to the existing code; otherwise the conversion would not work (you will neither be able to compile and deploy your servlet code )
import com.itextpdf.text.pdf.codec.PngImage;
Search our site on how to deploy to Tomcat, if you need to know how to deploy a WAR file in Tomcat web server. Post a comment for any other question, on this servlet code.

org.codehaus.groovy.grails.cli.support.GrailsStarter - SpringSource

While trying to set up Spring Source to develop a Groovy on Grails application a developer may encounter a Java exception as shown below;
java.lang.NoClassDefFoundError: org/codehaus/groovy/tools/RootLoader
Caused by: java.lang.ClassNotFoundException: org.codehaus.groovy.tools.RootLoader
 at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
 at java.security.AccessController.doPrivileged(Native Method)
 at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
 at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Exception in thread "main
Additionally on the Spring Source IDE, following error messages can also be visible;
---------------------------
Java Virtual Machine Launcher
---------------------------
Could not find the main class: org.codehaus.groovy.grails.cli.support.GrailsStarter.  Program will exit.
---------------------------
In this blog post, we will aim to provide a solution to such a problem and what you need to do to fix and get your grails application running in such cases.This problem often arises due to a compatibility issue between the version of Grails installed and the Spring Source version that is installed in your system.The first step you have to do is to read the documentation of Spring Source to make sure that the version of Grails you are using is certified for the IDE version. This could be the reason for this problem, and in this case you will want to install the right version of Grails that is supported by the IDE to get things working. I was running version 2.6.1 SR1, and Grails 1.4 was not accepted by the IDE. Downgrading to 1.3x version of Grails, helped to resolve this problem.

Convert PNG to PDF iText Java Example Tutorial

In this code example, we will provide a standalone Java class which will convert a PNG image to a PDF document, by using the iText Java API. This example is on the same lines as our BMP to PDF Conversion tutorial. The difference lies in the class used to read the input PNG image file. We will use the class com.itextpdf.text.pdf.codec.PngImage to accept a PNG image and return an object of type com.itextpdf.text.Image, so that we can add it to the PDF document directly. Note that this example requires a basic understanding of iText, and if you are new to iText, then I would suggest using the search functionality on this blog to find some beginners tutorials on iText. As such the code to convert PNG to PDF is very straightforward, and you can follow it quite easily, if you know some Java basics. The commented version of the Java code for this example is provided below;
//FileOutputStream holds the Physical PDF file
import java.io.FileOutputStream;
//The image class which will hold the PNG image as an object
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.Document;
//This class is required to read PNG image into Image object
import com.itextpdf.text.pdf.codec.PngImage;
public class PngToPDF {
public static void main(String[] args) {
try{
    //Create Document Object
    Document convertPngToPdf=new Document();
    //Create PdfWriter for Document to hold physical file
    //Change the PDF file path to suit to your needs
    PdfWriter.getInstance(convertPngToPdf, new FileOutputStream("c:\\java\\ConvertImagetoPDF.pdf"));
    convertPngToPdf.open();
    //Get the PNG image to Convert to PDF
    //getImage of PngImage class is a static method
    //Edit the file location to suit to your needs
    Image convertBmp=PngImage.getImage("c:\\java\\test.png");
    //Add image to Document
    convertPngToPdf.add(convertBmp);
    //Close Document
    convertPngToPdf.close();
    System.out.println("Converted and stamped PNG Image in a PDF Document Using iText and Java");
}
catch (Exception i1){
    i1.printStackTrace();
}
}
}
This example accepts a test image file and converts it to PDF. You may wish to use the methods inside the Image object to resize the image and fit to your needs. If you have a image resize / compression specific question on this example, you can post it as a comment in this blog. We will get back with a suitable working example based answer for your question. In the next blog post, we will update our generic image conversion servlet,to accept a user uploaded PNG image and render a PDF back to the browser.
Stay connected with Thinktibits through Facebook and Twitter (look to your left) and never miss a tutorial.

BMP to PDF Java Servlet Example - iText Tutorial

In this tutorial, we will extend the servlet code provided in the Gif to Pdf servlet tutorial, to support BMP to PDF conversion using iText library. The input to the servlet will be through a HTML form, where a user uploads a BMP file and the servlet will take care of converting the BMP image into a PDF document and stream it back to the browser. With this, the servlet code will be capable of handling the following conversions:
TIFF to PDF conversion
JPEG to PDF conversion
GIF to PDF conversion (all frames or first frame)
BMP to PDF conversion
We are slowly building an integrated image conversion servlet using iText, capable of handling any image extension type and stamp it to PDF. That is a bit far away, so we will keep ourselves satisfied with bitmap conversion now.I would recommend the readers to go through the base servlet code linked earlier, to get a feel of how the code is structured, if you are jumping right from the internet to this post. This post will focus on bitmap conversion alone. Code example to extend our servlet to support this change is provided below;

Step-1: Update your index.jsp file and add an option in the form drop down conversion type to support bmp to pdf. The code area to be modified is provided below;
  <select name="convertTo" id="convertTo" onChange="javascript:enableField()">
      <option>Tiff2Pdf</option>
      <option>Jpeg2Pdf</option>
      <option>Gif2Pdf</option> <!-- New Option to Capture Gif2Pdf conversion -->
      <option>Bmp2Pdf</option> <!-- Option to support BMP to PDF conversion -->
  </select><br></br>
Step-2: The change made in Step-2 will help to provide the servlet code an instruction to change the BMP image to PDF and render it back to the user. This option needs to be supported by an equivalent server side code which will render the PDF back to the user. The code snippet to be added in the servlet is provided below;
            //Check if the User has opted for Bmp2Pdf at the page
            //Bmp 2 PDF servlet example
            if (conversionType.equals("Bmp2Pdf")){
               Image tempImage=BmpImage.getImage(FilePath);                     
               document.add(tempImage);
            }
Now, before running this code, you will have to add the following import declaration as this is required for the conversion to work properly.
import com.itextpdf.text.pdf.codec.BmpImage;
A screendump of the FORM page from where the user uploads a BMP image is shown below;
BMP to PDF Conversion
BMP to PDF Conversion
The complete servlet image conversion code would be provided after we address all image formats. In the meantime, you can use the example link provide above and insert this code snippet to achieve BMP conversion.

Convert BMP to PDF iText Java Example Tutorial

In this iText image conversion tutorial, we will explain how to convert a bitmap (BMP) image file into a PDF document using iText Java API. This example would be driven with a standalone Java program, later we will provide a servlet integration example where a user uploaded bitmap picture would be changed to a PDF using a Java servlet.I will be using iText 5.1.0 for this example, if you are planning to use a older version of iText, make sure you modify the import declarations accordingly. We will be making use of the following class in iText API to read a BMP image into "Image" class : com.itextpdf.text.pdf.codec.BmpImage. The complete Java code example is provided below;
//We need the library below to write the final PDF file which has our image converted to PDF
import java.io.FileOutputStream;
//The image class which will hold the bitmap image
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.Document;
//This class is required to read image into Image object
import com.itextpdf.text.pdf.codec.BmpImage;
public class BmpToPDF {
public static void main(String[] args) {
try{
    //Create Document Object
    Document convertBmpToPdf=new Document();
    //Create PdfWriter for Document to hold physical file
    PdfWriter.getInstance(convertBmpToPdf, new FileOutputStream("c:\\java\\ConvertImagetoPDF.pdf"));
    convertBmpToPdf.open();
    //Get the Bitmap image to Convert to PDF
    //getImage is a static method, does not require object
    Image convertBmp=BmpImage.getImage("c:\\java\\test.bmp");
    //Add image to Document
    convertBmpToPdf.add(convertBmp);
    //Close Document
    convertBmpToPdf.close();
    System.out.println("Successfully Converted BMP to PDF in iText");
}
catch (Exception i1){
    i1.printStackTrace();
}
}
}
Now, for testing purposes, I had a 65 Kb Bitmap image file and it got converted to a PDF.The size of the PDF came around 3 Kb, which is a significant reduction in file size as well. I feel that Bitmap image is either converted / compressed before stamping it into the PDF. We will see more servlet based examples of image conversion using iText in upcoming posts.

Gem RemoteFetcher Fetch Error ECONNREFUSED Solution

Well, you could be here because you tried installing a gem, when you are behind a proxy, either at home or at office and you got a nice error when trying to install as shown below; (I got this while installing Rails for JRuby, but you can get this error for any other gem)
C:\jruby-1.6.2\samples>jruby -S gem install -y rails
INFO:  `gem install -y` is now default and will be removed
INFO:  use --ignore-dependencies to install only the gems you list
ERROR:  Could not find a valid gem 'rails' (>= 0) in any repository
ERROR:  While executing gem ... (Gem::RemoteFetcher::FetchError)
    Errno::ECONNREFUSED: Connection refused - Connection refused (http://rubygem
s.org/latest_specs.4.8.gz)
Now, you know the error is because,while installing the gem, the application is not able to get to the network as it does not know how to route itself, when you are behind a proxy. Follow the instructions as shown below, to fix this problem and get going with your installation

In Windows, you have to use the set command to set the value of "http_proxy" variable. If your proxy does not require an authentication, you can set the value by following a sample below;
set http_proxy=http://{hostname}:{portnumber}/
If your proxy require an authentication, then you can specify the user name and password in the same command as shown below;
set http_proxy=http://{username}:{password}@{hostname}:{portnumber}/
example:
set http_proxy=http://username:password@hostname:portnumber/

For other environments, you would want to use "export" instead of "set". Once you do this, you can try installing gems and it should work. (I got it working). Still having an issue? Post it and we will have a look.

GIF to PDF Java Servlet Example - iText Tutorial

In this post, we will explain how to convert a GIF image, uploaded from a JSP page, to a PDF document using the servlet example during our JPEG to PDF conversion. The User uploaded GIF file will be processed by a Java servlet and the servlet will stream the PDF file back to the user. I would strongly recommend to go through the JPEG to PDF conversion tutorial as the basic servlet code is taken out of that tutorial. The Java code used in that tutorial is extended to support a GIF to PDF conversion. Additionally, in the HTML page we also get an option from the user to convert all the frames in the GIF to PDF or convert the first frame to PDF. The code example has two components; the JSP page that accepts a user uploaded image, and the servlet code. The commented version of the code is provided below;
You will need iText library and com.oreilly.servlet package for this example to work.
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Convert Uploaded Image into PDF</title>
    </head>
    <script language="javascript">
    //This function will enable capture of GIF conversion type
    //ALL frames or first frame to PDF file
    function enableField()
    {        
    if(document.getElementById("convertTo").value=='Gif2Pdf'){
    document.uploadImage.frames.disabled=false;}
    else {document.uploadImage.frames.disabled=true;}
    } 
    </script>
    <body>
  <h1>Upload a Tiff/JPEG/GIF Image which will be Converted to PDF File</h1>        
  <form action="Tiff2Pdf" method="post" enctype="multipart/form-data" name="uploadImage" id="uploadImage">  
  <input type="file" name="file" id="file">
  <select name="convertTo" id="convertTo" onChange="javascript:enableField()">
      <option>Tiff2Pdf</option>
      <option>Jpeg2Pdf</option>
      <option>Gif2Pdf</option> <!-- New Option to Capture Gif2Pdf conversion -->
  </select><br></br>
  <!-- Get User Option on Frame conversion -->
  Select Frames to Convert (GIF files only):
  <select disabled="true" name="frames" id="frames">
      <option>ALL</Option>
      <option>1</option>
  </select>  
  <input type="submit" name="Submit" value="Submit">
  </form>
    </body>
</html>
This code runs a Javascript on selecting Gif2Pdf option to enable the capture of frame specific information. A screenshot of this JSP page is provided below;
GIF to PDF Conversion Servlet
GIF to PDF Conversion Servlet
Now, you will have to grab the initial servlet code from JPEG to PDF conversion tutorial, and add the following code to achieve a GIF to PDF conversion through a servlet. Once you have grabbed the code, add the following code into the existing servlet code to convert your GIF to PDF.
            //Check if the User has opted for Gif2Pdf at the page
            if (conversionType.equals("Gif2Pdf")){
                //We need to understand the type of conversion required
                //All frames or just the image
                String frameType=myrequest.getParameter("frames");
                if (frameType.equals("ALL")){
                  // A frame by Frame conversion is required  
                  GifImage myGif=new GifImage(FilePath);  
                  for(int i=1;i<=myGif.getFrameCount();i++){
                      document.add(myGif.getImage(i));
                  }
                }
                if (frameType.equals("1")){
                  // A complete image conversion is required  
                  Image gifImage=Image.getInstance(FilePath);               
                  document.add(gifImage);  
                }                       
            }
And don't forget to add the following additional import declaration
import com.itextpdf.text.pdf.codec.GifImage;
If you have put the code correctly, give it a go on your favourite web server and see if your GIF got converted to PDF. Not working? Post a comment with your problem and we will resolve it.

Animated Gif to PDF Conversion - Java iText Tutorial

In the previous post, we tried converting an Animated GIF image into a PDF. The GIF image had two frames and iText was able to grab two frames as separate image objects and push them inside a PDF file. However, at the output we noticed that the GIF image's second frame was totally redundant as it contained only the changed portion due to GIF optimization. In such a case, you would only want to convert one frame of the image into PDF, which would be a safe call, given that PDF cannot handle animated GIF files directly. In this post, we will try the same code example by directly accepting the Image into Image class rather than passing it through the GifImage class of iText.
import java.io.FileOutputStream;
//Image class to extract frames from GIF image
import com.itextpdf.text.Image;
//PdfWriter object to write the PDF document
import com.itextpdf.text.pdf.PdfWriter;
//Document object to add logical image frames to PDF
import com.itextpdf.text.Document;
//we need the class below to read input GIF file
import com.itextpdf.text.pdf.codec.GifImage;
public class animatdGifToPDF {
public static void main(String[] args) {
try{
    //Create Document Object
    Document convertGif2Pdf=new Document();
    //Create PdfWriter for Document to hold physical file
    PdfWriter.getInstance(convertGif2Pdf, new FileOutputStream("c:\\myjava\\ConvertImagetoPDF.pdf"));
    convertGif2Pdf.open();
    //Class GifImage is redundant.    
    GifImage myGif=new GifImage("c:\\myjava\\test.gif");
    //Get the number of frames in Gif Image
    System.out.println("Number of Frames to be converted" + myGif.getFrameCount());
    //You may wish to have a If condition here
    //to use the code below if the number of frames is more than 1
    //signifying that this is a animated GIF image
    Image myimage=Image.getInstance("c:\\myjava\\test.gif");
    convertGif2Pdf.add(myimage);
    convertGif2Pdf.close();
    System.out.println("Successfully Converted Animated GIF Frame to PDF in iText");
}
catch (Exception i1){
    i1.printStackTrace();
}
}
}
Now, this code converts only the first frame of the GIF (which is usually the full image) to the PDF, which could be a desired operation when you are dealing with multiple frames in a GIF file. In the next post, we will see how to expand our servlet code, which currently handles Jpeg to PDF, Tiff to PDF conversions, to include Gif to PDF conversion. The servlet will stream a PDF file back to the user when the user uploads a GIF image. For GIF alone, we will provide an option to convert all frames or just the file alone. Keep watching this space for more.