Monday, August 18, 2008

Making Charts using JFreeChart JAVA

Hi All,
The previous articles have guided you how to deal with excel files using JAVA and how to read/write and create charts within excel file. Now I take you through how you can create chart panels in the JAVA frame (AWT/Swing).

The JFree.org provides a way to create chart panels in the JAVA platform. JFreeChart is a Java free chart library which supports pie charts (2D and 3D), bar charts (horizontal and vertical, regular and stacked), line charts, scatter plots, time series charts, high-low-open-close charts, candlestick plots, Gantt charts, combined plots, thermometers, dials and more. JFreeChart can be used in applications, applets, servlets and JSP. You can download the latest version of JFreeChart using the following link: http://www.jfree.org/jfreechart/download.html. JFreeChart requires the JCommon class library. The JCommon runtime jar file is included in the JFreeChart download. You can also download the class library of the JCommon class from here.

The API for JFreeChart is available in the following link:
http://www.jfree.org/jfreechart/api/javadoc/index.html

The below is source code for creating charts using JFreeChart.



import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PiePlot;
import org.jfree.data.general.DefaultPieDataset;

public class ChartDrawDemo extends JFrame{
private static final long serialVersionUID = 1L;
private DefaultPieDataset datasetcls;
private JFreeChart jfccls;
PiePlot ppcls;
public ChartDrawDemo() {
datasetcls = new DefaultPieDataset();
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
}

this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
setVisible(false);
}
});

this.setTitle("Demo Charts");
//this.setSize(700,450);
this.setResizable(false);
this.setLocationRelativeTo(null);
this.setValueClassification("A",new Double(10));
this.setValueClassification("B",new Double(20));

this.setCharClassification("Demo Chart");
this.Show();
}

public void setValueClassification(String title, Double numDouble) {
datasetcls.setValue(title, numDouble);
}
public void setCharClassification(String title) {
jfccls = ChartFactory.createPieChart(title, datasetcls, true, true, false);
ppcls = (PiePlot) jfccls.getPlot();
ppcls.setSectionOutlinesVisible(false);
ppcls.setCircular(true);
ppcls.setLabelFont(new Font("SansSerif", Font.PLAIN, 8));
ppcls.setNoDataMessage("No Data Available");
ppcls.setLabelGenerator(null);
ppcls.setLabelGap(0.02);
}

private JPanel createPanelClassification() {
return new ChartPanel(jfccls,400,400,400,400,400,400,true,true,true,true,true,true);
}

public void Show() {
setLayout(new GridBagLayout());
add(createPanelClassification());
pack();
setLocationRelativeTo(null);
setVisible(true);
}

public static void main(String[] args) {
ChartDrawDemo ce = new ChartDrawDemo();
}
}






Hope you all will find it useful.

Thursday, August 14, 2008

Making Charts in MS Excel using JAVA

Probably the best part of using MS Excel would be the chart as it only allows you to track the record which you’ve entered efficiently, but also it helps you to project the data in a presentable way.

Jxcell provides a way to create charts in MS Excel using JAVA which takes the data from the MS Excel file and create the excel chart in a specific location.

Below is the code for creating charts in Excel using Jxcell.


import com.jxcell.GRChart;
import com.jxcell.RangeRef;
import com.jxcell.View;
import com.jxcell.chart.ChartFormat;

import java.awt.*;

