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

Thursday, 9 January 2014

How to update multiple value of specific embedded document, inside an array, of a specific document in MongoDB?


How to update multiple value of specific embedded document, inside an array, of a specific document in MongoDB?

MongoDB has a limitation of the same.

for more details please find the below link for your information.

https://jira.mongodb.org/browse/SERVER-1243

for example you have a JSON structure like this ...

{
"_id" : ObjectId("52ce2e4c9109b0e2274a388b"),
"address" : {
"street" : "Aurthor Street 1",
"area" : "Area 1",
"city" : "New York 1",
"country" : "UK"
},
"age" : 29,
"commList" : [
{
"userId" : 1,
"firstName" : "Commenter First Name",
"lastName" : "Commenter Last Name",
"commentText" : "Comment Text",
"date" : ISODate("2014-01-09T05:06:20.283Z")
},
{
"userId" : 1,
"firstName" : "Commenter First Name",
"lastName" : "Commenter Last Name",
"commentText" : "Comment Text 2",
"date" : ISODate("2014-01-09T11:59:57.050Z")
}
],
"commentCount" : 2,
"name" : "Jamse Cook"
}


Now the user name is changed and we need to update the it.

If we try using java code like :

DBCollection dbCollection = getCollection();
JacksonDBCollection<Person, String> coll = JacksonDBCollection.wrap(dbCollection, Person.class, String.class);

DBUpdate.Builder builder = new DBUpdate.Builder();
builder.set("commList.$.firstName", "Puneet");

WriteResult<Person, String> result = coll.update(DBQuery.is("commList.userId", 1), builder);
System.out.println("rows updated :: " + result.getN());

It updates the first occurence only.

you can use the below code and run it on mongoshell which will update the all occurances
var runUpdate = function(){
db.test.find({"commList.userId" : 1}).forEach( function(test) {
for(var i in test.commList){
test.commList[i].firstName = 'abhijit';
}
db.test.save(test);
});
};

db.eval(runUpdate);