Sunday 7 December 2014

Installing jdk 1.5 on ubantu



                                   Installing jdk 1.5 on ubantu


Here uou can keep multiple versions of Java (JRE and JDK) at a time and choose between them which one to use.
on the below link download your version of Java.

http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-javase5-419410.html

I have download the following file;

Java Development Kit 5.0 Update 22  42.14 MB    jdk-1_5_0_22-linux-amd64.bin

Go to the termial and go the the path where you downloaded the file.

type the following command;

sudo mv jdk-1_5_0_22-linux-amd64.bin /usr/lib/jvm
cd /usr/lib/jvm
chmod +x jdk-1_5_0_22-linux-amd64.bin
sudo ./jdk-1_5_0_22-linux-amd64.bin

sudo update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/jdk1.5.0_22/bin/java" 2

sudo update-alternatives --install "/usr/bin/javac" "javac" "/usr/lib/jvm/jdk1.5.0_22/bin/javac" 2

You have installed the jdk 1.5 Successfully

If you two verions of jdk you can use following commands to switch them

sudo update-alternatives --config java
sudo update-alternatives --config javac

Confirm the version of Java currently in use with these commands:

java -version
javac -version

Cheers!!!

Friday 14 November 2014

Storing POJOs in MongoDB Using Morphia

Storing POJOs in MongoDB Using Morphia:

Storing data in any Database is always a challenge irrespective of the Datadabase.

MongoDB is a leading NoSQL Database.
We create pojo/entity and store the data in the Database using framework like Hibernate.

Similarly we have Morphia which helps to store the data in the MongoDB.
In this we will try to store the Person data in the MongoDB.
Person will have name, address and the hobbies.

To store the above mentioned person data, we will create the entities.
Will create the entities for Person Entity, Hobbies Entity and the Address Entity.

We will embed the Hobbies and Address entity into Person.

Entity Annotation : To Store the class in MongoDB thro' Morphia, add annotate to class as @Entity

To Suppress the class name from the Mongo Document use "noClassnameStored=true".

@Id : Entity require unique @Id values; these values are stored in the MongoDB "_id" field.

@Indexed : This annotation applies an index to a field.
           The indexes are applied when the datastore.ensureIndexes() method is called

Example : @Indexed(value=IndexDirection.ASC, name="userName", unique=true, dropDups=true)

@Embedded :  to create a class that will be embedded in the Entity.

Below is the code sample of the mentioned Entities.

package com.mongo.morphia.entity;

import java.util.List;

import org.bson.types.ObjectId;

import com.google.code.morphia.annotations.Embedded;
import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Id;
import com.google.code.morphia.annotations.Property;

@Entity(noClassnameStored=true)
public class Person {

@Id
@Property("id")
private ObjectId id;

private String name;
private List<Hobbies> hobbies;
@Embedded
private Address address;

public ObjectId getId() {
return id;
}

public void setId(ObjectId id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public List<Hobbies> getHobbiess() {
return hobbies;
}

public void setHobbies(List<Hobbies> hobbies) {
this.hobbies = hobbies;
}

public Address getAddress() {
return address;
}

public void setAddress(Address address) {
this.address = address;
}

}


package com.mongo.morphia.entity;

import com.google.code.morphia.annotations.Embedded;

@Embedded
public class Address {
private String number;
private String street;
private String town;
private String postcode;

public String getNumber() {
return number;
}

public void setNumber(String number) {
this.number = number;
}

public String getStreet() {
return street;
}

public void setStreet(String street) {
this.street = street;
}

public String getTown() {
return town;
}

public void setTown(String town) {
this.town = town;
}

public String getPostcode() {
return postcode;
}

public void setPostcode(String postcode) {
this.postcode = postcode;
}

}



package com.mongo.morphia.entity;

import org.bson.types.ObjectId;

import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Id;
import com.google.code.morphia.annotations.Property;

@Entity
public class Hobbies {

@Id
@Property("id")
private ObjectId id;

private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public ObjectId getId() {
return id;
}

public void setId(ObjectId id) {
this.id = id;
}
}
DAO class..

package com.mongo.morphia.dao;

import com.google.code.morphia.Morphia;
import com.google.code.morphia.dao.BasicDAO;
import com.mongo.morphia.entity.Person;
import com.mongodb.Mongo;

public class PersonDAO extends BasicDAO<Person, String> {  

public PersonDAO(Morphia morphia, Mongo mongo, String dbName) {      
super(mongo, morphia, dbName);  
}
 
}





In the below class we have called the save , update , find and Delete operation. here we are using the entities to do all the operations.

package com.mongo.morphia;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import com.google.code.morphia.Datastore;
import com.google.code.morphia.Morphia;
import com.google.code.morphia.mapping.Mapper;
import com.google.code.morphia.query.Query;
import com.google.code.morphia.query.QueryResults;
import com.google.code.morphia.query.UpdateOperations;
import com.mongo.morphia.dao.PersonDAO;
import com.mongo.morphia.entity.Hobbies;
import com.mongo.morphia.entity.Address;
import com.mongo.morphia.entity.Person;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

public class Example {

public static void main(String[] args) throws UnknownHostException,MongoException {

String dbName = new String("User");
Mongo mongo = new Mongo();
Morphia morphia = new Morphia();
Datastore datastore = morphia.createDatastore(mongo, dbName);

morphia.mapPackage("com.mongo.morphia.entity");

Address address = new Address();
address.setNumber("Q-101");
address.setStreet("M.G. Road");
address.setTown("Pune");
address.setPostcode("411001");

Hobbies hobbies = new Hobbies();
hobbies.setName("Trekking");

List<Hobbies> listHobbies = new ArrayList<Hobbies>();
listHobbies.add(hobbies);

Person person = new Person();
person.setAddress(address);
person.setName("Mr Martin d'souza");
person.setHobbies(listHobbies);

//Save Methods
PersonDAO personDAO = new PersonDAO(morphia, mongo, dbName);
personDAO.save(person);

//Find Methods
//use in a loop
for(Person personObj : datastore.find(Person.class, "hobbies.name", "Trekking")) {
System.out.println(personObj.getName());
}

//get back as a list
//List<Person> personObj1 = datastore.find(Person.class, "name", "Martin").asList();

// Get the Data Using Query Criteria
Query<Person> query = datastore.createQuery(Person.class);
query.and(query.criteria("hobbies.name").equal("Trekking"),
query.criteria("address.number").equal("Q-101"),
query.criteria("name").contains("Martin"));

QueryResults<Person> retrievedPersons = personDAO.find(query);

for (Person retrievedPerson : retrievedPersons) {
System.out.println(retrievedPerson.getName());
System.out.println(retrievedPerson.getAddress().getPostcode());
System.out.println(retrievedPerson.getHobbiess().get(0).getName());
}

//Update Methods
for (Person retrievedPerson : retrievedPersons) {

UpdateOperations<Person> updatePerson = datastore.createUpdateOperations(Person.class).set("name", "Kevin Gibbs");
datastore.update(datastore.createQuery(Person.class).field(Mapper.ID_KEY).equal(retrievedPerson.getId()), updatePerson);

//Delete Methods
//personDAO.delete(retrievedCustomer);
}
}

}

Thursday 13 November 2014

Java To Python.......

Learning a new thing is always a fun... then whatever it is ... you enjoy it...
I am learning Python now...I knew java and use it for building the application as of now....
While learning the Python, it doesn't seems to hard with respect to the syntax..its very easy..
its like plain text sort of thing being learnt...

Python's simple and straight-forward syntax also encourages good programming habbits, especially through its focus on white space indentation, which contributes to the development of neat looking code.

We try to put out some difference between Python and Java...

Before that I am not criticizing any language here, just wanted you to enjoy this as I had...

1. If you want to print the "Hello World" in java, it looks something like this

public class TestJava {
public static void main(String[] args) {

System.out.println("Hello World");
}
}

and the same thing in Python is

print "Hello, Python!";


2. When it comes to some reserved words ..then yes both the languages has some keys reserved. I dint find any difference here. And the view is same that the reserved words not be used as constant or variable or any other identifier names.


3. Next is line and indentation where In Python the fact is that there are no braces to indicate blocks of code for class and function definitions or flow control. Blocks of code are denoted by line indentation, which is rigidly enforced.

The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount.
Both blocks in this example are fine:

if True:
    print "True"
else:
  print "False"

and the below block in this example will generate an error:

if True:
    print "Answer"
    print "True"
else:
    print "Answer"
  print "False"


Thus, in Python all the continuous lines indented with similar number of spaces would form a block.


4. Quotation in Python: Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the same type of quote starts and ends the string.

Same is not the case with Java while defining the String literals.. :)

