Sunday, 22 April 2012

Example to draw LineChart using JFreeChart in Java

JFreeChart  provides pretty good library to draw graphs in Java. As the documentation is paid you would have to struggle a lot to find the solution as per your requirements albeit simple examples are easily accessible. My requirement was also bit different than simple ones so made some efforts to achieve this. Following is an example of line chart with series. So i have names it "". I had tried my best to cover everything related to line chart in this example, using proper documentation.
//Code Starts here
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
package jfreecharts;

 * @author sshankar
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.Stroke;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;
import org.jfree.chart.axis.CategoryLabelPositions;

 * A simple demonstration application showing how to create a line chart using data from a
 * {@link CategoryDataset}.
public class JFreeSeriesLineChart extends ApplicationFrame {

     * Creates a new demo.
     * @param title  the frame title.
    public JFreeSeriesLineChart(final String title) {
        final CategoryDataset dataset = createDataset();
        final JFreeChart chart = createChart(dataset);
        final ChartPanel chartPanel = new ChartPanel(chart);
        this.add(chartPanel, BorderLayout.CENTER);
        //Adds a label at bottom of the chart. You can use it to show some useful information
        JPanel customPanel = new JPanel();
        JLabel lbl = new JLabel("<html><h3>Note : You can add any important note here.</h3></html>");
        this.add(customPanel, BorderLayout.SOUTH);
     * Returns a sample dataset.
     * @return The dataset.
    private CategoryDataset createDataset() {
        // create the dataset...
        final DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        dataset.addValue(1.0, "Series1", "Category1");
        dataset.addValue(4.0, "Series1", "Category2");
        dataset.addValue(3.0, "Series1", "Category3");
        dataset.addValue(5.0, "Series1", "Category4");
        dataset.addValue(5.0, "Series1", "Category5");

        dataset.addValue(5.0, "Series2", "Category1");
        dataset.addValue(7.0, "Series2", "Category2");
        dataset.addValue(6.0, "Series2", "Category3");
        dataset.addValue(8.0, "Series2", "Category4");
        dataset.addValue(4.0, "Series2", "Category5");

        dataset.addValue(4.0, "Series3", "Category1");
        dataset.addValue(3.0, "Series3", "Category2");
        dataset.addValue(2.0, "Series3", "Category3");
        dataset.addValue(3.0, "Series3", "Category4");
        dataset.addValue(6.0, "Series3", "Category5");
        return dataset;
     * Creates a sample chart.
     * @param dataset  a dataset.
     * @return The chart.
    private JFreeChart createChart(final CategoryDataset dataset) {
       final JFreeChart chart = ChartFactory.createLineChart(
            "Line Chart Example",
         // chart title
            "Category",                   // domain(x-axis) axis label
            "Value",                      // range(y-axis) axis label
            dataset,                      // data
            PlotOrientation.VERTICAL,     // orientation
            true,                         // include legend
            true,                         // tooltips
            false                         // urls
        //final StandardLegend legend = (StandardLegend) chart.getLegend();
        // set chart background

        //set plot specifications
        final CategoryPlot plot = (CategoryPlot) chart.getPlot();
        plot.setBackgroundPaint(new Color(0xffffe0));
        final CategoryAxis domainAxis = (CategoryAxis) plot.getDomainAxis();
        //customize domain label position
            CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 6.0)

        final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
        final LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer();
        // renderer.setDrawShapes(true);
        //You can also set series line colors for each line
        /*renderer.setSeriesPaint(0, Color.RED);
        renderer.setSeriesPaint(1, Color.BLUE);
        renderer.setSeriesPaint(2, Color.YELLOW);
        renderer.setSeriesPaint(3, Color.GREEN);
        renderer.setSeriesPaint(4, Color.ORANGE);
        renderer.setSeriesPaint(5, Color.white);*/

        //Working Code to show values along with dots
        /*NumberFormat format = NumberFormat.getNumberInstance();
        CategoryItemLabelGenerator generator =
            new StandardCategoryItemLabelGenerator(

        //set dots or you can say shapes at a point
        //It would show solid lines
        Stroke stroke = new BasicStroke(
            3f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL);
        //You can also customize your lines like dotted one, dash-ed one etc.
        /* renderer.setSeriesStroke(
            0, new BasicStroke(
                2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND,
                1.0f, new float[] {10.0f, 6.0f}, 0.0f
            1, new BasicStroke(
                2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND,
                1.0f, new float[] {6.0f, 6.0f}, 0.0f
            2, new BasicStroke(
                2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND,
                1.0f, new float[] {2.0f, 6.0f}, 0.0f
        return chart;
     * Starting point for the demonstration application.
     * @param args  ignored.
    public static void main(final String[] args) {

        final JFreeSeriesLineChart demo = new JFreeSeriesLineChart("Series-Line Chart Demo");



After running successfully, you will get the following output :

Note : In line chart you can't perform zoom-in operation for a particular section. For that you have to go with TimeSeriesChart.

Thanks!!!!!!!! Enjoy Programming :)

Saturday, 14 April 2012

PHP Associative Arrays and Hashtable

Our today’s topic is how associative arrays are implemented in PHP. Let’s  discuss over it….

Basic Arrays in C 

Let’s take an example of basic array in C where index or key is always an integer. It can’t be string. All the arrays start from index 0 and ends at index (n-1), where n is the number of elements in array. All the elements are stored in continuous memory locations. For example first element at memory location 0 and 10th  element on 9th location.  This is the basic array of C. 

What is Hashtable? 

A hash table or hash map is a data structure that uses a hash function to map identifying values, known as keys (e.g., a person's name), to their associated values (e.g., their telephone number). Thus, a hash table implements an associative array.  We will go into detail of this in next few minutes..

What is Hash Function?

The hash function is used to transform the key into the index (the hash) of an array element (the slot or bucket) where the corresponding value is to be sought. There is no magic formula for the creation of the hash function. It can be any mathematical transformation that produces a relatively random and unique distribution of values within the address space of the storage.


PHP and Hashtable (an implementation of a map):

In PHP associative arrays can be implemented using hash-maps or b-trees. This has important implications on the performance characteristics of associative arrays and how they should be used; e.g. b-trees are slow to insert but handle collisions better than hash maps.  Hashmaps are faster if there are no collisions, but are slower to retrieve when there are collisions. In PHP associative arrays are actually implemented using hashtables with ordered map or you can say hashmaps.  Following are the actual functions of PHP written in C to implement hashtable. Check here.

struct _hashtable;
typedef struct bucket {
                ulong h;                                                                                  /* Used for numeric indexing */
                uint nKeyLength;
                void *pData;
                void *pDataPtr;
                struct bucket *pListNext;
                struct bucket *pListLast;
                struct bucket *pNext;
                struct bucket *pLast;
                const char *arKey;
} Bucket;

typedef struct _hashtable {
                uint nTableSize;
                uint nTableMask;
                uint nNumOfElements;
                ulong nNextFreeElement;
                Bucket *pInternalPointer;      /* Used for element traversal */
                Bucket *pListHead;
                Bucket *pListTail;
                Bucket **arBuckets;
                dtor_func_t pDestructor;
                zend_bool persistent;
                unsigned char nApplyCount;
                zend_bool bApplyProtection;
                int inconsistent;
} HashTable;

In PHP, associative array key(string) is first converted into index using hash function and then that value is stored at that particular index location. Here is again a problem. Hash function returns an integer that is system dependent (e.g 32bit or 64 bit).

For example say, a system with 32 bit OS, against a key named ‘dirtyhandsphp’ hash function returns :

It’s decimal value is 6269624.

This is a huge value and can’t represent the location with hashtable size of 2048(say). So here PHP use one more trick. It throws some digits away by using table mask.
(ht)->nTableMask = (ht)->nTableSize - 1;

It’s one less than the size of hash table. Because if table size is 2048(210) then maximum index could be 2047 starting from 0.

PHP performs & operation between both of them
   &    00000000000000000000001111111111
          00000000000000000000001010111000 = 676

So the element would be stored at 676th location.

Collision: Implementing hash table in this way produces some problems called collision. For example hash function can generate same integer value for two different strings or you can say for associative array keys.  Two locations may refer to same index. Such situation is called collision. In PHP to solve such type of problem, it uses linked list. So if same index is generated then it would stored at different location but would linked to the same index generated using hash function.

To read or access the element again same process will follow :

1) Hash is calculated
2) Use table mask
3) Locate the memory address and
4) Get the data or if required traverse the linked list to find the element we needed.

