18 October 2015

API Documentation with Swagger

In this post I will discuss How to document REST API.There are several API documentation tools available.

So In here I will use Swagger as API documentation tool.

Why API Documentation

The Main purpose is Test the API work properly.For Test API normally what we do is using curl or postman send request and Test.So Let's think About Who don't have programming knowledge how to test API.API documentation is to help them to read our API.

Swagger Support user friendly UI to Test the API.For demonstrate behavior of swagger UI I have created sample rest API.

How to use Swagger

First Add these service beans and providers to your server.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
<jaxrs:serviceBeans>
     <ref bean="studentManagementListener"/>
     <ref bean="swaggerResourceJSON"/>
</jaxrs:serviceBeans>
<jaxrs:providers>
     <ref bean="jacksonProvider"/>
     <ref bean="resourceWriter"/>
     <ref bean="apiWriter"/>
     <ref bean="corsFilter"/>
</jaxrs:providers>


<bean id="corsFilter" class="org.apache.cxf.rs.security.cors.CrossOriginResourceSharingFilter"/>

    <bean id="swaggerResourceJSON" class="com.wordnik.swagger.jaxrs.listing.ApiListingResourceJSON"/>

    <!-- Swagger writers -->

    <bean id="resourceWriter" class="com.wordnik.swagger.jaxrs.listing.ResourceListingProvider"/>

    <bean id="apiWriter" class="com.wordnik.swagger.jaxrs.listing.ApiDeclarationProvider"/>


And Then Need to Add Swagger Config Bean.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
<bean id="swaggerConfig" class="com.wordnik.swagger.jaxrs.config.BeanConfig">

        <property name="resourcePackage" value="dev.innova.rest.server.api"/>

        <property name="version" value="1.0.0"/>

        <property name="basePath" value="${student.management.api.url}"/>

        <property name="title" value="Student Management API"/>

        <property name="description" value="Student Management API Support to Manage Students in library"/>

        <property name="contact" value="sajith.vijesekara@gmail.com"/>

        <property name="license" value="Apache 2.0 License"/>

        <property name="licenseUrl" value="http://www.apache.org/licenses/LICENSE-2.0.html"/>

        <property name="scan" value="true"/>

    </bean>

And The Final Step is define Your API model.It is simple.Using swagger Annotations you can easily  make API visible in swagger UI.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
@Path("/")
@ApiModel(value = "Student Management")
@Api(value = "Student Management Server", description = "Student Management")
@CrossOriginResourceSharing(allowAllOrigins = true, allowCredentials = true)
public interface StudentManagement {

    @POST
    @Path("/student/add")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "Add Student", response = Response.class, notes = "Add Student")
    @ApiResponses(value = {@ApiResponse(code = 200, message = "Add Student Successful"),
    @ApiResponse(code = 404, message = "Failed to Add Student"),
    @ApiResponse(code = 500, message = "Failed to connect to Server")})
    Response addStudent(Student student);



    @GET
    @Path("/student/search")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "Search Student", response = Response.class, notes = "Search Student")
    @ApiResponses(value = {@ApiResponse(code = 200, message = "Search Student Successful"),
    @ApiResponse(code = 404, message = "Failed to Search Student"),
    @ApiResponse(code = 500, message = "Failed to connect to Server")})
    Response searchUser(GetStudent name);



    @DELETE
    @Path("/student/remove")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "Delete Student", response = Response.class, notes = "Delete Student")
    @ApiResponses(value = {@ApiResponse(code = 200, message = "Delete Student Successful"),
    @ApiResponse(code = 404, message = "Failed to Delete Student"),
    @ApiResponse(code = 500, message = "Failed to connect to Server")})
    Response removeStudent(GetStudent name);

}

And One Thing I forgot to add what are the dependencies for swagger.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<dependency>
     <groupId>com.wordnik</groupId>
     <artifactId>swagger-jersey2-jaxrs_2.10</artifactId>
     <version>1.3.8</version>
      <exclusions>
         <exclusion>
             <groupId>javax.ws.rs</groupId>
             <artifactId>jsr311-api</artifactId>
         </exclusion>
      </exclusions>
  </dependency>

  <dependency>
       <groupId>org.apache.cxf</groupId>
       <artifactId>cxf-rt-rs-security-cors</artifactId>
       <version>2.6.1</version>
  </dependency>


How to use Swagger UI
Download Swagger UI and deploy in tomcat server.Then open swagger UI and enter API url with api-docs tag at end of URL.