5. Commenting the code in Python : A hash sign (#) that is not inside a string literal begins a comment.
All characters after the # and up to the physical line end are part of the comment and the Python interpreter ignores them.

In java Single line commenting is done by "//" and multiple lines commenting is by /* */. Anything that comes between /* */ will be ignored.

6. Values Assigning to Variable : In Python
   count = 100  # integer assignment
   distance = 10.5 # floating
   name = "Steve"  # String

   In Java

   String name = "xyx";
   Integer count = 100;

   Difference is you need to mention the data type along with the variable name.

7. Multiple Assignment:
   Python allows you to assign a single value to several variables simultaneously.
   For example:
a = b = c = 1

   Same thing is not possible in Java.

   You can also assign multiple objects to multiple variables.
   For example:
  a, b, c = 1, 2, "john"
   and if you print it the output is
   print a,b,c
   1 2 john

8. Lists : Lists are the most versatile of Python's compound data types.
   A list contains items separated by commas and enclosed within square brackets ([]).

   In java you have different collections like ArrayList and Hashset etc.

   One difference between them is that all the items belonging to a list in Python can be of different data    type.

   In Java it does too but seems hard when you introduce Generics.

9. Value access from List :
   In Python the values stored in a list can be accessed using the slice operator ( [ ] and [ : ] ) with
   indexes starting at 0 in the beginning of the list and working their way to end -1.
   list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
   
   print list          # Prints complete list
   print list[0]       # Prints first element of the list
   print list[1:3]     # Prints elements starting from 2nd till 3rd

   In Java use of Iterator or new for each would be used to get the data.

10. Defining a Function
    Here are simple rules to define a function in Python.
    Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).
    Any input parameters or arguments should be placed within these parentheses. You can also define       parameters inside these parentheses.
    The first statement of a function can be an optional statement - the documentation string of the               function or docstring.
    The code block within every function starts with a colon (:) and is indented.
    The statement return [expression] exits a function, optionally passing back an expression to the caller.
    A return statement with no arguments is the same as return None.
   
    For Example :
    def printme( str ):
    "This prints a passed string into this function"
    print str
    return

    In Java :
    public void test(Integer i){
System.out.println("funtion" + i);
    }


I would appreciate if anyone add more if they knew and correct me if I am wrong at any point...
Till then cheers...

Tuesday 3 June 2014

Generating plain xml from Jasper Irrespective of the Locale

Generating plain xml from the jasper report has another problem for me.

If the locale is changed then the column names will get changed.

As I want the xml for the Data Feed, it would not work as the xml parsing
mechanism will change as the locale will change.


So to achieve the same i.e. to get the xml attribute in English all the time
irrespective of the locale, need to do some changes in the code.

Here is the modified exportText method.


