Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Thursday, March 14, 2013

Jasper Reports tips and tricks

Jasper Reports basic steps:

1. Design report in iReport designer
2. Save the the template  - jrxml file
3. Compile the jrxml to jasper
4. Run from iReport or integrate it with a java program

Load the jasper report from .jasper file

//reportData is an instance of List
(JasperReport)jasperReport = JRLoader.loadObjectFromLocation(jasperReportName);

JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport,parameters,new JRBeanCollectionDataSource(reportData));


//Export into pdf format
byte[] pdfFile = JasperExportManager.exportReportToPdf(jasperPrint);


//Export into csv format
JRCsvExporter exporter = new JRCsvExporter();
StringBuffer buffer = new StringBuffer();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STRING_BUFFER,buffer);
exporter.exportReport();

//Export into HTML format
JRHtmlExporter exporter=new JRHtmlExporter();
StringBuffer buffer = new StringBuffer();
  
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STRING_BUFFER, buffer);
exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, false);
//following parameters are used to avoid the page breaks, empty spaces and display tabular data better in html compare to pdf
exporter.setParameter(JRHtmlExporterParameter.IGNORE_PAGE_MARGINS, true);
exporter.setParameter(JRHtmlExporterParameter.ZOOM_RATIO, 1.5F);
exporter.setParameter(JRHtmlExporterParameter.BETWEEN_PAGES_HTML, "");
exporter.setParameter(JRHtmlExporterParameter.FRAMES_AS_NESTED_TABLES,true);
exporter.setParameter(JRHtmlExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, true);
exporter.exportReport();
   
iReport Designer tips n tricks:


Create paremeters, fields in the iReport designer and make sure the name match the exact names in the javabean if you plan to use java bean as datasource.

List is also very useful if you do not want to use a subreport.
To create a list, drag list component from the pallet and right-click select datasource :
new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($F{fieldname})
go to the dataset1 and create all necessary fields and drag and drop them to the area.


If you want to display certain area when some conditions are met, select the band properties for that particular group or section and modify "print when expression" to new Boolean($F{fieldname}>0) for e.g.

Friday, September 21, 2012

Unit Testing Java code using mock objects (mockito)

Let's start with an example. We have a Conversion class to convert temperature from Fahrenheit to Celcius.

Following is the Java code :
class Fahrenheit {
 float f=0;
 public Fahrenheit(float f)
 {
  this.f=f;
 }
 public float getFahrenheit()
 {
  return f;
 }
 public void setFahrenheit(float f)
 {
  this.f=f;
 }
}

class Celcius {
 float celcius=0;
 public Celcius(Float c)
 {
  System.out.println("Celcius="+c);
  celcius=c;
 }
 public Float getCelcius()
 {
  return celcius;
 }

 public void setCelcius(Float c)
 {
  System.out.println("Celcius="+c);
  celcius=c;
 }
}

public class Convert {
 
 private float convertToFahrenheit(Celcius c)
 {
  return (float) ((c.getCelcius()*1.8)+32);
 }
 private float converToCelcius(Fahrenheit f)
 {

  return ((f.getFahrenheit()-32)*5/9);
 }

 public float convert(Fahrenheit f, Celcius c)
 {
  if(f!=null)
   return converToCelcius(f);
  else
   return convertToFahrenheit(c);
 }

}

1.Create Mock Objects
Object obj=mock(SomeclassName.class)

2. Setup return values on this object
when(obj.somemethod(param)).thenReturn(100);

3. Call a method under test
obj.aMethod()

4. Verify if a particular method is called and returns a certain value
verify(obj).bMethod(abc,anyObject());

For our example above, the test code looks like below

 @Test
 public void test() {

  Convert conversion = mock(Convert.class);
  Celcius celcius=mock(Celcius.class);
  Fahrenheit fahrenheit=mock(Fahrenheit.class);
  when(celcius.getCelcius()).thenReturn((float) 20.0);


  float val=conversion.convert(fahrenheit,celcius);

  verify(conversion).convertToFahrenheit(celcius);
 }

Thursday, March 29, 2007

XML, XSLT

XML Parsing using SAX Parser

Write a java class that extends DefaultHandler with following methods:

import org.xml.sax.*;
import org.xml.sax.helpers.*;

public class MyParser extends DefaultHandler {
..
public void startDocument( ) throws SAXException
public void endDocument( ) throws SAXException
public void startElement( String namespaceURI,
String localName,
String qName,
Attributes attr ) throws SAXException {
System.out.println( “Start element : “+localName);
for ( int i = 0; i <>
System.out.println( " ATTRIBUTE: " +
attr.getLocalName(i) +
" VALUE: " +
attr.getValue(i) );
}

public void endElement( String namespaceURI,
String localName,
String qName ) throws SAXException {

System.out.println( “End element : “+localName);
}
public void characters( char[] ch, int start, int length )
throws SAXException {

String val=null;
val = new String(ch, start, length);
if(val!=null)
System.out.println(“Characters :“+val);

}

Use above in your program as follows :
try {
// Create SAX 2 parser...
XMLReader xr = XMLReaderFactory.createXMLReader();
// Set the ContentHandler...
xr.setContentHandler( new QueryParser() );
// Parse the file...
InputSource is = new InputSource(new StringReader(Test.getXMLQueryString()));
xr.parse( is );

}catch ( Exception e ) {
e.printStackTrace();
}


Xslt for webRowSet to html

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:wrs="http://java.sun.com/xml/ns/jdbc" version="1.0">
<xsl:template match="/">
<h2>Query Results</h2>
<h3> Total Count : <xsl:value-of select="count(wrs:webRowSet/wrs:data/wrs:currentRow)"/> </h3>
<table border="1">
<tr bgcolor="lightgray">
<xsl:for-each select="wrs:webRowSet/wrs:metadata/wrs:column-definition">
<th><xsl:value-of select="wrs:column-label"/></th>
</xsl:for-each>
</tr>

<!-- fill in the table rows -->

<xsl:for-each select="wrs:webRowSet/wrs:data/wrs:currentRow">
<tr>
<xsl:for-each select="wrs:columnValue">
<td><xsl:value-of select="."/></td>
</xsl:for-each>
</tr>
</xsl:for-each>
</table>
</xsl:template>
</xsl:stylesheet>

Other important xslt:


If you have a xml like :
<list>
<val>10</val>
<val>100</val>
<val>30</val>
</list>
To print each value in a comma separated list :
<xsl:template match="/list">
<xsl:value-of select="val[1]"/>,
<xsl:value-of select="val[2]"/>,
<xsl:value-of select="val[3]"/>,
</xsl:template>