public class ChartFormatTest {

private void createChart(){
View m_view = new View();
RangeRef newRange = null;
try {
m_view.getLock();
m_view.setEntry(1,2,"Jan");
m_view.setEntry(1,3,"Feb");
m_view.setEntry(1,4,"Mar");
m_view.setEntry(1,5,"Apr");
m_view.setEntry(2,1,"Bananas");
m_view.setEntry(3,1,"Papaya");
m_view.setEntry(4,1,"Mango");
m_view.setEntry(5,1,"Lilikoi");
m_view.setEntry(6,1,"Comfrey");
m_view.setEntry(7,1,"Total");
m_view.setEntry(1,6,"time");
m_view.setNumber(2,6,1);
m_view.setNumber(3,6,2);
m_view.setNumber(4,6,3);
m_view.setNumber(5,6,4);
m_view.setNumber(6,6,5);
m_view.setNumber(7,6,6);

for(int col = 2; col <= 5; col++)
for(int row = 2; row <= 7; row++)
m_view.setFormula(row, col, "rand()");
m_view.setFormula(7, 2, "SUM(C3:C7)");
m_view.setSelection("C8:F8");
m_view.editCopyRight();
com.jxcell.GRChart chart = (GRChart)m_view.addObject(com.jxcell.GRObject.eChart, 0, 9.1, 7, 20.4);
chart.setChartType(GRChart.eChartLine);
// chart.setLinkRange("Sheet1!$C$2", false);
chart.addSeries();
chart.setSeriesName(0, "Sheet1!$C$2");
chart.setSeriesYValueFormula(0, "Sheet1!$C$3:$C$7");
chart.setCategoryFormula("Sheet1!$B$3:$B$7");
chart.addSeries();
chart.setSeriesName(1, "Sheet1!$D$2");
chart.setSeriesYValueFormula(1, "Sheet1!$D$3:$D$7");
chart.addSeries();
chart.setSeriesName(2, "Sheet1!$E$2");
chart.setSeriesYValueFormula(2, "Sheet1!$E$3:$E$7");
chart.addSeries();
chart.setSeriesName(3, "Sheet1!$F$2");
chart.setSeriesYValueFormula(3, "Sheet1!$F$3:$F$7");
chart.getChart().validateData();
chart.setAxisTitle(GRChart.eXAxis, 0, "Category");
chart.setAxisTitle(GRChart.eYAxis, 0, "Amount");
// set fill color
ChartFormat cf = chart.getChartFormat();
cf.setPattern((short)1);
cf.setPatternFG(Color.LIGHT_GRAY);
chart.setChartFormat(cf);
cf = chart.getPlotFormat();
cf.setPattern((short)1);
cf.setPatternFG(new Color(204, 255, 255));
chart.setPlotFormat(cf);
cf = chart.getAxisFormat(GRChart.eXAxis, 0);
cf.setFontSizeInPoints(8.5);
chart.setAxisFormat(GRChart.eXAxis, 0, cf);
cf = chart.getAxisFormat(GRChart.eYAxis, 0);
cf.setFontSizeInPoints(8.5);
chart.setAxisFormat(GRChart.eYAxis, 0, cf);
cf = chart.getSeriesFormat(0);
cf.setLineStyle(1);
cf.setLineWeight(3*20);
cf.setLineColor((new Color(0, 0, 128)).getRGB());
cf.setMarkerAuto(false);
cf.setMarkerStyle((short)0);
chart.setSeriesFormat(0, cf);
cf = chart.getSeriesFormat(1);
cf.setLineStyle(1);
cf.setLineWeight(3*20);
cf.setLineColor((new Color(255, 0, 255)).getRGB());
cf.setMarkerAuto(false);
cf.setMarkerStyle((short)0);
chart.setSeriesFormat(1, cf);
cf = chart.getSeriesFormat(2);
cf.setLineStyle(1);
cf.setLineWeight(3*20);
cf.setLineColor((new Color(255, 255, 0)).getRGB());
cf.setMarkerAuto(false);
cf.setMarkerStyle((short)0);
chart.setSeriesFormat(2, cf);
cf = chart.getSeriesFormat(3);
cf.setLineStyle(1);
cf.setLineWeight(3*20);
cf.setLineColor((new Color(0, 255, 255)).getRGB());
cf.setMarkerAuto(false);
cf.setMarkerStyle((short)0);
chart.setSeriesFormat(3, cf);
cf = chart.getMajorGridFormat(GRChart.eYAxis, 0);
cf.setLineStyle(2);
cf.setLineColor((new Color(255, 0, 0)).getRGB());
cf.setLineAuto(false);
chart.setMajorGridFormat(GRChart.eYAxis, 0, cf);
chart.setLegendPos(ChartFormat.eLegendPlacementTop);
cf = chart.getLegendFormat();
cf.setFontBold(true);
cf.setFontSizeInPoints(8);
chart.setLegendFormat(cf);
m_view.write("C:\\out.xls", View.eFileExcel);
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
m_view.releaseLock();
}
}
public static void main(String args[]) {
ChartFormatTest cft = new ChartFormatTest(); cft.createChart();
}
}