public void exportText(JRPrintText text) throws IOException
{

JRStyle style = text.getStyle();
if (style != null){
String styleName = style.getName();
if(!isColumn && "TableColumnHeaderTextStyle".equals(styleName)){
columnMap.put(columnCount, text.getOriginalText());
columnCount++;
}else if(!isRow && "TableDetailTextStyle".equals(styleName)){
isColumn = true;
isRow = true;
}
}

if(isRow){
if (!isNewColumn && text.hasProperties())
{
JRPropertiesMap propertiesMap = text.getPropertiesMap();
String[] propertyNames = propertiesMap.getPropertyNames();
if (propertyNames != null && propertyNames.length > 0)
{
for(int i = 0; i < propertyNames.length; i++)
{
String value = propertiesMap.getProperty(propertyNames[i]);
if (value != null)
{
int p = value.indexOf('.');
String regex = "[_][0-9][0-9][0-9]";
if (p >= 0) {
   String right = value.substring(p + 1);
   String []val = right.split(regex);
   String modValue = val[0];
   if(newColumnMap.containsValue(modValue)){
    isNewColumn = true;
    }else{
    newColumnMap.put(newCoulmnCount, modValue);
    newCoulmnCount++ ;
    }
   }
}
}
}
}

if(style != null && "TableDetailTextStyle".equals(style.getName())){
isRowClosed = false;
if(rowCount == 0){
xmlWriter.startElement(ELEMENT_row);
}

if(null == text.getOriginalText()){
System.out.println("text value is null");
}

String attributName = newColumnMap.get(rowCount);
xmlWriter.addEncodedAttribute(attributName, text.getOriginalText());
rowCount++;
}

if(rowCount == columnCount){
isRowClosed = true;
xmlWriter.closeElement();
rowCount = 0;
}
}

}

Sunday 1 June 2014

XML parsing Issues

While working on Generating XML output/export in jasper, I came across some xml issues.

Xml generation was successful, but parsing the same in browsers had some issues.

Listing out those issues here and the solution for the same.

Every Browser show the error or explain it differently.

Here I am showing the errors by crome and Firefox.


Issue 1:

On Crome :
This page contains the following errors:
error on line 4 at column 60: Specification mandate value for attribute Size
Below is a rendering of the page up to the first error.

Here Size is the attribute name, being used by me in the xml.
The original column name in jasper was Size(Kb)

On FireFox :
XML Parsing Error: not well-formed
Location: http://10.55.36.34:8080/xyz?id=dT01ODg5NyZwPTEzODI4JnI9VGVzdCBSZXBvcnQmaj0vOTYzNDctdXNyLWZvbC11cmkvMTM4MjgtdXNyLXdzLXJlcG9ydHMtZm9sLXVyaS9UZXN0X1JlcG9ydCZkPTE0MDA3MzkxODYwODgmYz0xNjgyMjA4NTg2
Line Number 4, Column 171:
<row Reference="abc-16316AD-2411101F000" Action_Date="18/03/2014 11:45" Title="audit.png" User_Name="SEND NO MESSAGES KEINE NACHRICHT SENDEN" Content_Id="21565941" Size(Kb)="72"

FireFox highlights the error by pointing to the attribute "Size(Kb)". The attribute contains the special character.

By removing/replacing the special character "(", the above issue gets resolved.


Issue 2:

On crome :
This page contains the following errors:
error on line 6843 at column 19: Extra content at the end of the document
Below is a rendering of the page up to the first error.

On FireFox :
XML Parsing Error: no element found
Location: http://10.55.36.34:8080/xyz?id=dT01ODg5NyZwPTEzODI4JnI9RG9jdW1lbnQgRGlzdHJpYnV0aW9uIFYxIFJlcG9ydCZqPS85NjM0Ny11c3ItZm9sLXVyaS8xMzgyOC11c3Itd3MtcmVwb3J0cy1mb2wtdXJpL0RvY3VtZW50X0Rpc3RyaWJ1dGlvbl9WMV9SZXBvcnQmZD0xNDAwNzUxODUzNDUzJmM9MzI3NjMxMDE0Mg
Line Number 6844, Column 1:

The error was because of xml root node is missing.


Issue 3:

Mozilla....

XML Parsing Error: duplicate attribute
Location: http://10.55.36.34:8080/BIReportDataFeed?id=dT01ODg5NyZwPTEzODI4Jmo9Lzk2MzQ3LXVzci1mb2wtdXJpLzEzODI4LXVzci13cy1yZXBvcnRzLWZvbC11cmkvRG9jdW1lbnRfTWV0YWRhdGEmZD0xNDAwODUyNzU5Mjg2JmM9MjUzMTIwMTg0NQ
Line Number 4, Column 42: <row Reference="GER-BRU-7" Property="" Property="" Property="" Property="" Property="" Property="" Property="" Property="" Property=""/>


This is very straight forward. Xml does not allow duplicate attributes.

Wednesday 21 May 2014

Generate Xml export from Jasper for the data feed in Excel.

Generate Xml export from Jasper for the data feed in Excel.

Generating xml export from jasper for the data feed.
This data feed or the xml file when imported in excel should generate a report in correct format.

The xml format is

<jasperPrint name="rt demo">
<report-results>
<row Reference="Dummy Reference 12" Date="25/03/2014 16:38" User_Name="Vaibhav joshi" Type_ID="85"/>
<row Reference="Dummy Reference 11" Date="25/03/2014 16:38" User_Name="Vaibhav joshi" Type_ID="85"/>
<row Reference="Dummy Reference 5" Date="25/03/2014 16:34" User_Name="Vaibhav joshi" Type_ID="17"/>
<row Reference="Dummy Reference 5" Date="25/03/2014 16:34" User_Name="Vaibhav joshi" Type_ID="3"/>
<row Reference="Dummy Reference 4" Date="25/03/2014 16:34" User_Name="Vaibhav joshi" Type_ID="3"/>
<row Reference="Dummy Reference 2" Date="21/03/2014 12:15" User_Name="Vaibhav joshi" Type_ID="165"/>
<row Reference="register2.JPG" Date="20/03/2014 14:03" User_Name="Vaibhav joshi" Type_ID="1"/>
<row Reference="Dummy Reference 1" Date="20/03/2014 12:43" User_Name="Vaibhav joshi" Type_ID="17"/>
<row Reference="Dummy Reference 2" Date="20/03/2014 12:43" User_Name="Vaibhav joshi" Type_ID="17"/>
<row Reference="Dummy Reference 6" Date="18/03/2014 12:48" User_Name="Vaibhav joshi" Type_ID="7"/>
<row Reference="Dummy Reference 7" Date="18/03/2014 12:48" User_Name="Vaibhav joshi" Type_ID="7"/>
........
.......
......
</jasperPrint>