Ex:- http://127.0.0.1:4738/api-docs



04 October 2015

Android Google cloud messaging Test server

Java GCM Testing Server

Today I will share how to create java Testing Application for send android GCM notifications to android client.There are lot of examples how to create android GCM client application but for testing the notification flow you need server.But I couldn't found any good example how to create java server.So I found Library for send notifications so i used that library and create simple swing application to send notification.



Sample Code

This is the code-sample which I have already pushed in to github location(https://github.com/sajith4u/android-gsm-sample).


  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
package dev.innova.sajith;

import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.Result;
import com.google.android.gcm.server.Sender;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;


public class MainClass {

    public static void main(String[] args) {
        System.out.println("starting gcm-server Application");
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                init();
            }
        });

    }

    /**
     *  Send Notification to server
     * @param apiKey
     * @param registrationId
     * @param title
     * @param messagetext
     * @return
     */
    public static String send(String apiKey, String registrationId,String title,String messagetext) {
        Sender sender = new Sender(apiKey);
        Result result = null;
        Message message = new Message.Builder()
                .addData("message",messagetext)
                .addData("title", title)
                .build();
        try {
            result = sender.send(message, registrationId, 2);
            System.out.println("Result : " + result.getMessageId());
            System.out.println("Result ErrorCode : " + result.getErrorCodeName());
            System.out.println("Result : " + result.getCanonicalRegistrationId());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result.toString();
    }

    /**
     * Initialize the Swing form
     */
    public static void init() {
        JFrame frame = new JFrame("Notification Sender");
        frame.setSize(600, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel();
        frame.add(panel);
        placeComponents(panel);

        frame.setVisible(true);
    }

    /**
     *  Add Items to Swing form
     * @param panel
     */
    private static void placeComponents(JPanel panel) {

        panel.setLayout(null);

        JLabel apiKeyLabel = new JLabel("ApiKey");
        apiKeyLabel.setBounds(50, 20, 100, 40);
        panel.add(apiKeyLabel);

       final JTextField apiKeyText = new JTextField(20);
        apiKeyText.setBounds(160, 20, 400, 40);
        panel.add(apiKeyText);

        JLabel registrationLabel = new JLabel("Registraion ID");
        registrationLabel.setBounds(50, 70, 100, 40);
        panel.add(registrationLabel);

        final JTextField registrationText = new JTextField(20);
        registrationText.setBounds(160, 70, 400, 40);
        panel.add(registrationText);

        JLabel titleLabel = new JLabel("Title :");
        titleLabel.setBounds(50, 120, 100, 40);
        panel.add(titleLabel);

        final JTextField titleText = new JTextField(20);
        titleText.setBounds(160, 120, 400, 40);
        panel.add(titleText);

        JLabel messageLabel = new JLabel("Message :");
        messageLabel.setBounds(50, 170, 100, 40);
        panel.add(messageLabel);

        final JTextField messageText = new JTextField(20);
        messageText.setBounds(160, 170, 400, 40);
        panel.add(messageText);

        JButton resetButton = new JButton("Reset");
        resetButton.setBounds(50, 220, 120, 40);
        panel.add(resetButton);

        JButton sendNotification = new JButton("Send");
        sendNotification.setBounds(250, 220, 120, 40);
        panel.add(sendNotification);

        final JLabel statusLabel = new JLabel("status :");
        statusLabel.setBounds(50, 270, 400, 100);
        panel.add(statusLabel);

        sendNotification.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                statusLabel.setText("");
                String message = messageText.getText();
                String apiKey = apiKeyText.getText();
                String registrationKey = registrationText.getText();
                String titleMessage = titleText.getText();
                if((registrationKey.equals("")||registrationKey.equals(null))||(apiKey.equals("")||apiKey.equals(null))||(message.equals("")||message.equals(null))){
                    statusLabel.setText("Please Fill the above three Fields");
                }else {
                    statusLabel.setText("sending message ...........");
                    String response = send(apiKey,registrationKey,titleMessage,message);
                    statusLabel.setText(response);
                }

            }
        });

        resetButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                statusLabel.setText("");
                messageText.setText("");
                apiKeyText.setText("");
                registrationText.setText("");
                titleText.setText("");
            }
        });

    }


}

For use this application you need API key which provided when creating application in Google could platform and registration Id.In the next post I will share simple android client application and how to test using this server.

05 September 2015

Linux Bash Generate Random Files