Thanks !!!!!!!!!!! Enjoy Programming :)

Sunday, 1 April 2012

Understanding OAuth

In this post we are going to discuss over  OAuth, it’s use and the workflow etc. Although it’s not easy to sum it up in just one post but i will try my best to cover it. I am using Oauth 1.0 to explain it.

What is OAuth

Oauth is an open standard for authorization. Today most of the third party application use this terminology for user authorization. 

As per Wikipedia 

OAuth is an open standard for authorization. It allows users to share their private resources (e.g. photos, videos, contact lists) stored on one site with another site without having to hand out their credentials, typically supplying username and password tokens instead. Each token grants access to a specific site (e.g., a video editing site) for specific resources (e.g., just videos from a specific album) and for a defined duration (e.g., the next 2 hours). This allows a user to grant a third party site access to their information stored with another service provider, without sharing their access permissions or the full extent of their data.

Before OAuth what was happening that user had to submit access credentials, username and password, to third party site so that they can access user’s data on his/her behalf. But it cause number of problems :

1) User may have used the same username/password for other services also. For example you are using same password for gmail and facebook.

2) If user have given it’s credentials to more than 1 third party applications say A and B and user is not happy with app A service and wants to unauthorize it then the user have to change the password and if user did that then access of second application would gets declined automatically. So they will have to update app B with new credentials.