Hope you all will find it useful.

Writing in MS Excel through Jxcell

In my previous articles of “Writing in MS Excel”, I gave you the overview of how you can write into it through POI package. There is another API available Jxcell, which will guide you the same thing, but in different way. You can download the latest version of Jxcell using following link:
http://www.jxcell.net/
The following code will guide you how to deal with MS Excel using Jxcell.

import com.jxcell.CellFormat;
import com.jxcell.TextWithFormat;
import com.jxcell.View;
import com.jxcell.designer.Designer;

import java.awt.*;

public class TextFormattingTest {

private void doTextFormatting(){
View m_view = new View();
try {
m_view.setText(0,0,"Hello, you are welcome!");
m_view.setColWidth(0, 36*256);
m_view.setRowHeight(0, 120*20);
CellFormat rangeStyle = m_view.getCellFormat();
rangeStyle.setOrientation((short)45);
m_view.setCellFormat(rangeStyle);
TextWithFormat[] tf = new TextWithFormat[4];
tf[0] = new TextWithFormat(m_view);
tf[1] = new TextWithFormat(m_view);
tf[2] = new TextWithFormat(m_view);
tf[3] = new TextWithFormat(m_view);
tf[0].setFontItalic(true);
tf[0].setStartPos(0);
tf[0].setFontColor(Color.BLUE.getRGB());
tf[1].setFontBold(true);
tf[1].setFontSize(16*20);
tf[1].setStartPos(7);
tf[2].setFontUnderline(true);
tf[2].setStartPos(11);
tf[2].setFontColor(Color.GREEN.getRGB());
tf[3].setFontSize(14*20);
tf[3].setStartPos(14);
m_view.setTextFormat(tf);
m_view.write("C:/TextFormatting.xls", View.eFileExcel);
Designer.newDesigner(m_view);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
TextFormattingTest tft = new TextFormattingTest();
tft.doTextFormatting();
}
}






The next section will guide you how to create charts using Jxcell.

Reading From MS Excel using JAVA

The previous article has shown us how to write or populate the excel files. In this article, I walk through the steps of code of how to read from MS Excel file all using JAVA.


The steps for reading from MS Excel files are:
1. Opening the file with fileinputstream and opening the workbook of that excel file with the help of POI package.
2. Opening the HSSF sheet and HSSFcell to that row and column.
3. Get the value of that cell.



import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class JavaExcelRead{
HSSFWorkbook workBook;
HSSFSheet sheet;
HSSFRow row;
HSSFCell cell;
FileInputStream fileInputStream;
HSSFWorkbook workbook;

JavaExcelRead(){
}

public void readFromExcelFile(){
double cellVal = 0.0;
// getting all the data from sheet
try{
FileInputStream fileInputStream = new FileInputStream("C:\\Demo.xls");
HSSFWorkbook workBook = new HSSFWorkbook(fileInputStream);
HSSFSheet sheet = workBook.getSheet("Demo");
HSSFRow row = sheet.getRow(0);
HSSFCell cell = null;
for(int i=0;i"lessthanequal"1;i++){
row = sheet.getRow(i);
for(int j=0;j"lessthanequal"1;j++){
cell = row.getCell((short)j);
System.out.println("Data is: "+cell.getStringCellValue());
}
}
fileInputStream.close();
}catch(IOException ioe){
ioe.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}

public static void main(String args[]) {
JavaExcelRead jer = new JavaExcelRead();
jer.readFromExcelFile();
}
}

Hope you will find it useful.

Writing in MS Excel through JAVA using POI

Whether you have account information, data for employees, students, salary slips, calculations sheets for tax, Microsoft Excel is the best editor to compile such kind of things. The person whether he is from IT background or non-IT background, he feels comfortable working with MS Excel. The Jakarta POI (Poor Obfuscation Implementation) API is a fantastic way for Java programmers to access Microsoft document formats. The most mature API from Jakarta POI is the HSSF (Horrible Spreadsheet Format) API, which accesses Microsoft Excel documents.
POI terminology:

The key terms associated with Jakarta POI are as follows:
POIFS (Poor Obfuscation Implementation File System): Java APIs for reading and writing OLE (Object Linking and Embedding) 2 compound document formats
HSSF (Horrible Spreadsheet Format): Java API to read Microsoft Excel
HDF (Horrible Document Format): Java API to read and write Microsoft Word 97
HPSF (Horrible Property Set Format): Java API for reading property sets using (only) Java
Here is the code which can really guide you to use the POI package to write into the Excel file.

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class JavaExcelPOI{
BufferedWriter out;
File file = null;
FileOutputStream fileoutputstream;
HSSFWorkbook workbook;
HSSFCell cell;
HSSFRow row;
HSSFSheet sheet;
HSSFFont font;
HSSFCellStyle cellStyle;
int i = 0;
int j = 1;
JavaExcelPOI() {
}
private void doWriteIntoExcelFile(){
try {
fileoutputstream = new FileOutputStream(new File("C:\\Demo"+".xls"));
workbook = new HSSFWorkbook();
sheet = workbook.createSheet("Demo");
String header[] = {"Header1","Header2"};
row = sheet.createRow((short)0);
cellStyle = workbook.createCellStyle();
font = workbook.createFont();
font.setColor(HSSFFont.COLOR_RED);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
cellStyle.setFont(font);
for(i = 0;i"lessthan"header.length;i++){
cell = row.createCell((short)i);
cell.setCellValue(header[i]);
cell.setCellStyle(cellStyle);
}
String celldetails = "";
row = sheet.createRow((short)j);
for(i =0;i"lessthan"header.length;i++){
cell = row.createCell((short)i);
celldetails = "Cell Value";
cell.setCellValue(celldetails+i);
}
j = j+1;
workbook.write(fileoutputstream);
} catch(Exception se){
se.printStackTrace();
}

}

public static void main(String args[]) {
JavaExcelPOI jePOI= new JavaExcelPOI();
jePOI.doWriteIntoExcelFile();
}
}
You can download the latest version of the POI package from the following link:
http://poi.apache.org/index.html.
You can also view the API documentation of the POI package:
http://poi.apache.org/apidocs/

The code is also using the functionality of the POI packages that cause the cell to define with definite style and font.

The next sections will guide you through more details about it.

Monday, August 11, 2008

Java Class to Implement Email

Hi, The java developers can use the following code to send email through code. The developers should have smtp (Simple Mail Transfer Protocol) server, where she/he can authenticate her/him self with the help of her/his credentials. The default port the smtp server normally uses is 25. The developers can check it whether it works or not. Here we are going to use the default mail package of sun. You can download the javax.mail package from the following link: http://java.sun.com/products/javamail/.
The API is also available through the following link:
http://java.sun.com/products/javamail/javadocs/index.html?javax/mail/package-summary.html

The following code is useful for different scenarios. For example there are four constructors where you can define the possible situations of having cc, attachment. The possible combinations are:
SUBJECT, FROM, TO, CC, ATTACHMENT, BODY.
SUBJECT, FROM, TO, ATTACHMENT, BODY.
SUBJECT, FROM, TO, CC, BODY.
SUBJECT, FROM, TO, BODY.

The code does not authenticate the email id. So you can easily mention any non existing email id also.
package mailpackage;


import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Flags;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import javax.mail.internet.MimeMultipart;


public class ErrorMail {

String subject;
String from;
String[] to;
String[] cc;
String attachmentpath;
String body;

/**
* @param subject SUBJECT
* @param from FROM
* @param to TO
* @param cc CC
* @param attachmentpath ATTACHMENTPATH
* @param body BODY
*/

public ErrorMail(String subject,String from,String[] to,String[] cc,String attachmentpath,String body){
this.subject = subject;
this.from = from;
this.to = to;
this.cc = cc;
this.attachmentpath = attachmentpath;
this.body = body;
}

/ *
* @param subject SUBJECT
* @param from FROM
* @param to TO
* @param attachmentpath ATTACHMENTPATH
* @param body BODY
*/



public ErrorMail(String subject,String from,String[] to,String attachmentpath,String body){
this.subject = subject;
this.to = to;
this.attachmentpath = attachmentpath;
this.body = body;
this.from = from;
}


/**
* @param subject SUBJECT
* @param from FROM
* @param to TO
* @param cc CC
* @param body BODY
*/

public ErrorMail(String subject,String from,String[] to,String cc[],String body){
this.subject = subject;
this.to = to;
this.cc = cc;
this.body = body;
this.from = from;
}




/**
* @param subject SUBJECT
* @param from FROM
* @param to TO
* @param body BODY
*/


public ErrorMail(String subject,String from,String[] to,String body){
this.subject = subject;
this.to = to;
this.body = body;
this.from = from;
}




public void run() {
try{
Session session = getSession();
MimeMessage message = new MimeMessage(session);
session.setDebug(true);
InternetAddress[] addressTO = new InternetAddress[to.length];
for(int i=0;i < to.length;i++){
System.out.println("to is "+to[i]);
addressTO[i] = new InternetAddress(to[i]);
}
message.setRecipients(RecipientType.TO,addressTO);
System.out.println("cc "+cc);
if(cc!=null){
InternetAddress[] addressCC = new InternetAddress[cc.length];
for(int i=0;i < cc.length;i++){
System.out.println("cc is "+cc[i]);
addressCC[i] = new InternetAddress(cc[i]);
}
message.setRecipients(RecipientType.CC,addressCC);
}
System.out.println("from : "+from);
message.addFrom(new InternetAddress[] { new InternetAddress(from) });
message.setSubject(subject);
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText(body);

Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);
System.out.println("attachmentpath "+attachmentpath);
if(attachmentpath!=null){
MimeBodyPart mbp2 = new MimeBodyPart();
FileDataSource fds = new FileDataSource(attachmentpath);
mbp2.setDataHandler(new DataHandler(fds));
mbp2.setFileName(fds.getName());
mp.addBodyPart(mbp2);
}

message.setContent(mp);

Transport.send(message);
}catch(MessagingException me){
me.printStackTrace();
}
}

private Session getSession() {
Authenticator authenticator = new Authenticator();

Properties properties = new Properties();
properties.setProperty("mail.smtp.submitter", authenticator.getPasswordAuthentication().getUserName());
properties.setProperty("mail.smtp.auth", "true");

properties.setProperty("mail.smtp.host",”myhost.smtpserver”);
properties.setProperty("mail.smtp.port",”myhostport”);

return Session.getInstance(properties, authenticator);
}

private class Authenticator extends javax.mail.Authenticator {
private PasswordAuthentication authentication;

public Authenticator() {
String username =”validuserofthesmtpserver”;
String password =”password”;
authentication = new PasswordAuthentication(username, password);
}

protected PasswordAuthentication getPasswordAuthentication() {
return authentication;
}
}

public static void main(String[] args) throws MessagingException {
ErrorMail mwpa1 = new ErrorMail("SUBJECT","abc@domain.com",new String[] {"xyz @domain.com","efg @domain.com"},"BODY");
mwpa1.run();

ErrorMail mwpa2 = new ErrorMail("SUBJECT","abc@domain.com",new String[] {"pqr@domain.com","efg@domain.com","xyz@domain.com"},"C:\\attachment.txt ","Body");
mwpa2.run();
ErrorMail mwpa3 = new ErrorMail("SUBJECT","abc@domain.com",new String[] {"abc@domain.com","efg@domain.com","pqr@domain.com"},new String[] {"abc@domain.com","pqr@domain.com"}," Body");
mwpa3.run();
ErrorMail mwpa4 = new ErrorMail("SUBJECT","abc@domain.com",new String[] {"abc@domain.com","efg@domain.com","pqr@domain.com","xyz @dsomain.com"},"Body");
mwpa4.run();

}
}

Hope you all will find it useful.

JUnit Test Case

One of the tenets of agile development is continuous testing. Agile development states that code should be tested as often as possible, during development. Not only should the new module be tested, the whole application should be tested each time a new module or new feature is added to it, to ensure that the application is not broken. In case of manual testing, if testing frequency is increased, tester moral will become very low. As the number of tests to be executed increases, testers may miss executing a few tests, resulting in problems at later stages. To overcome some of these problems, usage of automated testing in the development cycle is crucial. Though automated testing will not identify all code bugs, it will overcome the problem of low morale due to frequent execution of the tests. Usually when automated tests are executed a test log is generated. This test log is analyzed for success or failure of the tests. Such test logs can be circulated to the customer, to assure the customer that the developed code does work as expected under test conditions. Such an exchange of information will build customer’s confidence in the development team and the development process.
JUnit

JUnit, as the name suggests is an API for developing unit test cases using Java. Unit tests are used to test the business logic of the application.

Each test case is derived from the TestCase class. Each unit test starts with the prefix “test”. The success or failure of each test is determined by “assert”ing the result. If the result matches expectation, the test is a success. Else the test is a failure.

Key Points:

JUnit is open source project and hence it is free !!
Fast development while increasing quality of code.
Easy to understand.
Integrated with IDE’s like Eclipse and Ant, makes it easy to use and inexpensive to write.
Provides immediate feedback about code changes.
Regression testing can be automated using Junit test suites.
Increases stability of software.
Without going into the much details, lets have a look how the junit test cases are prepared in real case:

Writing Sample TestCase:

Test Class:
public class Demo {
static public int add(int a, int b) {
return a + b;
}
}

JUNIT TestCase

import junit.framework.*;
public class DemoTest extends TestCase {
setUp() { }
tearDown() { }
public void testAdd() {
int no1 = 5;
int no2 = 5;
int total = 10;
int addResult = 0;
addResult = Math.add(no1, no2);
assertEquals(total,addResult);
}
}


JUnit TestSuite:

JUnit TestSuite includes several test cases. It allows multiple test cases to run in one go. It also automates regression testing process.

To write a test suite, follow these steps:
ü Write a Java class that defines a static suite() factory method that creates a TestSuite containing all the tests.
ü Optionally define a main() method that runs the TestSuite in batch mode.


public class JUnitPracSuite {
public static void main(String[] args) {
junit.textui.TestRunner.run(suite());
}
public static Test suite() {
TestSuite suite = new TestSuite("Test for Demo");
suite.addTestSuite(Demo.class);
//More TestCase classes to be added.
return suite;
}
}


Running a TestSuite will automatically run all of its subordinate TestCase instances and TestSuite instances. Running a TestCase will automatically invoke all of its public testXXX() methods. JUnit provides both a textual and a graphical user interface. The interface provided are No. of Test cases Run, Simple sompletion status, Error if any.

To run textual user interface----java junit.textui.TestRunner MathsClassTest
To run graphical user interface----java junit.swingui.TestRunner MathsClassTest
To run TestSuite----java junit.swingui.TestRunner JUnitPractSuite

TestCase object extends Assert which provides way to judge if a test has succeeded or failed:

Types of Assert statements:
assertEquals: Provides a series of overloads that allows to test if an actual value matches the expected one.
assertFalse: Use this if the function will always return false (fails if it receives true)
assertNotNull: If method returns null in the event of failure use this to check to see if it succeeds.
assertNotSame: If method is supposed to return an element from a list, use this to check if the element returned is the one from the actual list
assertNull: If method returns null in the event of failure, use this to check to see if it fails
fail: Will fail the test, use this in conjunction with conditionals
failNotEquals: Essentially the same as assertEquals but will fail the test if they aren’t equal instead of causing an error
failNotSame: Essentially the same as assertNotSame except instead of causing an error it will cause a failure

Suggestions for arranging tests in development environment:

Create test cases in the same package as the code under test.
To avoid combining application and testing code in your source directories, create a mirrored directory structure aligned with the package structure that contains the test code.
For each Java package in your application, define a TestSuite class that contains all the tests for validating the code in the package.
Define similar TestSuite classes that create higher-level and lower-level test suites in the other packages (and sub-packages) of the application.
Make sure your build process includes the compilation of all tests.


To Watch:

The software does well those things that the tests check.
Test a little, code a little, test a little, code a little...
Make sure all tests always run at 100%.
Write tests for the areas of code with the highest probability of breakage.
Write tests that have the highest possible return on your testing investment.
If you find yourself debugging using System.out.println(), write a test to automatically check the result instead.
Write unit tests before writing the code and only write new code when a test is failing.

Download JUnit latest version from http://www.junit.org/home
Hope you all will find it useful.

Friday, August 8, 2008

Java class to capture frame in JPG format

Here is the thing that enables java developers to capture the frame into a picture. To capture a frame, you need to use BufferedImage class of the java.awt.image package.

The BufferedImage subclass describes an Image with an accessible buffer of image data. A BufferedImage is comprised of a ColorModel and a Raster of image data. The number and types of bands in the SampleModel of the Raster must match the number and types required by the ColorModel to represent its color and alpha components. All BufferedImage objects have an upper left corner coordinate of (0, 0). Any Raster used to construct a BufferedImage must therefore have minX=0 and minY=0.

You can go to the following link to see the API of BufferedImage class.
http://java.sun.com/j2se/1.5.0/docs/api/java/awt/image/BufferedImage.html

A demo code for capturing the frame into picture is given below.

Source code:

import java.awt.AWTException;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;


public class Fig extends javax.swing.JFrame implements ActionListener{

private JButton jButton1 = null;
private JLabel jLabel1 = null;
public Fig(){
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
setLayout(new FlowLayout());
jLabel1 = new JLabel("Demo");
jButton1 = new JButton("Demo");

this.add(jLabel1);
this.add(jButton1);
jButton1.setActionCommand("Demo");
jButton1.addActionListener(this);
this.setTitle("Figure");
this.setSize(200,100);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setVisible(true);
}

public void actionPerformed(ActionEvent ae){
if(ae.getActionCommand().equals("Demo")){
try {
this.createImage(this,"C:\\Demo.jpg");
} catch (AWTException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
// Methods to create Image correspoding to the frame.
public static BufferedImage createImage(Component component, String fileName)
throws AWTException, IOException {
Point p = new Point(0, 0);
SwingUtilities.convertPointToScreen(p, component);
Rectangle region = component.getBounds();
region.x = p.x;
region.y = p.y;
return Fig.createImage(region, fileName);
}

public static BufferedImage createImage(Rectangle region, String fileName)
throws AWTException, IOException {
BufferedImage image = new Robot().createScreenCapture( region );
Fig.writeImage(image, fileName);
return image;
}

public static void writeImage(BufferedImage image, String fileName)
throws IOException {
if (fileName == null) return;
int offset = fileName.lastIndexOf( "." );
String type = offset == -1 ? "jpg" : fileName.substring(offset + 1);

ImageIO.write(image, type, new File( fileName ));
}
// Methods to create Images
//End
public static void main(String args[]){
Fig fig = new Fig();
}
}


The highlighted portion of the code is responsible for capturing the frame into picture. There are two createImage methods in the code.

The first one converts a point from the component’s coordinate system to screen coordinates. Then it gets the bound of the component in the form of rectangle object. The bound specify the width, height and location relative to its parents.

It passes the location/region and size details to the second createImage method. The second one creates the image containing the pixels read from the screen corresponding to the region.

The writeImage method writes it to the specific file in jpg format with the help of write method of ImageIO class.




Practical Use:

It is quite useful in standalone applications.

The application is also useful, whenever you want some frame to be shown to a particular group of people. If you want some chart frame or any status frame which indicates some record over the past few months, you can easily capture it in jpg format and send it to concerned persons.



Hope you all will find it useful.

Total Pageviews