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