Wednesday, 13 April 2011

Jfreechart : Charting tools in java

iText is a wonderful library if you want to generate PDFs in Java. It comes with a huge set of API to create/manage a PDF file. IText can be used in cases like : how to generate a pdf file in itext and also how to merge two pdf  or splitting pdf files using itext.
In this tutorial we will see how to generate Pie charts and Bar charts in Java using iText and jFreeChart library. First a brief note about jFreeChart.
JFreeChart is a free 100% Java chart library that makes it easy for developers to display professional quality charts in their applications. It gives a wide range of API to generate charts and graphs in Java.

Step 1: Download required Jar files

For this example we will need following jar files.
  • iText-2.1.5.jar (download)
  • jcommon-1.0.16.jar
  • jfreechart-1.0.13.jar
Download the jFreeChart jars from: http://sourceforge.net/projects/jfreechart/files/

Step 2: Generating Pie Charts/Bar Graph using jFreeChart

Next we will use jFreeChart library and generate the pie and bar charts.
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;

public class PieChartDemo {
public static void main(String[] args) {
//TODO: Add code to generate PDFs with charts
}

public static JFreeChart generatePieChart() {
DefaultPieDataset dataSet = new DefaultPieDataset();
dataSet.setValue("China", 19.64);
dataSet.setValue("India", 17.3);
dataSet.setValue("United States", 4.54);
dataSet.setValue("Indonesia", 3.4);
dataSet.setValue("Brazil", 2.83);
dataSet.setValue("Pakistan", 2.48);
dataSet.setValue("Bangladesh", 2.38);

JFreeChart chart = ChartFactory.createPieChart(
"World Population by countries", dataSet, true, true, false);

return chart;
}

public static JFreeChart generateBarChart() {
DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
dataSet.setValue(791, "Population", "1750 AD");
dataSet.setValue(978, "Population", "1800 AD");
dataSet.setValue(1262, "Population", "1850 AD");
dataSet.setValue(1650, "Population", "1900 AD");
dataSet.setValue(2519, "Population", "1950 AD");
dataSet.setValue(6070, "Population", "2000 AD");

JFreeChart chart = ChartFactory.createBarChart(
"World Population growth", "Year", "Population in millions",
dataSet, PlotOrientation.VERTICAL, false, true, false);

return chart;
}
}

n above code, we have created two methods that returns JFreeChart object. These methods creates charts using jFreeChart API. Note that we have used dummy data. In real example these values must be dynamically fetched from database or other data source.

Now we can do various stuff with these charts.

Eg. Generating pdf files from these charts.
So change the main method and add following code to above code:

public static void main(String[] args) {
writeChartToPDF(generateBarChart(), 500, 400, "C://barchart.pdf");
writeChartToPDF(generatePieChart(), 500, 400, "C://piechart.pdf");
}
public static void writeChartToPDF(JFreeChart chart, int width, int height, String fileName) {
PdfWriter writer = null;

Document document = new Document();

try {
writer = PdfWriter.getInstance(document, new FileOutputStream(
fileName));
document.open();
PdfContentByte contentByte = writer.getDirectContent();
PdfTemplate template = contentByte.createTemplate(width, height);
Graphics2D graphics2d = template.createGraphics(width, height,
new DefaultFontMapper());
Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, width,
height);

chart.draw(graphics2d, rectangle2d);

graphics2d.dispose();
contentByte.addTemplate(template, 0, 0);

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

In above code we have created a method writeChartToPDF() which take few arguments like jFreeChart object, width, height and filename and write a PDF files in that file.
java-bar-chart-pdf
java-pdf-pie-chart
This is ofcourse very preliminary example of adding pie charts in PDF using Java iText/jFreeChart. But atleast it gives basic idea of how to achieve this. Feel free to modify the above code and play around to generate different charts/graphs in PDF.

You can refer to following book for  more reading on jfreechart:

Monday, 11 April 2011

Eclipse tip: Conditional breakpoints

Eclipse provides a very nice debugging environment. One of the features I use often is conditional breakpoints. It is essentially breakpoints which suspend code execution only when a specified condition is satisfied. For example you want to set a breakpoint inside a loop but only are interested when a certain variable is null. To specify a condition select ‘Breakpoint Properties…‘ in the context menu of the breakpoint.
Enable conditional breakpoint
Then check the ‘Enable Condition‘ and type away the condition in the text area below. The text area also provides code assistance.There is an option to suspend when the expression evaluates to true or when the value changes.
Conditional breakpoint

Some very useful Eclipse IDE Shortcuts for Developers

Eclipse have been my favorite Java IDE since I started coding in Java. Shortcuts makes life very easy when you are working with any IDE. Eclipse also comes with lot of shortcuts that makes like of a developer easy.
Following are few shortcuts of my choice.
  1. Ctrl + Shift + O : Organize imports
  2. Ctrl + / : Line Comment
  3. Ctrl + Shift + T : Open Type
  4. Ctrl + O : Open declarations
  5. Ctrl + E : Open Editor
  6. Ctrl + Shift + F4 : Close all Opened Editors
  7. Alt + Shift + R : Rename
  8. Alt + Shift + L : Extract to Local Variable
  9. Alt + Shift + M : Extract to Method
  10. F3 : Open Declaration
  11. Alt + Shift + X : Run As…
  12. Alt + Shift + D : Debug As…
  13. Alt + Shift + W : show the class in the package view.
  14. Ctrl + T : Type hierarchy
  15. Ctrl+Q : Last edit
  16. Alt + Left or Alt + Right : Navigate Left and Right
  17. Ctrl + 1 : Quick Fix
  18. Ctrl + Space : Content Assist
  19. Alt + Shift + F : Format code
  20. Alt + Shift + S + R : Generate getter and setter methods

Eclipse Tip: Hide Closed Projects in Eclipse Project Explorer View

Ever wanted to hide all those closed projects in eclipse? Well, here is a simple trick that you may not know already.
Imagine your Eclipse workspace is filled with many projects that you created in past just to test some small functionality. Now you are done with these projects and hence you have closed it. Eclipse by default show all the closed projects in Project Explorer. Hence your project explorer may look like following where only two projects are open and rest competing for your attention although they are closed!
eclipse-close-project
Eclipse comes with a cool tiny feature that many of us not know. You may want to Hide all those closed projects from your workspace in Project Explorer tab. Simply follow following steps and do this is few seconds!
Step 1: Click on right corner of Project Explorer tab and open context menu. Select Filters option from menu.
eclipse-project-explorer-filter
Step 2: Check Closed Projects option from Filter and press Ok
eclipse-filter-close
Now check your project explorer tab, all the closed projects are gone! Doesn’t it looks more clean :)