The Modified XML Export code to achieve the above xml is :

public class FinalCustomExporter extends JRXmlExporter
{
private static final Log log = LogFactory.getLog(JRXmlExporter.class);
private static final String XML_EXPORTER_PROPERTIES_PREFIX = JRPropertiesUtil.PROPERTY_PREFIX + "export.xml.";
public static final String XML_EXPORTER_KEY = JRPropertiesUtil.PROPERTY_PREFIX + "xml";

public static final String PROPERTY_REPLACE_INVALID_CHARS = JRPropertiesUtil.PROPERTY_PREFIX + "export.xml.replace.invalid.chars";
protected static final String DEFAULT_XML_ENCODING = "UTF-8";
protected static final String DEFAULT_OBJECT_TYPE = "java.lang.String";
protected static final String XML_FILES_SUFFIX = "_files";
protected static final String IMAGE_PREFIX = "img_";
public static final String ELEMENT_row  = "row";
public static final String ELEMENT_report_results  = "report-results";

public static final XmlNamespace JASPERPRINT_NAMESPACE =
new XmlNamespace(JRXmlConstants.JASPERPRINT_NAMESPACE, null, JRXmlConstants.JASPERPRINT_XSD_SYSTEM_ID);

protected JRXmlWriteHelper xmlWriter;
protected String encoding;
protected String version;
protected VersionComparator versionComparator = new VersionComparator();

protected JRExportProgressMonitor progressMonitor;
protected Map<Renderable,String> rendererToImagePathMap;
protected Map<String,byte[]> imageNameToImageDataMap;
protected Map<String,JRStyle> stylesMap = new HashMap<String,JRStyle>();

protected boolean isEmbeddingImages = true;
protected boolean isColumn = false;
protected boolean isRow = false;
protected Integer columnCount = 0;
protected Integer rowCount = 0;
protected Map<Integer,String> columnMap = new HashMap<Integer, String>();
protected File destFile;
protected File imagesDir;

protected class ExporterContext extends BaseExporterContext implements JRXmlExporterContext
{
public String getExportPropertiesPrefix()
{
return FinalCustomExporter.this.getExporterPropertiesPrefix();
}
}

protected JRXmlExporterContext exporterContext = new ExporterContext();


public FinalCustomExporter()
{
this(DefaultJasperReportsContext.getInstance());
}


public FinalCustomExporter(JasperReportsContext jasperReportsContext)
{
super(jasperReportsContext);
}


public void exportReport() throws JRException
{
progressMonitor = (JRExportProgressMonitor)parameters.get(JRExporterParameter.PROGRESS_MONITOR);

setOffset();

try
{
setExportContext();

setInput();

if (!parameters.containsKey(JRExporterParameter.FILTER))
{
filter = createFilter(getExporterPropertiesPrefix());
}

setPageRange();

@SuppressWarnings("deprecation")
String dtdLocation = (String)parameters.get(JRXmlExporterParameter.DTD_LOCATION);
if (dtdLocation != null)
{
log.warn("The JRXmlExporterParameter.DTD_LOCATION export parameter has no effect and should no longer be used.");
}

encoding = (String)parameters.get(JRExporterParameter.CHARACTER_ENCODING);
if (encoding == null)
{
encoding = DEFAULT_XML_ENCODING;
}

setHyperlinkProducerFactory();

StringBuffer sb = (StringBuffer)parameters.get(JRExporterParameter.OUTPUT_STRING_BUFFER);
if (sb != null)
{
StringBuffer buffer = exportReportToBuffer();
sb.append(buffer.toString());
}
else
{
Writer outWriter = (Writer)parameters.get(JRExporterParameter.OUTPUT_WRITER);
if (outWriter != null)
{
try
{
exportReportToStream(outWriter);
}
catch (IOException e)
{
throw new JRException("Error writing to writer : " + jasperPrint.getName(), e);
}
}
else
{
OutputStream os = (OutputStream)parameters.get(JRExporterParameter.OUTPUT_STREAM);
if (os != null)
{
try
{
exportReportToStream(new OutputStreamWriter(os, encoding));
}
catch (Exception e)
{
throw new JRException("Error writing to OutputStream : " + jasperPrint.getName(), e);
}
}
else
{
destFile = (File)parameters.get(JRExporterParameter.OUTPUT_FILE);
if (destFile == null)
{
String fileName = (String)parameters.get(JRExporterParameter.OUTPUT_FILE_NAME);
if (fileName != null)
{
destFile = new File(fileName);
}
else
{
throw new JRException("No output specified for the exporter.");
}
}

imagesDir = new File(destFile.getParent(), destFile.getName() + XML_FILES_SUFFIX);

Boolean isEmbeddingImagesParameter = (Boolean)parameters.get(JRXmlExporterParameter.IS_EMBEDDING_IMAGES);
if (isEmbeddingImagesParameter == null)
{
isEmbeddingImagesParameter = Boolean.TRUE;
}
isEmbeddingImages = isEmbeddingImagesParameter.booleanValue();

exportReportToFile();
}
}
}
}
finally
{
resetExportContext();
}
}

protected void setHyperlinkProducerFactory()
{
hyperlinkProducerFactory = (JRHyperlinkProducerFactory) parameters.get(JRExporterParameter.HYPERLINK_PRODUCER_FACTORY);
}

protected void exportReportToFile() throws JRException
{
{
rendererToImagePathMap = new HashMap<Renderable,String>();
imageNameToImageDataMap = new HashMap<String,byte[]>();
}

Writer writer = null;
try
{
OutputStream fileOutputStream = new FileOutputStream(destFile);
writer = new BufferedWriter(new OutputStreamWriter(fileOutputStream, encoding));
exportReportToStream(writer);
}
catch (IOException e)
{
throw new JRException("Error writing to file : " + destFile, e);
}
finally
{
if (writer != null)
{
try
{
writer.close();
}
catch(IOException e)
{
}
}
}

if (!isEmbeddingImages)
{
Collection<String> imageNames = imageNameToImageDataMap.keySet();
if (imageNames != null && imageNames.size() > 0)
{
if (!imagesDir.exists())
{
imagesDir.mkdir();
}

for(Iterator<String> it = imageNames.iterator(); it.hasNext();)
{
String imageName = it.next();
byte[] imageData = imageNameToImageDataMap.get(imageName);

File imageFile = new File(imagesDir, imageName);

OutputStream fos = null;
try
{
fos = new FileOutputStream(imageFile);
fos.write(imageData, 0, imageData.length);
}
catch (IOException e)
{
throw new JRException("Error writing to image file : " + imageFile, e);
}
finally
{
if (fos != null)
{
try
{
fos.close();
}
catch(IOException e)
{
}
}
}
}
}
}
}


protected StringBuffer exportReportToBuffer() throws JRException
{
StringWriter buffer = new StringWriter();
try
{
exportReportToStream(buffer);
}
catch (IOException e)
{
throw new JRException("Error while exporting report to buffer", e);
}
return buffer.getBuffer();
}

protected XmlNamespace getNamespace()
{
return JASPERPRINT_NAMESPACE;
}

protected void exportReportToStream(Writer writer) throws JRException, IOException
{
version = JRPropertiesUtil.getInstance(jasperReportsContext).getProperty(jasperPrint, JRXmlBaseWriter.PROPERTY_REPORT_VERSION);

xmlWriter = new JRXmlWriteHelper(writer);

xmlWriter.writeProlog(encoding);

xmlWriter.startElement(JRXmlConstants.ELEMENT_jasperPrint);
xmlWriter.addEncodedAttribute(JRXmlConstants.ATTRIBUTE_name, jasperPrint.getName());

List<JRPrintPage> pages = jasperPrint.getPages();
if (pages != null && pages.size() > 0)
{
JRPrintPage page = null;
for(int i = startPageIndex; i <= endPageIndex; i++)
{
if (Thread.interrupted())
{
throw new JRException("Current thread interrupted.");
}

page = pages.get(i);

exportPage(page);
}

if(isRow){
xmlWriter.closeElement();
isRow = false;
}
}

xmlWriter.closeElement();

writer.flush();
}


protected void exportPage(JRPrintPage page) throws JRException, IOException
{
exportElements(page.getElements());

if (progressMonitor != null)
{
progressMonitor.afterPageExport();
}
}

protected void exportElements(Collection<JRPrintElement> elements) throws IOException, JRException
{
if (elements != null && elements.size() > 0)
{
for(Iterator<JRPrintElement> it = elements.iterator(); it.hasNext();)
{
exportElement(it.next());
}
}
}

public void exportElement(JRPrintElement element) throws IOException, JRException
{
if (filter == null || filter.isToExport(element))
{
if (element instanceof JRPrintText)
{
exportText((JRPrintText)element);
}
else if (element instanceof JRPrintFrame)
{
exportFrame((JRPrintFrame) element);
}
}
}

public void exportText(JRPrintText text) throws IOException
{
JRStyle style = text.getStyle();
if (style != null){
String styleName = style.getName();
if(!isColumn && "TableColumnHeaderTextStyle".equals(styleName)){
columnMap.put(columnCount, text.getOriginalText());
columnCount++;
}else if(!isRow && "TableDetailTextStyle".equals(styleName)){
isColumn = true;
isRow = true;
xmlWriter.startElement(ELEMENT_report_results);
}
}

if(isRow && style != null && "TableDetailTextStyle".equals(style.getName())){

if(rowCount == 0){
xmlWriter.startElement(ELEMENT_row);
}

if(null == text.getOriginalText()){
System.out.println("text value is null");
}

String attributName = columnMap.get(rowCount);
String replaceAttribName = attributName.replace(" ", "_");
xmlWriter.addEncodedAttribute(replaceAttribName, text.getOriginalText());
rowCount++;
}

if(rowCount == columnCount){
xmlWriter.closeElement();
rowCount = 0;
}
}

protected void exportFrame(JRPrintFrame frame) throws IOException, JRException
{
setFrameElementsOffset(frame, true);
try
{
exportElements(frame.getElements());
}
finally
{
restoreElementOffsets();
}
}

protected String getExporterPropertiesPrefix()
{
return XML_EXPORTER_PROPERTIES_PREFIX;
}


public String getExporterKey()
{
return XML_EXPORTER_KEY;
}

public JRXmlWriteHelper getXmlWriteHelper()
{
return xmlWriter;
}

protected boolean isNewerVersionOrEqual(String oldVersion)
{
return versionComparator.compare(version, oldVersion) >= 0;
}
}