3) it also provide these application unlimited access to do as they wish. They can do anything, including changing the passwords and lock users out.

So to solve such type of problems a new terminology emerged named OAuth. One more advantage of using OAuth is that you can also restrict third party to access only limited resources.

OAuth Terminology Workflow 

As explained above OAuth is mainly used by third-party to get information on user’s behalf from his account.  Let’s explain it using a diagram :

1) Front end user directly interacts with third-party or say client application. In our case it’s User wants to print some of his photos which are on facebook and are not public. So to print them zoomin have to import them and to import them it needs user’s authorization. User clicks on say ‘import photos from facebook’ link.

2) Client application use it’s application key, oauth_signature and other parameters to send request at backend to facebook(Service Provider) on behalf of user.

3) In response client application managed to get temporary credetials,request_token and request_secret, from service provider.

4) Client application (zoomin) will show a page to get restricted authorization from user. When user will authorize it, client application will use these temprary credentials to get access credentials in form of access_token and access_secret from service provider. Anytime user can withdraw it’s access from client application without changing password of any application.

5) Nowonwards client application( will use these access credentials to import restricted photos from service provider (

6) Finally user will get printed photos from

Important stuff from development prospective

Some important parameters used in OAuth for sending any request are : 

1) oauth_consumer_key: Whenever you are going to create an application although it’s in Flickr, Facebook or in any other environment you will get consumer key in response. As the word key indicates it’s the key part of application.

2)  oauth_secret : 2nd thing you get after creating application is consumer secret or only secret. As the name indicates keep it secret. It’s mainly used to create oauth_signature parameter.

3) oauth_timestamp :  As the name indicates it’s current timestamp.  Please make sure that your application is using the right timestamp from right timezone. For example Flickr uses UTC timezone.

4) oauth_nonce : The term nonce means ‘number used once’ and is a unique and usually random string that is meant to uniquely identify each signed request. By having a unique identifier for each request, the Service Provider is able to prevent requests from being used more than once. So oauth_nonce once used can’t be used again.

5) Oauth_signature : It’s send with request for verification purpose. It’s one of the crucial part of request. If it’s not generated properly then you can’t move ahead. It’s explained in detail in next section.

How to generate oauth_signature ?

It depends on which signature method you are going to use. Following three signature methods are used in OAuth request.

1) PLAINTEXT : The PLAINTEXT method does not provide any security protection and SHOULD only be used over a secure channel such as HTTPS. It does not use the Signature Base String so this method doesn’t use any signature algorithm. It also does not utilize the signature base string or the "oauth_timestamp" and   "oauth_nonce" parameters. oauth_signature is set to the concatenated encoded values of the Consumer Secret and Token Secret, separated by a ‘&’ character (ASCII code 38), even if either secret is empty. The result MUST be encoded again.

2) HMAC-SHA1 : HMAC-SHA1 offers a simple and common algorithm that is available on most platforms. HMAC-SHA1 uses HMAC signature algorithm and SHA1 hash method to generate oauth_signature. It’s not easy to explain in detail about this signature method. But to generate signature it uses base string and hash key which is set of concatenated encoded values of the Consumer Secret and Token Secret, separated by a ‘&’ character. After using HMAC method whole string is encoded using base64.

$hashkey         = $cc_secret."&".$token_secret;
$oauth_signature = base64_encode(hash_hmac('sha1', $base_string, $hashkey, true));

3) RSA-SHA1  : The "RSA-SHA1" signature method uses the RSASSA-PKCS1-v1_5 signature algorithm using SHA-1 as the hash function for EMSA-PKCS1-v1_5. To use this method, the client MUST have established client credentials with the server that included its RSA public key.

RSA-SHA1 provides enhanced security using key-pairs but is more complex and requires key generation and a longer learning curve.

Since the RSA-SHA1 method does not use the token secret (it doesn’t use the client secret either but that is adequately replaced by the client private key), the private key is the only protection against attacks. In case of web based applications it’s easy to keep secret private key but in case of desktop applications like applets in java it has to be distributed with the application, which inheritably compromises them.

 Note : Most commonly used signature method is HMAC-SHA1.

What is use of oauth_signature ? 

It’s related with security issue. Oauth_signature allow the recipient to verify that the content of the request hasn’t changed in transit. To do that, the sender uses a mathematical algorithm to calculate the signature of the request and includes it with the request.  

In turn, the recipient performs the same workflow to calculate the signature of the request and compares it to the signature value provided. If the two match, the recipient can be confident that the request has not been modified in transit. The confidence level depends on the properties of the signature algorithm used (some are stronger than others). This mechanism requires both sides to use the same signature algorithm and apply it in the same manner.

To go deeper you can also read OAuth and Flickr, my previous post.

Thanks !!!!!! Enjoy Programming :)