We used Filters option to remove closed projects from Project Explorer tab. Filters provides more options to select and remove from displaying it from explorer view.

Friday, 8 April 2011

Sending a soap message from soap client in java

Sending a soap message requires a server name, like --
http://localhost:13000/myservicename
13000 is port no.
Now just create a connection and write soap message to it.
We are using following imports:
import java.net.*;
import java.io.*;
Now just write the code:
URL u = new URL(server);
URLConnection uc = u.openConnection();
HttpURLConnection connection = (HttpURLConnection) uc;

connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("SOAPAction", SOAP_ACTION);

OutputStream out = connection.getOutputStream();
Writer wout = new OutputStreamWriter(out);

wout.write("<?xml version='1.0'?>\r\n");
wout.write("<SOAP-ENV:Envelope ");
wout.write("xmlns:SOAP-ENV=");
wout.write(
"'http://schemas.xmlsoap.org/soap/envelope/' "
);
wout.write("xmlns:xsi=");
wout.write(
"'http://www.w3.org/2001/XMLSchema-instance'>\r\n");
wout.write(" <SOAP-ENV:Body>\r\n");
wout.write(" <calculateFibonacci ");
wout.write(
"xmlns='http://namespaces.cafeconleche.org/xmljava/ch3/'\r\n"
);
wout.write(" type='xsi:positiveInteger'>" + input
+ "</calculateFibonacci>\r\n");
wout.write(" </SOAP-ENV:Body>\r\n");
wout.write("</SOAP-ENV:Envelope>\r\n");

wout.flush();
wout.close();

InputStream in = connection.getInputStream();
int c;
while ((c = in.read()) != -1) System.out.write(c);
in.close();

Creating a soap message in java using SAAJ

Installation issues
Setting up the Java Web Services Developer Pack 1.2 is easy -- as long as you send your messages through the included Tomcat Web server. To send messages through a standalone application, as I do here, you need to take the following steps:
  1. Download the JWSDP 1.2 from http://java.sun.com/webservices/downloads/webservicespack.html.
  2. Follow the instructions and install.
Example of soap message to be created : 

<SOAP-ENV:Envelope 
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/1999/XMLSchema">
<SOAP-ENV:Header />
<SOAP-ENV:Body>
<ns1:Price xmlns:ns1="urn:xmethods-BNPriceCheck" >340
</ns1:Price>
         <AuthorName>
<FirstName>Rajesh</FirstName>
<LastName>Thakur</LastName>
</AuthorName>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

Now it has 2 parts - name and price , which it wants to submit to the service.
Notice the structure of the message. The Envelope contains the Header and Body elements, and all three are part of the http://schemas.xmlsoap.org/soap/envelope/ namespace. The application sends the message using a SOAPConnection.

Creating the message object
//Next, create the actual message
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage message = messageFactory.createMessage();

//Create objects for the message parts
SOAPPart soapPart = message.getSOAPPart();
SOAPEnvelope envelope = soapPart.getEnvelope();
SOAPBody body = envelope.getBody();

First, you create the message itself by using the MessageFactory. This message already contains empty versions of the basic parts, such as the envelope and header. The SOAPPart contains the envelope, and the envelope contains the body. Create references to the needed objects, such as the SOAPBody.

Populating the body:
The body of the SOAP message is just like any other XML element in that you can add a child element, such as Price.
//Populate the body
//Create the main element and namespace
SOAPElement bodyElement =
body.addChildElement(envelope.createName("Price" ,
"ns1",
"urn:xmethods-BNPriceCheck")).addTextNode("340");

SOAPElement authorElement = body.addChildElement(envelope.createName("AuthorName");
authorElement.addChildElement("FirstName").addTextNode("Rajesh");
authorElement.addChildElement("LastName").addTextNode("Thakur");

//Save the message
message.saveChanges();


//Check the input
System.out.println("\nREQUEST:\n");
message.writeTo(System.out);
System.out.println();
So this is how our message is prepared and now we can send it as request.

Thursday, 7 April 2011

Create JAR file using Eclipse IDE

reating JAR file using Eclipse IDE is pretty much easy. Follow the simple steps.
Right click on your project, which you want to create a JAR file of. And select Export from the context menu.

Select JAR file from Java folder and click Next.


Provide the Destination path and click on Finish to create the JAR.