Here is the output in Excel looks alike...






Tuesday 20 May 2014

Generate XML Output from Jasper Reports

Generate XML Output from Jasper Reports :

I was trying for generating/exporting the data in xml from Jasper.
It generates the data in xml but along with the text content it generates the other tag/layout data
in xml as which is the layout of the report...like style tag and all... which is not required.

So we modified the code to achieve xml export.


The xml ouput we were getting from the jasper was something like this


<jasperPrint xmlns="http://jasperreports.sourceforge.net/jasperreports/print" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/print http://jasperreports.sourceforge.net/xsd/jasperprint.xsd" name="rt demo" pageWidth="665" pageHeight="792" topMargin="20" leftMargin="20" bottomMargin="20" rightMargin="20" locale="en_US" timezone="Asia/Calcutta">
<property name="net.sf.jasperreports.export.xml.start.page.index" value="0"/>
<property name="net.sf.jasperreports.export.xml.end.page.index" value="2"/>
<property name="net.sf.jasperreports.export.xml.page.count" value="3"/>
<property name="net.sf.jasperreports.export.xls.collapse.row.span" value="false"/>
<property name="net.sf.jasperreports.export.html.border.collapse" value="separate"/>
<property name="net.sf.jasperreports.export.docx.frames.as.nested.tables" value="false"/>
<property name="net.sf.jasperreports.export.pdf.tagged" value="false"/>
<property name="net.sf.jasperreports.export.pdf.tag.language" value="EN-US"/>
<origin group="newSet2.CATEGORY_NAME" band="groupHeader"/>
<origin group="newSet2.CATEGORY_NAME" band="groupFooter"/>
<origin band="title"/>
<origin band="detail"/>
<origin band="summary"/>
<origin report="rt32demo_tableDataset_1400134558392_604720" group="newSet2.CATEGORY_NAME" band="groupHeader"/>
<origin report="rt32demo_tableDataset_1400134558392_604720" group="newSet2.CATEGORY_NAME" band="groupFooter"/>
<origin report="rt32demo_tableDataset_1400134558392_604720" band="columnHeader"/>
<origin report="rt32demo_tableDataset_1400134558392_604720" band="detail"/>
<style name="ReportDefault" isDefault="true" mode="Transparent" forecolor="#666666" backcolor="#FFFFFF" hAlign="Left" vAlign="Middle" fontName="DejaVu Sans" fontSize="11">...</style>
<style name="TableBaseFrameStyle" mode="Transparent">...</style>
<style name="TableFrameStyle" style="TableBaseFrameStyle">...</style>
<style name="TableColumnHeaderFrameStyle" style="TableBaseFrameStyle">...</style>
<style name="TableColumnFooterFrameStyle" style="TableBaseFrameStyle">...</style>
<style name="TableColumnHeaderTextStyle" style="ReportDefault" mode="Opaque" forecolor="#666666" backcolor="#D5DEE8" hAlign="Left" vAlign="Middle" fontName="DejaVu Sans" fontSize="11" isBold="true">...</style>
.....
......
<style name="ChartSeriesColor0" backcolor="#87C4FE"/>
<style name="ChartSeriesColor1" backcolor="#E96270"/>
......
......
<page>
<frame>
<reportElement uuid="21047d3c-c9f7-46e2-810e-3689a470fce9" style="TableFrameStyle" x="20" y="20" width="627" height="727" origin="4" srcId="3">...</reportElement>
<frame>
<reportElement uuid="1b51c819-e28b-43a1-87a3-3add5e51ac0d" x="0" y="0" width="125" height="25" origin="7" srcId="8">
<property name="net.sf.jasperreports.export.headertoolbar.cellID" value="newSet2.DOCUMENT_REFERENCE_1882018985_0"/>
<property name="net.sf.jasperreports.export.html.class" value="jrcolHeader interactiveElement"/>
<property name="net.sf.jasperreports.export.headertoolbar.columnUUID" value="93469203-1702-437d-856c-5326b63e6082"/>
<property name="net.sf.jasperreports.export.headertoolbar.tableUUID" value="21047d3c-c9f7-46e2-810e-3689a470fce9"/>
<property name="net.sf.jasperreports.export.headertoolbar.columnIndex" value="0"/>
</reportElement>
<genericElement>...</genericElement>
<text textAlignment="Left" textHeight="12.8046875" lineSpacingFactor="1.1640625" leadingOffset="-2.5942383">
<reportElement uuid="940ff028-90cf-4ca2-ae5c-864da3e50ebc" style="TableColumnHeaderTextStyle" x="0" y="0" width="125" height="25" origin="7" srcId="10"/>
<textContent>
<![CDATA[ Reference ]]>
</textContent>
<lineBreakOffsets>
<![CDATA[ ]]>
</lineBreakOffsets>
</text>
</frame>
<frame>
<reportElement uuid="6720edab-8950-4141-8120-c705e23c0082" x="125" y="0" width="125" height="25" origin="7" srcId="11">
<property name="net.sf.jasperreports.export.headertoolbar.cellID" value="newSet1.AUDIT_EVENT_DATE_TIME_806444232_0"/>
<property name="net.sf.jasperreports.export.html.class" value="jrcolHeader interactiveElement"/>
......
<frame>
<reportElement uuid="a363100e-edd8-4a0e-93dd-e05d00b25368" x="500" y="0" width="125" height="25" origin="7" srcId="20">
<property name="net.sf.jasperreports.export.headertoolbar.cellID" value="newSet1.AUDIT_EVENT_TYPE_ID_1616381145_0"/>
<property name="net.sf.jasperreports.export.html.class" value="jrcolHeader interactiveElement"/>