In this Post I will discuss how to create random files using Linux bash script and how to remove files. For Example If you need to remove logs created for project you can write bashscripts to remove log files.First script create log files and second script remove the log files.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
#!/bin/bash

DIRECTORY_NAME="/home/sajithv/scripts"

cd $DIRECTORY_NAME

while :

do

CURRENT_TIME=`date +%Y-%m-%d:%H:%M:%S`

echo "Create Files at $CURRENT_TIME."

 touch "SampleFile$CURRENT_TIME.txt"

 sleep 5

done

Happy Coding...

24 January 2015

Linux Interactive Shell Scripting

Last week i saw interactive shell running in the juju-quickstart . It is really cool.So i search about interactive shell scripting techniques available in Linux.So i found one of the famous method is "Whiptail" . Basically these scripting used for displaying dialog boxes which used to get user Inputs.So I have created Sample Interactive shell Scripting using dialog boxes.


First Screen Start with Menus.


This is the confirm box with yes / no option.
 This is the Password box. In this script i have put another Input box.

This is the Progress bar in "whiptail".Here i will put the bash script file.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#!/bin/bash
# Whiptail is the interactive shell Scrpting
OPTION=$(whiptail --title "Whiptail Shell Script Menu" --menu "Choose your option" 15 60 4 \
"1" "Change Password" \
"2" "Change UserName" \
"3" "Change Email" \
"4" "exit"  3>&1 1>&2 2>&3)

exitstatus=$?
if [ $exitstatus = 0 ]; then
    echo "Your chosen option:" $OPTION

case $OPTION in
  1) echo "Option1 Selected"
     if (whiptail --title "Change Password" --yes-button "Yes" --no-button "No"  --yesno "Do you need to changed Password ?" 10 60) then
    echo "password Selection Yes$?."
     
    # Start Password Box
    PASSWORD=$(whiptail --passwordbox "please enter your secret password" 8 78 --title "Change Password" 3>&1 1>&2 2>&3)
                                                                        # A trick to swap stdout and stderr.
    # Again, you can pack this inside if, but it seems really long for some 80-col terminal users.
     exitstatus=$?
 if [ $exitstatus = 0 ]; then
     echo "User selected Ok and entered " $PASSWORD
     touch sample_out_put.txt
     echo $PASSWORD > sample_out_put.txt
            
            # Start Progress Bar
      {
       for ((i = 0 ; i <= 100 ; i+=5)); do
  sleep 0.3
  echo $i
     done
      } | whiptail --gauge "Password Updating.." 6 50 0
            # End Progress Bar    

 else
     echo "User selected Cancel."
 fi

    # End Password Box 
     else
    echo "Password Selection No$?."
     fi
     ;;
  2) echo "option2 Selected"
 # Change User Name Box
 NAME=$(whiptail --inputbox "Change Username " 8 78  --title "Changed UserName" 3>&1 1>&2 2>&3) 
 exitstatus=$?
 if [ $exitstatus = 0 ]; then
     echo "UserName Changed " $NAME
 if (whiptail --title "Confirm Change UserName" --yes-button "Yes" --no-button "No"  --yesno "Do you need to changed UserName ?" 10 60)  then
     echo "Username Confirm Yes$?."
     # Start Progress Bar
      {
       for ((i = 0 ; i <= 100 ; i+=5)); do
  sleep 0.3
  echo $i
       done
      } | whiptail --gauge "UserName Updating.." 6 50 0
            # End Progress Bar 
 else
  echo"Confirm Failed"
 fi

 else 
    echo "UserName Not Changed"
 fi

     ;;
  3) echo "Option3 Selected"
     
     ;;
  4) echo "exit"
     {
    for ((i = 0 ; i <= 100 ; i+=5)); do
        sleep 0.1
        echo $i
    done
     } | whiptail --gauge "exit..." 6 50 0
esac

else
    echo "You chose Cancel."
fi

And Happy Coding....

16 January 2015

Write Juju charm

