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

Tuesday, 7 January 2014

Example of MongoDB with MongoJack

There is need of java mapper to the mongo object and MongoJack is very helpful in the same
to achieve the objective. It uses Jackson as the Java JSON mapper.

You need to add the following jars.

1.  bson4jackson-2.1.0.jar
2.  commons-io-2.4.jar
3.  hamcrest-core-1.3.jar
4.  hamcrest-library-1.3.jar
5.  jackson-annotations-2.1.2.jar
6.  jackson-core-2.1.3.jar
7.  jackson-databind-2.1.3.jar
8.  mongo-java-driver-2.11.3.jar
9.  mongojack-2.0.0-RC5.jar
10. persistence-api-1.0.2.jar


In the example you will find how add, update, updating Embedded field, find and find with some criteria using the MongoJack.


public static void main(String[] args) {
create();
findOne();
updateEmbeddedField();
update();
findOne();
findWithCriteria();
}

public static void create(){

DBCollection dbCollection = getCollection();

JacksonDBCollection<Person, String> coll = JacksonDBCollection.wrap(dbCollection, Person.class,
       String.class);
Person person = getPerson();
WriteResult<Person, String> result = coll.insert(person);
Person p = coll.findOne();
Address ad = p.getAddress();
System.out.println("Create o/p ->>  name :: " + p.getName() + " age :: " + p.getAge() + " area :: "+ ad.getArea());
}

public static void updateEmbeddedField(){

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

DBUpdate.Builder builder = new DBUpdate.Builder();
builder.set("address.area", "Pune");

Person result = coll.findAndModify(DBQuery.is("name", "Jamse Cook"), null, null, false, builder, false, false);
Address ad = result.getAddress();
System.out.println("updateEmbeddedField o/p ->> name :: " + result.getName() + " age :: " + result.getAge() + " area :: "+ ad.getArea());
}

public static void update(){

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

DBUpdate.Builder builder = new DBUpdate.Builder();
builder.set("name", "Abhijit");

Person result = coll.findAndModify(DBQuery.is("name", "Jamse Cook"), null, null, false, builder, false, false);
Address ad = result.getAddress();
System.out.println("update o/p  ->>  name :: " + result.getName() + " age :: " + result.getAge() + " area :: "+ ad.getArea());
}

public static void findOne(){

DBCollection dbCollection = getCollection();
JacksonDBCollection<Person, String> coll = JacksonDBCollection.wrap(dbCollection, Person.class,
       String.class);
Person result = coll.findOne();
Address ad = result.getAddress();
System.out.println("find o/p ->> name :: " + result.getName() + " age :: " + result.getAge() + " area :: "+ ad.getArea());

}

public static void findWithCriteria(){

DBCollection dbCollection = getCollection();
JacksonDBCollection<Person, String> coll = JacksonDBCollection.wrap(dbCollection, Person.class,
       String.class);
Person result = coll.findOne(DBQuery.is("name", "Abhijit"));
Address ad = result.getAddress();
System.out.println("findWithCriteria o/p ->>  name :: " + result.getName() + " age :: " + result.getAge() + " area :: "+ ad.getArea());

}

private static DBCollection getCollection() {
MongoClient mongoClient = null;
try {
mongoClient = new MongoClient( "localhost" , 27017 );
} catch (UnknownHostException e) {
e.printStackTrace();
}
DB db = mongoClient.getDB( "jack" );
DBCollection dbCollection = db.getCollection("test");
return dbCollection;
}

private static Person getPerson(){

Person person = new Person();
person.setName("Jamse Cook");
person.setAge(29);

Address address = new Address();
address.setArea("Area 1");
address.setCity("New York 1");
address.setStreet("Aurthor Street 1");
address.setCountry("UK");

person.setAddress(address);

return person;
}

The output on the java console is :


Create o/p ->>  name :: Jamse Cook age :: 29 area :: Area 1
find o/p ->> name :: Jamse Cook age :: 29 area :: Area 1
updateEmbeddedField o/p ->> name :: Jamse Cook age :: 29 area :: Area 1
update o/p  ->>  name :: Jamse Cook age :: 29 area :: Pune
find o/p ->> name :: Abhijit age :: 29 area :: Pune
findWithCriteria o/p ->>  name :: Abhijit age :: 29 area :: Pune