<reportElement uuid="7d0e99df-b27b-4d17-9642-153799495f2b" key="textField" style="TableDetailTextStyle" x="500" y="250" width="125" height="25" origin="8" srcId="27">
<property name="net.sf.jasperreports.export.html.class" value="jrcel cel_newSet1.AUDIT_EVENT_TYPE_ID_1616381145_0"/>
</reportElement>
<textContent>
<![CDATA[ 17 ]]>
</textContent>
<lineBreakOffsets>
<![CDATA[ ]]>
</lineBreakOffsets>
</text>
...........
..........
...........


this was not in readable format for us.

So we modified the code by Writing CustomXmlExporter and got the xml in proper format.


<jasperPrint name="rt demo">
<columns>
<column>
<![CDATA[ Reference ]]>
</column>
<column>
<![CDATA[ Action Date ]]>
</column>
<column>
<![CDATA[ Uploaded By Username ]]>
</column>
<column>
<![CDATA[ User Name ]]>
</column>
<column>
<![CDATA[ Action Type ID ]]>
</column>
</columns>
<rows>
<row>
<text>
<![CDATA[ Dummy Reference 12 ]]>
</text>
<text>
<![CDATA[ 25/03/2014 16:38 ]]>
</text>
<text>
<![CDATA[ xyz xyz ]]>
</text>
<text>
<![CDATA[ xyz xyz ]]>
</text>
<text>
<![CDATA[ 85 ]]>
</text>
</row>
<row>
<text>
<![CDATA[ Dummy Reference 11 ]]>
</text>
<text>
<![CDATA[ 25/03/2014 16:38 ]]>
</text>
<text>
<![CDATA[ xyz xyz ]]>
</text>
<text>
<![CDATA[ xyz xyz ]]>
</text>
<text>
<![CDATA[ 85 ]]>
</text>
</row>
..........
<row>
<text>
...........
...........
...........