In the last tutorial(tutorial1) we discuss what is juju and what are the capabilities in juju. In juju all the concepts based on juju charms.Basically individual component is called juju charm. Developers can build their charms and publish in to juju charm store(https://demo.jujucharms.com/).This image shows how to add mysql charm and wordpress charm and add relations between them.



Why use juju ??

Juju is a framework which support deploy applications to any cloud or Ubuntu based environment simple and more flexibility.

What is juju charm ??

Charm is individual component which used to manage service. If  we get simple service  "mysql database" or "wordpress".If you need to deploy these service in to your cloud environment you need to just drag and drop these charms and connect them through GUI.

Write Hello world charm.

When you write charm you may use python or bash script as programming languages.In here i will create "Helloworld" charm and then deploy in LXC container. 

First need to install charm tools.

sudo apt-get install charm-tools
Then create Helloworld charm

charm create hello_world

Then it look like this one.It contains hooks folder and config.yaml and metadata.yaml
Then inside hooks folder   there are several scripts files.These are "install" , "config-changed","start","stop","upgrade-charm" and other relation changed and relation joined scripts.

Charm life cycle 

In this flow diagram show how scripts inside hooks folder runs.


First it runs "install" hook which used to install all the dependencies to the charm.For example if your charm need java or python need to install before start application in your environment you have to mention these dependencies in install hook.

Then It runs "config-changed" hook.It is responsible for act  when changing configuration in charms.And then "start" hook runs.It is responsible for start the application.It may be server or service.

And there are other three hooks which are related to changed or add relations to charms.As example if mysql charm need to connect to wordpress charm we have to add relation between mysql and wordpress.

And Last Step it runs "stop" hook.Which is responsible for shutdown all services provided in charm.

24 December 2014

Data Mining Classification with weka

My final year project based on data mining and data classification.So i spent lot of time to find how data classification done by using weka. So In this article i will show how data classification/prediction using weka API.In This tutorial i will show how to predict data using weka API.First you need data set.For that i will suggest it is better to install weka (http://www.cs.waikato.ac.nz/ml/weka/downloading.html )software in your computer. After installing you can see in the installed location data folder.For this tutorial i will use iris.ARFF to predict result.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
@RELATION iris

@ATTRIBUTE sepallength REAL

@ATTRIBUTE sepalwidth  REAL

@ATTRIBUTE petallength  REAL

@ATTRIBUTE petalwidth REAL

@ATTRIBUTE class  {Iris-setosa,Iris-versicolor,Iris-virginica}

@DATA

5.1,3.5,1.4,0.2,Iris-setosa

4.9,3.0,1.4,0.2,Iris-setosa

4.7,3.2,1.3,0.2,Iris-setosa

4.6,3.1,1.5,0.2,Iris-setosa

5.0,3.6,1.4,0.2,Iris-setosa

5.4,3.9,1.7,0.4,Iris-setosa

4.6,3.4,1.4,0.3,Iris-setosa

5.0,3.4,1.5,0.2,Iris-setosa

4.4,2.9,1.4,0.2,Iris-setosa

4.9,3.1,1.5,0.1,Iris-setosa

5.4,3.7,1.5,0.2,Iris-setosa

4.8,3.4,1.6,0.2,Iris-setosa

4.8,3.0,1.4,0.1,Iris-setosa

This is the sample data set.Here you can see data set realation name is iris and there are four Attribute to predict class.For predict the class there are several classification algorithm available in  weka API.In here i have used decision tree classification.

First you need to open weka and select iris.arff file and then go to classification tab and select J48 algorithm.Then start classification process.Then you can see this result.


Then you can see the decision tree generated in weka.For the write click the j48 panel (blue color) and visualize.



 Then we have to predict the class value based on our four attributes.In this example i will predict the  class value for this attribute data.     
 4.8,2.1,3.7,1.4,?

1 Step :

Need to build model file for using data set.As a first step you have to add weka jar file to your project and import necessary classes. For building model file we need the data set and using the data set based on the classification algorithm we build model here.I have used cross validation as evaluation technique.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
public void buildIrisModel() {

        try {

            ConverterUtils.DataSource source = new ConverterUtils.DataSource("C://Users//Sajith//Desktop//iris.arff");

            Instances train = source.getDataSet();

            train.setClassIndex(train.numAttributes() - 1);

            J48 j48 = new J48();

            j48.setUnpruned(true);

            Evaluation eval = new Evaluation(train);

            eval.crossValidateModel(j48, train, 10, new Random(1));

            System.out.println("Percent correct: " + Double.toString(eval.pctCorrect()));

            System.out.println("Correct : " + Double.toString(eval.correct()));

            System.out.println("Incorrect : " + Double.toString(eval.incorrect()));

            System.out.println("Error Rate : " + Double.toString(eval.errorRate()));

            System.out.println("Mean Absolute Error  : " + Double.toString(eval.meanAbsoluteError()));


            j48.buildClassifier(train);

            ObjectOutputStream oos = new ObjectOutputStream(

                    new FileOutputStream("C://Users//Sajith//Desktop//iris.model"));

            oos.writeObject(j48);

            oos.flush();

            oos.close();

            System.out.println("Graph   : " + j48.graph());

        } catch (Exception e) {

            e.printStackTrace();

        }

    }
2 Step :
This method used to generate Instance of Arff data set.It means we create instance of data set and using that Instance predict class value. This CreateInstance method get the four attributes and returns the Instance.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
private Instances data;

    public Instances CreateInstance(double sepallength,double sepalwidth,double petallength,double petalwidth){

        double result = -1;

        String prediction=null;

        try {

          ArrayList<Attribute> attributeList = new ArrayList<Attribute>(2);

          Attribute attribute_sepallength = new Attribute("sepallength");

          Attribute attribute_sepalwidth = new Attribute("sepalwidth");

          Attribute attribute_petallength = new Attribute("petallength");

          Attribute attribute_petalwidth = new Attribute("petalwidth");

            ArrayList<String> classVal = new ArrayList<String>();

            classVal.add("Iris-setosa");

            classVal.add("Iris-versicolor");

            classVal.add("Iris-virginica"); 

            attributeList.add(attribute_sepallength);

            attributeList.add(attribute_sepalwidth);

            attributeList.add(attribute_petallength);

            attributeList.add(attribute_petalwidth);

            attributeList.add(new Attribute("class",classVal));


            data = new Instances("Iris",attributeList,0);

            data.setClassIndex(data.numAttributes() - 1);


            Instance inst_co = new DenseInstance(data.numAttributes());


            inst_co.setValue(attribute_sepallength, sepallength);

            inst_co.setValue(attribute_sepalwidth, sepalwidth);

            inst_co.setValue(attribute_petallength, petallength);

            inst_co.setValue(attribute_petalwidth, petalwidth);

            data.add(inst_co);

            System.out.println(data);

        } catch (Exception e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

        return data;

    }

3  Step:
This is the last step.In this step we parse the data and create Instance and then predict class value based on Instance.

1
2
3
4
5
// parse sepallength,sepalwidth,petallength,petalwidth  values
Instances inst = new wekaWriteArfFile().CreateInstance(4.8,2.1,3.7,1.4);
Classifier j48_classifier = (Classifier)weka.core.SerializationHelper.read("C://Users//Sajith//Desktop//ModelFiles//j48_iris_model.model");
 value = j48_classifier.classifyInstance(inst.instance(linereadFromfile));
 prediction = inst.classAttribute().value((int) value);

And now you got the result.Later i will upload source code in to github..Thanks

05 December 2014

Java swing chart library

First You need to download library.(http://www.jfree.org/jfreechart/download.html).Then it supports different type of chart types and it is easy to implement.Here i will describe how to implement PieChart and save chart as Image.Before You start you have to import jcommon and jfreechart to your project.

public class PieChartExampleDemo extends JFrame {

    public PieChartExampleDemo(String applicationTitle, String chartTitle) {

        super(applicationTitle);

        PieDataset dataset = createDataset();

        JFreeChart chart = createChart(dataset, chartTitle);

        String filename = "F:\\pichartImage.jpg";

        try {

            ChartUtilities.saveChartAsJPEG(new File(filename), chart, 600, 400);

        } catch (IOException e) {

            e.printStackTrace();

        }

        ChartPanel chartPanel = new ChartPanel(chart);

        chartPanel.setPreferredSize(new java.awt.Dimension(600, 400));

        setContentPane(chartPanel);


    }


    private  PieDataset createDataset() {

        DefaultPieDataset result = new DefaultPieDataset();

        result.setValue("Blackberry", 24);

        result.setValue("Apple", 22);

        result.setValue("Windows", 44);

        result.setValue("Android", 35);

        result.setValue("Symbian", 5);

        result.setValue("Other", 4);

        return result;


    }


    private JFreeChart createChart(PieDataset dataset, String title) {

        JFreeChart chart = ChartFactory.createPieChart3D(title, dataset,

                true,

                true,

                false);

        PiePlot3D plot = (PiePlot3D) chart.getPlot();

        plot.setStartAngle(290);

        plot.setDirection(Rotation.CLOCKWISE);

        plot.setForegroundAlpha(0.5f);

        return chart;

    }

}

From main class you can call to this class.You can save chart as jpg image.

PieChartExampleDemo pieChartExampleDemo = new PieChartExampleDemo("Mobile OS", "Mobile operating System Usage 2014");
        pieChartExampleDemo.pack();
        pieChartExampleDemo.setVisible(true);


And This is the result.