And the output on the mongo shell is :


db.test.find().pretty();
{
"_id" : ObjectId("52cce4e19109c56d473c46eb"),
"address" : {
"area" : "Pune",
"city" : "New York 1",
"country" : "UK",
"street" : "Aurthor Street 1"
},
"age" : 29,
"name" : "Abhijit"
}






Saturday, 4 January 2014

Adding JSON to MongoDB Using Java

we can add JSON directly to mongo using Java.

1. In the first example will add josn String directly as shown in the code below.


public static void jsonExmple(){
String jsonString = "{'Name' : 'James Smith', 'Age' : 29," +
 "'Address' : {'area' : 'Area', 'city' : 'New York', 'country' : 'USA'} }";

MongoClient mongoClient = null;
try {
mongoClient = new MongoClient( "localhost" , 27017 );
} catch (UnknownHostException e) {
e.printStackTrace();
}
DB db = mongoClient.getDB( "testJson" );
DBCollection json = db.getCollection("json");
DBObject dbObject = (DBObject)JSON.parse(jsonString);

json.insert(dbObject);

DBCursor jsonDoc = json.find();
while (jsonDoc.hasNext()) {
System.out.println(jsonDoc.next());
}
}

the output on the mongo console would be like :


db.json.find().pretty();
{
"_id" : ObjectId("52c7fead91090c7db49d1604"),
"Name" : "James Smith",
"Age" : 29,
"Address" : {
"area" : "Area",
"city" : "New York",
"country" : "USA"
}
}

2. Another case would be, convert the Java object to json and add the json to mongoDB as shown below.
I have used the google json api to convert Java object to Json.


public static void jsonExample(){

MongoClient mongoClient = null;
try{
mongoClient = new MongoClient( "localhost" , 27017 );
DB db = mongoClient.getDB( "testJson" );
DBCollection json = db.getCollection("json");

Person person = new Person();
person.setName("Jamse Cook");
person.setAge(29);

Address address = new Address();
address.setArea("Area");
address.setCity("New York");
address.setStreet("Aurthor Street");
address.setCountry("USA");

person.setAddress(address);

Gson gson = new Gson();
             String jsonString = gson.toJson(person);
             System.out.println(" print the json " + jsonString);
         
             DBObject dbObject = (DBObject)JSON.parse(jsonString);
             json.insert(dbObject);

}catch (Exception e) {

}
}

the output on the mongo console would be like :


{
"_id" : ObjectId("52c7fc479109fd33fdc45793"),
"name" : "Jamse Cook",
"age" : 29,
"address" : {
"street" : "Aurthor Street",
"area" : "Area",
"city" : "New York",
"country" : "USA"
}
}





Monday, 16 December 2013

How to read the array data in mongoDB, modify the array data and update the same in mongoDB.



How to read the arrat data in mongoDB, modify the array data and update the same in mongoDB.

public static void mongoArrayExample(){
DBCursor cursor = null;
MongoClient mongoClient = null;
try {

mongoClient = new MongoClient("localhost", 27017);
DB db = mongoClient.getDB("school");
DBCollection students = db.getCollection("students");

BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("_id" , 0);

cursor = students.find(whereQuery);
Map<String, Double> map = new HashMap<String, Double>();
while (cursor.hasNext()){
BasicDBObject result = (BasicDBObject) cursor.next();
BasicDBList  scores = (BasicDBList) result.get("scores");
// Reading the data from Array.
        for(int j = 0; j< scores.size(); j++)
        {
        // Reading the individual records
            String type = (String) ((BSONObject) scores.get(j)).get("type");
            Double score = (Double) ((BSONObject) scores.get(j)).get("score");
            if(map.containsKey("homework")){
            map.put(type, score);
            }
        }
}

List<BasicDBObject> scores = new ArrayList<BasicDBObject>();
  Set<String> str = map.keySet();
  for (String string : str) {
  BasicDBObject obje = new BasicDBObject();
  obje.put("type", string);
  obje.put("score", map.get(string));
  scores.add(obje);
}

  // Modifying the array
  BasicDBObject updateQuery = new BasicDBObject();
  updateQuery.append("$set", new BasicDBObject().append("scores", scores));
  students.update(whereQuery, updateQuery);

}catch (Exception e) {
}
}