</rows>
</jasperPrint>


This is been achieved by modifying the below code.


public class FinalCustomExporter extends JRXmlExporter
{
private static final Log log = LogFactory.getLog(JRXmlExporter.class);
private static final String XML_EXPORTER_PROPERTIES_PREFIX = JRPropertiesUtil.PROPERTY_PREFIX + "export.xml.";
public static final String XML_EXPORTER_KEY = JRPropertiesUtil.PROPERTY_PREFIX + "xml";

public static final String PROPERTY_REPLACE_INVALID_CHARS = JRPropertiesUtil.PROPERTY_PREFIX + "export.xml.replace.invalid.chars";
protected static final String DEFAULT_XML_ENCODING = "UTF-8";
protected static final String DEFAULT_OBJECT_TYPE = "java.lang.String";
protected static final String XML_FILES_SUFFIX = "_files";
protected static final String IMAGE_PREFIX = "img_";
public static final java.lang.String ELEMENT_columns  = "columns";
public static final java.lang.String ELEMENT_column  = "column";
public static final java.lang.String ELEMENT_rows  = "rows";
public static final java.lang.String ELEMENT_row  = "row";

public static final XmlNamespace JASPERPRINT_NAMESPACE =
new XmlNamespace(JRXmlConstants.JASPERPRINT_NAMESPACE, null, JRXmlConstants.JASPERPRINT_XSD_SYSTEM_ID);

protected JRXmlWriteHelper xmlWriter;
protected String encoding;
protected String version;
protected VersionComparator versionComparator = new VersionComparator();

protected JRExportProgressMonitor progressMonitor;
protected Map<Renderable,String> rendererToImagePathMap;
protected Map<String,byte[]> imageNameToImageDataMap;
protected Map<String,JRStyle> stylesMap = new HashMap<String,JRStyle>();

protected boolean isEmbeddingImages = true;
protected boolean isColumn = false;
protected boolean isRow = false;
protected Integer columnCount = 0;
protected Integer rowCount = 0;
protected File destFile;
protected File imagesDir;

protected class ExporterContext extends BaseExporterContext implements JRXmlExporterContext
{
public String getExportPropertiesPrefix()
{
return FinalCustomExporter.this.getExporterPropertiesPrefix();
}
}

protected JRXmlExporterContext exporterContext = new ExporterContext();


public FinalCustomExporter()
{
this(DefaultJasperReportsContext.getInstance());
}


public FinalCustomExporter(JasperReportsContext jasperReportsContext)
{
super(jasperReportsContext);
}


public void exportReport() throws JRException
{
progressMonitor = (JRExportProgressMonitor)parameters.get(JRExporterParameter.PROGRESS_MONITOR);

setOffset();

try
{
setExportContext();

setInput();

if (!parameters.containsKey(JRExporterParameter.FILTER))
{
filter = createFilter(getExporterPropertiesPrefix());
}

setPageRange();

@SuppressWarnings("deprecation")
String dtdLocation = (String)parameters.get(JRXmlExporterParameter.DTD_LOCATION);
if (dtdLocation != null)
{
log.warn("The JRXmlExporterParameter.DTD_LOCATION export parameter has no effect and should no longer be used.");
}

encoding = (String)parameters.get(JRExporterParameter.CHARACTER_ENCODING);
if (encoding == null)
{
encoding = DEFAULT_XML_ENCODING;
}

setHyperlinkProducerFactory();

StringBuffer sb = (StringBuffer)parameters.get(JRExporterParameter.OUTPUT_STRING_BUFFER);
if (sb != null)
{
StringBuffer buffer = exportReportToBuffer();
sb.append(buffer.toString());
}
else
{
Writer outWriter = (Writer)parameters.get(JRExporterParameter.OUTPUT_WRITER);
if (outWriter != null)
{
try
{
exportReportToStream(outWriter);
}
catch (IOException e)
{
throw new JRException("Error writing to writer : " + jasperPrint.getName(), e);
}
}
else
{
OutputStream os = (OutputStream)parameters.get(JRExporterParameter.OUTPUT_STREAM);
if (os != null)
{
try
{
exportReportToStream(new OutputStreamWriter(os, encoding));
}
catch (Exception e)
{
throw new JRException("Error writing to OutputStream : " + jasperPrint.getName(), e);
}
}
else
{
destFile = (File)parameters.get(JRExporterParameter.OUTPUT_FILE);
if (destFile == null)
{
String fileName = (String)parameters.get(JRExporterParameter.OUTPUT_FILE_NAME);
if (fileName != null)
{
destFile = new File(fileName);
}
else
{
throw new JRException("No output specified for the exporter.");
}
}

imagesDir = new File(destFile.getParent(), destFile.getName() + XML_FILES_SUFFIX);

Boolean isEmbeddingImagesParameter = (Boolean)parameters.get(JRXmlExporterParameter.IS_EMBEDDING_IMAGES);
if (isEmbeddingImagesParameter == null)
{
isEmbeddingImagesParameter = Boolean.TRUE;
}
isEmbeddingImages = isEmbeddingImagesParameter.booleanValue();

exportReportToFile();
}
}
}
}
finally
{
resetExportContext();
}
}

protected void setHyperlinkProducerFactory()
{
hyperlinkProducerFactory = (JRHyperlinkProducerFactory) parameters.get(JRExporterParameter.HYPERLINK_PRODUCER_FACTORY);
}

protected void exportReportToFile() throws JRException
{
{
rendererToImagePathMap = new HashMap<Renderable,String>();
imageNameToImageDataMap = new HashMap<String,byte[]>();
}

Writer writer = null;
try
{
OutputStream fileOutputStream = new FileOutputStream(destFile);
writer = new BufferedWriter(new OutputStreamWriter(fileOutputStream, encoding));
exportReportToStream(writer);
}
catch (IOException e)
{
throw new JRException("Error writing to file : " + destFile, e);
}
finally
{
if (writer != null)
{
try
{
writer.close();
}
catch(IOException e)
{
}
}
}

if (!isEmbeddingImages)
{
Collection<String> imageNames = imageNameToImageDataMap.keySet();
if (imageNames != null && imageNames.size() > 0)
{
if (!imagesDir.exists())
{
imagesDir.mkdir();
}

for(Iterator<String> it = imageNames.iterator(); it.hasNext();)
{
String imageName = it.next();
byte[] imageData = imageNameToImageDataMap.get(imageName);

File imageFile = new File(imagesDir, imageName);

OutputStream fos = null;
try
{
fos = new FileOutputStream(imageFile);
fos.write(imageData, 0, imageData.length);
}
catch (IOException e)
{
throw new JRException("Error writing to image file : " + imageFile, e);
}
finally
{
if (fos != null)
{
try
{
fos.close();
}
catch(IOException e)
{
}
}
}
}
}
}
}


protected StringBuffer exportReportToBuffer() throws JRException
{
StringWriter buffer = new StringWriter();
try
{
exportReportToStream(buffer);
}
catch (IOException e)
{
throw new JRException("Error while exporting report to buffer", e);
}
return buffer.getBuffer();
}

protected XmlNamespace getNamespace()
{
return JASPERPRINT_NAMESPACE;
}

protected void exportReportToStream(Writer writer) throws JRException, IOException
{
version = JRPropertiesUtil.getInstance(jasperReportsContext).getProperty(jasperPrint, JRXmlBaseWriter.PROPERTY_REPORT_VERSION);

xmlWriter = new JRXmlWriteHelper(writer);

xmlWriter.writeProlog(encoding);

xmlWriter.startElement(JRXmlConstants.ELEMENT_jasperPrint);
xmlWriter.addEncodedAttribute(JRXmlConstants.ATTRIBUTE_name, jasperPrint.getName());

List<JRPrintPage> pages = jasperPrint.getPages();
if (pages != null && pages.size() > 0)
{
JRPrintPage page = null;
for(int i = startPageIndex; i <= endPageIndex; i++)
{
if (Thread.interrupted())
{
throw new JRException("Current thread interrupted.");
}

page = pages.get(i);

exportPage(page);
}

if(isRow){
xmlWriter.closeElement();
isRow = false;
}
}

xmlWriter.closeElement();

writer.flush();
}


protected void exportPage(JRPrintPage page) throws JRException, IOException
{
exportElements(page.getElements());

if (progressMonitor != null)
{
progressMonitor.afterPageExport();
}
}

protected void exportElements(Collection<JRPrintElement> elements) throws IOException, JRException
{
if (elements != null && elements.size() > 0)
{
for(Iterator<JRPrintElement> it = elements.iterator(); it.hasNext();)
{
exportElement(it.next());
}
}
}

public void exportElement(JRPrintElement element) throws IOException, JRException
{
if (filter == null || filter.isToExport(element))
{
if (element instanceof JRPrintText)
{
exportText((JRPrintText)element);
}
else if (element instanceof JRPrintFrame)
{
exportFrame((JRPrintFrame) element);
}
}
}

public void exportText(JRPrintText text) throws IOException
{
JRStyle style = text.getStyle();
if (style != null)
{
String styleName = style.getName();
if(!isRow && !isColumn && "TableColumnHeaderTextStyle".equals(styleName)){
xmlWriter.startElement(ELEMENT_columns);
isColumn = true;
columnCount = 0;
}else if(isColumn && ("TableGroupHeaderTextStyle".equals(styleName) || "TableDetailTextStyle".equals(styleName))){
xmlWriter.closeElement();
isColumn = false;
isRow = true;
xmlWriter.startElement(ELEMENT_rows);
}
}
if (isColumn && text.getOriginalText() != null)
{
columnCount++;
xmlWriter.writeCDATAElement(ELEMENT_column, text.getOriginalText(),
JRXmlConstants.ATTRIBUTE_truncateIndex, text.getTextTruncateIndex());
}else if(style != null && !("TableGroupHeaderTextStyle".equals(style.getName())) && isRow){
if(rowCount == 0){
xmlWriter.startElement(ELEMENT_row);
}
rowCount++;
xmlWriter.writeCDATAElement(JRXmlConstants.ELEMENT_text, text.getOriginalText(),
JRXmlConstants.ATTRIBUTE_truncateIndex, text.getTextTruncateIndex());
}

xmlWriter.writeCDATAElement(JRXmlConstants.ELEMENT_textTruncateSuffix, text.getTextTruncateSuffix());
if(rowCount == columnCount){
xmlWriter.closeElement();
rowCount = 0;
}
}

protected void exportFrame(JRPrintFrame frame) throws IOException, JRException
{
setFrameElementsOffset(frame, true);
try
{
exportElements(frame.getElements());
}
finally
{
restoreElementOffsets();
}
}

protected String getExporterPropertiesPrefix()
{
return XML_EXPORTER_PROPERTIES_PREFIX;
}


public String getExporterKey()
{
return XML_EXPORTER_KEY;
}

public JRXmlWriteHelper getXmlWriteHelper()
{
return xmlWriter;
}

protected boolean isNewerVersionOrEqual(String oldVersion)
{
return versionComparator.compare(version, oldVersion) >= 0;
}
}