Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Monday, March 20, 2017

Develop Your First REST Web Service with Java Spring

Hi All,

Let's develop our first REST web service. There are various libraries and methods you can follow to develop a REST API. But here we are going to use Spring framework to get this done in a much more easier manner. Here I am using IntelliJ IDEA 2016 to develop my application.

First let's go and create a maven project in Idea. Here we are not going to select a archetype. We will just use the existing template.

Let's update the pom.xml. We need to specify our spring dependencies and also the tomcat plugin to run our service locally. We will also need to add Jackson to do JSON mapping for us. Once you have update the pom file, it should should look like below. 


Once the dependencies are added to the project, you can check that by going into the project structure. 

Then we need to specify the WebApp folder where the necessary web resources are present. It's important that we adhere to the given structure, otherwise during the project build and packaging, we need to edit the pom to recognize where our resources exactly resides in. Project structure should look like below. 

Now let's create a package and add our REST controller class inside the package. REST controller is acting as an endpoint to the requests. It will get the requests as GET, POST and etc. according to the requests it will reply with the necessary output. To specify this class as a controller we need to use the '@RestController' annotation. Then we can optionally use the '@RequestMapping' to specify the path to our controller from the root. In order to include header for CORS( Cross-Origin Resource Sharing ) we need to use '@CrossOrigin' annotation. To read more about CORS you can refer to this link. 


Now we have setup our rest controller. Let's add some REST methods to get some work done with our controller. There are several rest methods like GET, POST, PUT, PATCH, DELETE. You can read about the REST methods here. 

Before adding the methods, lets create a simple Person class and a list of people inside our controller, just to test both GET and POST methods.


Now we can go and create our methods. Following is the complete code for the controller class.


We also need to add the servlet.xml and web.xml inside WEB-INF folder. 


Now let's run our program first and then look into the methods and what we have done in each. 

In order to run the program we can create new debug configuration in IntelliJ as following. Then you can click on the debug button to debug the program. 

In order to check the results it's good to install the Postman plugin for chrome. 

Now lets check our results while referring to the methods. 

The first method is a GET method that creates a Person and returns the object as the response. The person object is converted to a JSON object automatically with Jackson Data Binding. The method is just a simple GET method without any arguments passed into it. You can access the web service from the following URI. 

http://localhost:8080/JavaSpringRESTDemo/learning/newperson

If you check the result through Postman it will be as following. 


Second addPerson method is a POST method, that accepts a Person as a JSON object and adds the Person to a list. Here the Person object is again sent as a JSON object and it is mapped to a POJO by Jackson data binding. You can send the POST request as following. 

Once you send the request, response will be the existing list with the added Person as a JSON object. 

Now let's use a URL parameter to get the person, when the user ID is specified. URL parameter is specified by the annotation @RequestParam(value = "id"). So we have to specify the URL as following and get the output object. 

There is another way we can specify a parameter in the URL itself. It's by using a Path Variable. The final method is developed to accept a path variable containing a user ID. You can use the following URL to get the person with ID 15. 

So that's should be it for now. Hope to publish more with Spring Related stuff. 

Hope that helps. 
Thank you.

Sunday, March 19, 2017

Communicate Within Wars Inside Same Container

Hi All,

There are certain scenarios when you want to communicate within the wars inside the same container without using the network. For an example, you need to avoid any network delay that would cause either by using web-services,RMI or HTTP.

So what I'm going to show you is one working solution to achieve the above problem. What we can do is introduce a common library that is a dependent to both the services. Through the intermediate library we can continue the communication among the war files.

For this example, I'm using a service called, Front Service to accept the user request. Then a second service called 'Ground Service' that contains a method need to be called by the Front Service. The communication between the services are done with a JAR named 'Common-Lib'.

Common Lib has an interface which is similar to the Ground Service. It contains the method definitions of the Ground Service.



Common Lib also has a class that gets and sets the Service Instances registered to the jar.



Then let's develop the Front Service. This service is a simple Spring service, that gets a message from the Ground Service.



Finally we need to implement the Ground Service.
Here we have the Ground Service class and the helper classes to map a service instance to the Service Handler. There is a class named GroundServiceConfig, that sets an instance of the IGroundService interface to the Service Handler. IGroundService is implemented in the GroundServiceAdapter class.







Now we have the two services and the common library defined. It's important to note that although common-lib is a dependent of both the services, we do not bundle them with the service. Therefore in the POM.xml, we specify the 'common-lib' dependency as provided.



Therefore we need to deploy the common-lib in the 'lib' inside tomcat installation.

What happens here is that, when the Ground Service is initializing, it will assign a new instance of the IGroundService in the Service Handler. This instance can then be used to call the service methods from the other Services that uses 'Common-Lib' as a dependency.

Now let's deploy the two services inside the web-apps and put the common-lib inside the 'lib'

Let's go to the Front Service URL and check the result. As you can see we have got the message successfully from the GroundService.

The complete projects and code can be found here.

Hope that helps.
Thank You.



Sunday, December 20, 2015

Using SIFT/SURF for Object Recognition in OpenCV Java

Hi All,

Today my post is on, how you can use SIFT/SURF algorithms for Object Recognition with OpenCV Java. I have shared this post on SURF feature detector previously. This is fully based on that post and therefore I'm just trying to show you how you can implement the same logic in OpenCV Java. It's important that you have to download previous OpenCV versions, so that you have SURF feature detector in your library. Because in the newer versions they have removed these Non-Free modules from the java wrapper. You can check this out.

I believe that you have some basic knowledge in working with OpenCV Java. If you want some beginner help you can refer the following links.
Now let's move on to our development. I'm using Eclipse for developing this. I'm going to use OpencCV 2.4.11. You can download it here. 

First create the user library for OpenCV as described in the previous link and add it to the build path. Then we can start developing the code for object recognition. Following is my eclipse project. I have added the OpenCV 2.4.11 library as a user library and added it to the build path. 

I'm using following images for object recognition. 

1. Object we are going to recognize. 

2. Scene that we are going to recognize the object from. 

Now following is the Java implementation of our SURF feature detector. 



Following are our outputs. 

1. Identified key-points of the object.



2. Matching the object keypoints with the scene. 


3. Object recognized image. 


You can do the same with SIFT feature detector by just changing the Feature Detector and Descriptor Extractor name to SIFT. 

So that's it. 

Hope that helps. 

Thank You. :-) 



Sunday, December 13, 2015

Develop OpenCV Cross Platform Applications with Java

Hi All,

Today I'm going to show you how you can start developing OpenCV applications with Java that can work independently from the underlying OS. This might not be the best implementation, but what I'm going to share works fine.

I assume you have some basic knowledge in working with OpenCV in Java. You can easily download OpenCV for Windos/Linux/Mac from OpenCV downloads. Here I'm going to use OpenCV 2.4.11. You can download your preferred version.

I'm going to use the following simple code to demonstrate that OpenCV is working.
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;

public class Main
{
 public static void main(String[] args)
 {
  System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
  Mat mat = Mat.eye(3, 3, CvType.CV_8UC1);
                System.out.println("mat = " + mat.dump());
 }
}

Our purpose here is to provide the above code to work in any platform. ( Here I'm going to show only for Windows and Linux. You can use similar method for Mac)

Therefore first we have to build necessary .dll and .so files so that we can use them in our application. For Windows it's very easy because, when you download OpenCV for windows and extract it to a particular location you can find the .dll files in \build\java\x64 and in \build\java\x86.

Next we have to build the .so files.

In your Linux machine that you are going to build .so files, make sure you have installed the following programs before you follow the next set of instructions.

1. g++
2. cmake
3. ant

You can install the above programs by just using 'sudo apt-get install ' .
Make sure you have set the Java path in your terminal before you execute the commands. You can use 'export JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64' command to do this.

Once you have set up your environment you can use the following instructions to build the .jar and .so files for opencv.

1. Download OpenCV for Linux.
2. Extract the .zip file to a location.
3. CD into that location.
4. Execute the following commands.

mkdir release
cd release
cmake -DBUILD_SHARED_LIBS=OFF ..
make -j8
When you run the cmake -DBUILD_SHARED_LIBS=OFF .. command make sure you get the following output. Otherwise you won't get the .so and .jar files created.


Inside the release folder you can find the newly created files. Inside 'bin' folder you can find the 'opencv-2411.jar' and inside 'lib' folder you can find the 'libopencv_java2411.so' file.

You can build for both Linux 32 and 64 bit environments.

Now we are ready to develop our OpenCV program for both Windows and Linux environments along with their respective bitness (64 or 32).

I am using Eclipse to develop my application. First add the 'opencv-2411.jar' to your project and add it to the Build Path.

Then copy the .dll and .so files for both 32 and 64bit versions to a folder inside the project. Now with the following code, you can start loading the libraries for the respective OS.
if (os.toUpperCase().contains("WINDOWS"))
  {
   if (bitness.endsWith("64"))
   {
    lib = new File("native/64x" + System.mapLibraryName("opencv_java2411"));
   }
   else
   {
    lib = new File("native/86x" + System.mapLibraryName("opencv_java2411"));
   }
  }
  else if (os.toUpperCase().contains("LINUX"))
  {
   if (bitness.endsWith("64"))
   {
    lib = new File("native/64x" + System.mapLibraryName("opencv_java2411"));
   }
   else
   {
    lib = new File("native/86x" + System.mapLibraryName("opencv_java2411"));
   }
  }
  
  System.out.println(lib.getAbsolutePath());
  System.load(lib.getAbsolutePath());

Insert the above code block inside your class. Then you can run the previous demo code without using the 'System.loadLibrary(Core.NATIVE_LIBRARY_NAME);' line, because we have already loaded the library from the above block.

Following is the complete code. I have loaded the library inside the main method. In your applications you can use it inside a Static code block according to your application.
import java.io.File;

import org.opencv.core.CvType;
import org.opencv.core.Mat;

public class Main
{
 public static void main(String[] args)
 {
  File lib = null;
  String os = System.getProperty("os.name");
  String bitness = System.getProperty("sun.arch.data.model");
  
  if (os.toUpperCase().contains("WINDOWS"))
  {
   if (bitness.endsWith("64"))
   {
    lib = new File("lib/opencv/64x" + System.mapLibraryName("opencv_java2411"));
   }
   else
   {
    lib = new File("lib/opencv/86x" + System.mapLibraryName("opencv_java2411"));
   }
  }
  else if (os.toUpperCase().contains("LINUX"))
  {
   if (bitness.endsWith("64"))
   {
    lib = new File("lib/opencv/64x" + System.mapLibraryName("opencv_java2411"));
   }
   else
   {
    lib = new File("lib/opencv/86x" + System.mapLibraryName("opencv_java2411"));
   }
  }
  
  System.out.println(lib.getAbsolutePath());
  System.load(lib.getAbsolutePath());
  
  Mat mat = Mat.eye(3, 3, CvType.CV_8UC1);
        System.out.println("mat = " + mat.dump());
 }
}


Here my native .dll and .so files are inside a folder named 'lib/opencv/'.


You will get the following output. 

Hope this helps.

Thank you..

:-)

Sunday, June 14, 2015

JOptionPane with Multiple Inputs

Assume that you want to provide a JOptionPane, Input Message Dialog with multiple input fields. There are several ways that you can do this. Among them this is one simple solution that you can try out.

Following is the Input Dialog that we are going to develop.


Following is the main method that you have to use in order to develop the JOptionPane with multiple inputs.
private void showMultipleInputMessageDialog() {

        textArea.setText("");
        JTextField textField1 = new JTextField();
        final JTextField textField2 = new JTextField();
        final JCheckBox checkBox = new JCheckBox();
        textField2.setEnabled(false);

        checkBox.addChangeListener(new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent e) {
                if (e.getSource() == checkBox) {
                    if (checkBox.isSelected()) {
                        textField2.setEnabled(true);
                    } else {
                        textField2.setEnabled(false);
                    }
                }
            }
        });

        Object[] inputFields = {"Enter Text 01", textField1,
                "Enable TextField 02", checkBox,
                "Enter Text 02", textField2};

        int option = JOptionPane.showConfirmDialog(this, inputFields, "Multiple Inputs", JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE);

        if (option == JOptionPane.OK_OPTION) {
            String text = textField1.getText() + "\n" + (checkBox.isSelected() ? "Checked" : "Unchecked") + "\n" + textField2.getText() + "\n";
            textArea.setText(text);
        }
    }

Following is the complete JFrame with the demo application.

package com.dummy.learning;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * Created by Kinath.
 */
public class ApplicationFrame extends JFrame implements ActionListener {

    private static ApplicationFrame instance;

    JPanel jPanel = new JPanel();
    JButton jButton = new JButton("Click");
    JTextArea textArea = new JTextArea(5, 100);
    GridBagLayout gridBagLayout1 = new GridBagLayout();
    GridBagLayout gridBagLayout2 = new GridBagLayout();

    public static ApplicationFrame getInstance() {
        if (instance == null) {
            instance = new ApplicationFrame();
        }
        return instance;
    }

    public ApplicationFrame() {
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(new Dimension(300, 250));
        this.setTitle("JOptionPane Demo");
        this.setResizable(false);
        setGui();
    }

    private void setGui() {
        this.setLayout(gridBagLayout1);
        this.getContentPane().add(jPanel, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 0, 0));
        jPanel.setLayout(gridBagLayout2);
        jPanel.setBorder(BorderFactory.createEtchedBorder());
        jButton.setMinimumSize(new Dimension(100, 25));
        jButton.setMaximumSize(new Dimension(100, 25));
        jButton.setPreferredSize(new Dimension(100, 25));
        jButton.addActionListener(this);
        jPanel.add(jButton, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
        jPanel.add(textArea, new GridBagConstraints(0, 1, 1, 1, 1.0, 1.0, GridBagConstraints.SOUTH, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 0, 0));
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == jButton) {
            showMultipleInputMessageDialog();
        }
    }

    private void showMultipleInputMessageDialog() {

        textArea.setText("");
        JTextField textField1 = new JTextField();
        final JTextField textField2 = new JTextField();
        final JCheckBox checkBox = new JCheckBox();
        textField2.setEnabled(false);

        checkBox.addChangeListener(new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent e) {
                if (e.getSource() == checkBox) {
                    if (checkBox.isSelected()) {
                        textField2.setEnabled(true);
                    } else {
                        textField2.setEnabled(false);
                    }
                }
            }
        });

        Object[] inputFields = {"Enter Text 01", textField1,
                "Enable TextField 02", checkBox,
                "Enter Text 02", textField2};

        int option = JOptionPane.showConfirmDialog(this, inputFields, "Multiple Inputs", JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE);

        if (option == JOptionPane.OK_OPTION) {
            String text = textField1.getText() + "\n" + (checkBox.isSelected() ? "Checked" : "Unchecked") + "\n" + textField2.getText() + "\n";
            textArea.setText(text);
        }
    }
}

Hope that helps.
Thank You. :-)

Sunday, May 24, 2015

Java Grid Bag Layout Tutorial

Hi All,

Today we are going to learn how we can use Java GridBagLayout to develop you GUI for your application. GridBagLayout is a flexible layout manager that comes with java.

According to oracle documentation,

A GridBagLayout places components in a grid of rows and columns, allowing specified components to span multiple rows or columns. Not all rows necessarily have the same height. Similarly, not all columns necessarily have the same width. Essentially, GridBagLayout places components in rectangles (cells) in a grid, and then uses the components' preferred sizes to determine how big the cells should be.

A component is placed and positioned inside a container by specifying the ‘GridBagConstraints’ for each component. When you are adding the component inside the container, you can provide GridBagConstraints object as a parameter.

It’s important to understand each parameter of the GridBagConstraints constructor. Therefore please go through the following document to get a good understanding about them.

Let’s go through a demo GUI application and learn how to do it.
Following is the GUI that we are going to develop. This sketch was developed using Pencil (http://pencil.evolus.vn/).


Before developing the GUI, we should first understand the Grid we are positioning our components. Following is how I have divided the main frame as a grid, so that the main panels get positioned in the given space.


I am using IntelliJ Idea 14 to develop this Demo Application.

Following are the initial Classes developed to setup the main panel.

Left-Top-Panel
This panel contains a JTabbedPane and a JTable which is positioned in NORTH and SOUTH cells inside the panel. For the ‘fill’ parameter in GridBagConstraints I have used BOTH in order to make the component fill its display area entirely.

package com.dummyscodes.learning;

import javax.swing.*;
import java.awt.*;

/**
 * Created by Kinath on 05/04/2015.
 */
public class LeftTopPanel extends JPanel {

    private JTabbedPane jTabbedPane;
    private JPanel panel01;
    private JPanel panel02;
    private JPanel panel03;
    private JTable jTable;
    private GridBagLayout gridBagLayoutLeftTop;
    private JScrollPane jScrollPane;

    public LeftTopPanel() {
        setupGui();
    }

    private void setupGui() {
        jTabbedPane = new JTabbedPane();
        panel01 = new JPanel();
        panel02 = new JPanel();
        panel03 = new JPanel();
        jTable = new JTable();

        gridBagLayoutLeftTop = new GridBagLayout();

        this.setBorder(BorderFactory.createTitledBorder("Left-Top-Panel"));
        this.setLayout(gridBagLayoutLeftTop);

        jTabbedPane.add("Banana", panel01);
        jTabbedPane.add("Pummelo", panel02);
        jTabbedPane.add("Mango", panel03);

        // Create columns names
        String columnNames[] = {"Column 1", "Column 2", "Column 3", "Column 4"};

        // Create some data
        String dataValues[][] =
                {
                        {"12", "234", "67", "52"},
                        {"-123", "43", "853", "234"},
                        {"93", "89.2", "109", "23"},
                        {"279", "9033", "3092", "2342"},
                        {"12", "234", "67", "52"},
                        {"-123", "43", "853", "234"},
                        {"93", "89.2", "109", "23"},
                        {"279", "9033", "3092", "2342"},
                        {"12", "234", "67", "52"},
                        {"-123", "43", "853", "234"},
                        {"93", "89.2", "109", "23"},
                        {"279", "9033", "3092", "2342"},
                        {"12", "234", "67", "52"},
                        {"-123", "43", "853", "234"},
                        {"93", "89.2", "109", "23"},
                        {"279", "9033", "3092", "2342"}
                };

        jTable = new JTable(dataValues, columnNames);
        jScrollPane = new JScrollPane(jTable);

        this.add(jTabbedPane, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.NORTH, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 0, 0));
        this.add(jScrollPane, new GridBagConstraints(0, 1, 1, 1, 1.0, 1.0, GridBagConstraints.SOUTH, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 0, 0));
    }
}
Right-Top-Panel 
This panel also uses simple GridBagConstraints. Here I have divided the right-top-panel into 3 vertical cells and positioned the components inside them. TextField and JButton are allowed to fill the area in HORIZONTAL way. JScrollpane is allowed to fill the entire area.
package com.dummyscodes.learning;

import javax.swing.*;
import java.awt.*;

/**
 * Created by Kinath on 05/04/2015.
 */
public class RightTopPanel extends JPanel {

    JTextField textField = new JTextField();
    JButton addButton = new JButton();
    JList jList;
    JScrollPane jScrollPane;
    GridBagLayout gridBagLayout = new GridBagLayout();

    public RightTopPanel() {
        setupGui();
    }

    private void setupGui() {
        this.setBorder(BorderFactory.createTitledBorder("Right-Top-Panel"));
        this.setLayout(gridBagLayout);

        String[] items = {"Item 01", "Item 02", "Item 03", "Item 04", "Item 05", "Item 06", "Item 07", "Item 08", "Item 09", "Item 10"};
        jList = new JList(items);
        jScrollPane = new JScrollPane(jList);

        int width = this.getWidth();
        Dimension dimension = new Dimension(width, 25);
        addButton.setPreferredSize(dimension);
        addButton.setMinimumSize(dimension);
        addButton.setMaximumSize(dimension);
        addButton.setText("Add");

        textField.setPreferredSize(dimension);
        textField.setMinimumSize(dimension);
        textField.setMaximumSize(dimension);

        this.add(textField, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
        this.add(addButton, new GridBagConstraints(0, 1, 1, 1, 1.0, 1.0, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
        this.add(jScrollPane, new GridBagConstraints(0, 2, 1, 1, 1.0, 1.0, GridBagConstraints.NORTH, GridBagConstraints.BOTH, new Insets(2, 2, 2, 2), 0, 0));

    }
}
Right-Bottom-Panel
Same as the above layouts.
package com.dummyscodes.learning;

import javax.swing.*;
import java.awt.*;

/**
 * Created by Kinath on 05/04/2015.
 */
public class RightBottomPanel extends JPanel {

    JLabel label01 = new JLabel("Text Label Text");
    JLabel label02 = new JLabel("Text Label Text");
    JRadioButton radio01 = new JRadioButton("Radio Button 01");
    JRadioButton radio02 = new JRadioButton("Radio Button 02");
    JRadioButton radio03 = new JRadioButton("Radio Button 03");
    JSpinner spinner = new JSpinner();
    GridBagLayout gridBagLayout = new GridBagLayout();

    public RightBottomPanel() {
        setupGui();
    }

    private void setupGui()
    {
        this.setBorder(BorderFactory.createTitledBorder("Right-Bottom-Panel"));
        this.setLayout(gridBagLayout);

        this.add(label01 ,  new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
        this.add(radio01 ,  new GridBagConstraints(0, 1, 1, 1, 1.0, 1.0, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
        this.add(radio02 ,  new GridBagConstraints(0, 2, 1, 1, 1.0, 1.0, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
        this.add(radio03 ,  new GridBagConstraints(0, 3, 1, 1, 1.0, 1.0, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
        this.add(label02 ,  new GridBagConstraints(0, 4, 1, 1, 1.0, 1.0, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
        this.add(spinner ,  new GridBagConstraints(0, 5, 1, 1, 1.0, 1.0, GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
    }
}

Bottom-Panel 
This panel consists of horizontally placed set of buttons on a horizontal grid cells. Here the buttons are not allowed to resize. They keep their original size.
package com.dummyscodes.learning;

import javax.swing.*;
import java.awt.*;

/**
 * Created by Kinath on 05/04/2015.
 */
public class BottomPanel extends JPanel {

    private JButton btn01 = new JButton();
    private JButton btn02 = new JButton();
    private JButton btn03 = new JButton();
    private JButton btn04 = new JButton();
    private JCheckBox checkBox01 = new JCheckBox();
    private JCheckBox checkBox02 = new JCheckBox();
    private GridBagLayout gridBagLayout = new GridBagLayout();

    public BottomPanel() {
        setupGUI();
    }

    private void setupGUI() {
        int width = this.getWidth();
        this.setBorder(BorderFactory.createTitledBorder("Bottom-Panel"));
        this.setPreferredSize(new Dimension(width,80));
        this.setMinimumSize(new Dimension(width,80));
        this.setMaximumSize(new Dimension(width,80));
        this.setLayout(gridBagLayout);

        Dimension btnDimension = new Dimension(100,25);
        btn01.setMaximumSize(btnDimension);
        btn02.setMaximumSize(btnDimension);
        btn03.setMaximumSize(btnDimension);
        btn04.setMaximumSize(btnDimension);

        btn01.setMinimumSize(btnDimension);
        btn02.setMinimumSize(btnDimension);
        btn03.setMinimumSize(btnDimension);
        btn04.setMinimumSize(btnDimension);

        btn01.setPreferredSize(btnDimension);
        btn02.setPreferredSize(btnDimension);
        btn03.setPreferredSize(btnDimension);
        btn04.setPreferredSize(btnDimension);

        btn01.setText("Button 01");
        btn02.setText("Button 02");
        btn03.setText("Button 03");
        btn04.setText("Button 04");

        checkBox01.setText("Checkbox 01");
        checkBox02.setText("Checkbox 02");

        this.add(btn01, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
        this.add(btn02, new GridBagConstraints(1, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
        this.add(btn03, new GridBagConstraints(2, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
        this.add(btn04, new GridBagConstraints(3, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));

        this.add(checkBox01, new GridBagConstraints(4, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
        this.add(checkBox02, new GridBagConstraints(5, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
    }

}

MainPanel
MainPanel.java uses the GridBagLayout to position the panels according to the specified GridBagConstraints.
package com.dummyscodes.learning;

import javax.swing.*;
import java.awt.*;

/**
 * Created by Kinath on 05/04/2015.
 */
public class MainPanel extends JPanel {

    private LeftTopPanel leftTopPanel;
    private RightTopPanel rightTopPanel;
    private RightBottomPanel rightBottomPanel;
    private BottomPanel bottomPanel;
    private GridBagLayout gridBagLayoutMain;
    private JPanel topMainPanel;

    public MainPanel() {
        setupGui();
    }

    private void setupGui() {

        topMainPanel = new JPanel();
        gridBagLayoutMain = new GridBagLayout();
        leftTopPanel = new LeftTopPanel();
        rightBottomPanel = new RightBottomPanel();
        rightTopPanel = new RightTopPanel();
        bottomPanel = new BottomPanel();

        this.setBorder(BorderFactory.createTitledBorder("Main-Panel"));
        this.setLayout(gridBagLayoutMain);
        this.add(leftTopPanel, new GridBagConstraints(0, 0, 1, 2, 1, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 0, 0));
        this.add(rightTopPanel, new GridBagConstraints(1, 0, 1, 1, 1, 1, GridBagConstraints.NORTHEAST, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 0, 0));
        this.add(rightBottomPanel, new GridBagConstraints(1, 1, 1, 1, 1, 1, GridBagConstraints.EAST, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 0, 0));
        this.add(bottomPanel, new GridBagConstraints(0, 2, 2, 1, 1, 0, GridBagConstraints.SOUTH, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
    }

}


package com.dummyscodes.learning;

import javax.swing.*;
import java.awt.*;

/**
 * Created by Kinath on 02/04/2015.
 */
public class ApplicationFrame extends JFrame
{
    private static ApplicationFrame instance = null;
    private MainPanel mainPanel;
    private GridBagLayout gridBagLayoutAppFrame;

    private ApplicationFrame()
    {
        setupGUI();
    }

    public static ApplicationFrame getInsance()
    {
        if(instance == null)
        {
            instance = new ApplicationFrame();
        }
        return  instance;
    }

    public void setupGUI()
    {
        this.setTitle("Demo Application");
        this.setMinimumSize(new Dimension(800,600));
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        gridBagLayoutAppFrame = new GridBagLayout();
        mainPanel = new MainPanel();
        this.setLayout(gridBagLayoutAppFrame);
        this.getContentPane().add(mainPanel,new GridBagConstraints(0,0,1,1,1,1,GridBagConstraints.CENTER,GridBagConstraints.BOTH,new Insets(10,10,10,10),0,0));
    }
}


package com.dummyscodes.learning;

/**
 * Created by Kinath on 02/04/2015.
 */
public class Main {

    public static void main(String[] args) {

        ApplicationFrame app = ApplicationFrame.getInsance();
        app.setVisible(true);
    }

}


That’s it.
Hope that helps.
Thanks.

Thursday, March 26, 2015

When to Use String/StringBuilder/String Buffer during Concatenation

When you want the String concatenation to be done at compile time, then you can use the normal '+' operator, otherwise String.concat() to do it. This is efficient at the compile time.

But when you are using the concatenation at the run time, you have to do it using StringBuilder or String Buffer. 

We have to identify the difference between these two. StringBuilder is NOT Synchronized and StringBuffer is Synchronized. Therefore when you want to work in a thread safe environment you have to use StringBuffer. Otherwise you have to use the StringBuilder. That would make the concatenation faster at runtime. 

References : 

Wednesday, August 27, 2014

Write Excel File Using Apache POI in Java

Hi All,

Editing Microsoft documents using a java program might be useful in certain cases. For that there are various libraries. Here I'm going to show you how you can use the Apache POI with Microsoft Documents. More details are available here.

I had to use Apache POI to create and write values received from Arduino, to an Excel Sheet. So here I'm going to show you how you can write values to an Excel Sheet.

First download the latest release from Apache POI. It can be downloaded from here.

Create a new project in Eclipse and create a new class named 'WriteExcel.java'. Add a new folder to the project named 'lib'. Extract the Apache POI library and copy the 'poi-3.10.1-20140818.jar' to the lib folder. Then add the jar to the project by Right Click the Project -> Build Path -> Configure Build Path -> Add JARs.



Now we can start coding the 'WriteExcel.java' class.
Following is the complete code.

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.WorkbookUtil;


public class WriteExcel {
 
 public static void main(String[] args) {
  Workbook workbook = new HSSFWorkbook(); //Create a workbook object
  
  //Create a sheet inside the workbook. There are several ways to do this. 
  //1.Create sheet with default name
  Sheet sheet1 = workbook.createSheet(); 
  //2.Create Sheet with Valid Name
  Sheet sheet2 = workbook.createSheet("ValidName"); 
  //3.Create Sheet with any (may be invalid) name
  //createSafeSheetName() will make it correct
  Sheet sheet3 = workbook.createSheet(WorkbookUtil.createSafeSheetName("%?%#23InvalidName"));
  
  //Let's write some values to rows and columns in sheet1
  
  for (int i = 0; i < 20; i++) {
   //Create a row in sheet 1 assign it to "Row" object.
   Row row = sheet1.createRow(i);
   for (int j = 0; j < 10; j++) {
    //Create a cell in 'row' and assign it to "Cell" object
    Cell cell = row.createCell(j);
    //Write Values to Cell
    cell.setCellValue("( "+i+","+j+" )");
   }
  }
  
  try {
   //Create a new file output stream to write data to a File
   FileOutputStream fileOutputStream = new FileOutputStream("FirstExcel.xls");
   //Write values to the file
   workbook.write(fileOutputStream);
   //Cose file output stream
   fileOutputStream.close();
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 
}

Now run the file and once you refresh the project, you'll see the "FirstExcel.xls" file added to your project. Open it. Following is the output.


Hope that helps, 
Thank You. :-) 

Thursday, August 7, 2014

Using JFreeChart to Show Arduino Data

Hi All,

In the previous tutorial I showed you how we can develop a simple chart application using JFreeChart. Now let's do something interesting with that. We are going to read some data from a Arduino and show that in a java chart. We are using the Java RxTx library for communication and JFreeChart for displaying the chart. Lets' start then.

First we will write a simple application that would send some random data from Arduino. There are situations where you have to send some sensor values for processing in a Java application. So here I'm trying to send some values that will appear like some sensor values.

float sensor_values[3]; //declare an arrary of 3 float values
float val_1,val_2,val_3; //declare 3 sensor values

void setup()
{
  Serial.begin(9600); //Start serial
  
  // Generate 3 random numbers between -100 and +100
  val_1 = random(-100,100); 
  val_2 = random(-100,100);
  val_3 = random(-100,100);
  
}

void loop()
{
  //if any value is equal to 100 start again from -100  
  if(val_1 >= 100){
    val_1 = -100;
  }
  else{
    val_1++;
  }
  
  if(val_2 >= 100){
    val_2 = -100;
  }
  else{
    val_2++;
  }
  
  if(val_3 >= 100){
      val_3 = -100;
  }  
  else{
    val_3++;
  }
  
  // Assign the values to array
  sensor_values[0] = val_1;
  sensor_values[1] = val_2;
  sensor_values[2] = val_3;
  
  //call the write sensor values function to write the values to serial port
  writeSensorValues(sensor_values);
}

//Method that will write the values to the serial port
void writeSensorValues(float values [])
{
  Serial.print("STX,"); //STX is used to identify the start of the string
  for(int i = 0 ; i < 3 ; i++){
    Serial.print(values[i]);
    Serial.print(","); // Seperate each value with ',' to identify them seperately
  }
  Serial.println("ETX"); //ETX is used to identify the end of the string
}

Now the Arduino code is complete. You can upload this code to your Arduino and check the output using the Serial Monitor.
Our next step is to write the Java Program that will read from the Arduino and display that data in a chart. I will get the help of the tutorials on Java RxTx for Serial Communication and JFree Chart tutorial to do this. I have described how to add the RxTx and JFreeChart libraries to the project in the above tutorials.

First create a class named 'SerialChart.java' and extend it from the ApplicationFrame class and implement the SerialPortEventListener class. Then add the constructor and add the unimplemented methods.



Now let's declare the variables that we need to use.

 private TimeSeriesCollection timeSeriesCollection; // Collection of time series data
 private XYDataset xyDataset; // dataset that will be used for the chart
 private TimeSeries seriesX; // X series data
 private TimeSeries seriesY; // Y series data
 private TimeSeries seriesZ; // X series data
 
 private BufferedReader input; // input reader
 private OutputStream output; //output reader
 private SerialPort serialPort; // serial port object
 
 private String [] PORT_NAMES = {"COM7"}; // available ports

Then let's start with a method that will initialize the serial port connection.

private void initializeSerial()
 {
  CommPortIdentifier portId = null;
  Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
  
  while(portEnum.hasMoreElements())
  {
   CommPortIdentifier currentPortIdentifier = (CommPortIdentifier)portEnum.nextElement();
   for(String portName : PORT_NAMES)
   {
    if(currentPortIdentifier.getName().equals(portName))
    {
     portId = currentPortIdentifier;
     break;
    }
   }   
  }
  
  if(portId == null)
  {
   System.out.println("Port not found");
   return;
  }
  
  try {
   
   serialPort = (SerialPort)portId.open(this.getClass().getName(), 2000);
   serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
   
   input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
   output = serialPort.getOutputStream();
   
   serialPort.addEventListener(this);
   serialPort.notifyOnDataAvailable(true);
   
  } catch (Exception e) {
   System.err.println("Initialization failed : " + e.toString());
  }
 }

Now let's create the method to return a chart object.

 private JFreeChart createChart() {

        JFreeChart chart = ChartFactory.createTimeSeriesChart(
            "Sensor Data Display",  // title
            "Time",             // x-axis label
            "Sensor Value",   // y-axis label
            timeSeriesCollection,            // data
            true,               // create legend?
            true,               // generate tooltips?
            false               // generate URLs?
        );

        chart.setBackgroundPaint(Color.white);

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

        DateAxis axis = (DateAxis) plot.getDomainAxis();
        axis.setAutoRange(true);
  axis.setFixedAutoRange(60000.0);

        return chart;
 }

We can complete the constructor now.

public SerialChart(String title) {
  super(title);
  
  initializeSerial();
  
  timeSeriesCollection = new TimeSeriesCollection();
  seriesX = new TimeSeries("SensorX");
  seriesY = new TimeSeries("SensorY");
  seriesZ = new TimeSeries("SensorZ");
  
  timeSeriesCollection.addSeries(seriesX);
  timeSeriesCollection.addSeries(seriesY); 
  timeSeriesCollection.addSeries(seriesZ);
  
  JFreeChart chart = createChart();
  ChartPanel chartPanel = new ChartPanel(chart);
  chartPanel.setFillZoomRectangle(true);
  chartPanel.setMouseWheelEnabled(true);
  chartPanel.setPreferredSize(new java.awt.Dimension(1000,500));
  setContentPane(chartPanel);
 }

Next we have to complete the serialEvent method so that it will respond to the data received from Arduino.


 @Override
 public synchronized void serialEvent(SerialPortEvent event) {
  if(event.getEventType() == SerialPortEvent.DATA_AVAILABLE)
  {
   try
   {
    String inputLine = input.readLine();
    String [] inputValues = inputLine.split(",");
    
    if(inputValues[0].equals("STX") && inputValues[inputValues.length-1].equals("ETX"))
    {
     float in_x = new Float(inputValues[1]).floatValue();
     float in_y = new Float(inputValues[2]).floatValue();
     float in_z = new Float(inputValues[3]).floatValue();
     
     this.timeSeriesCollection.getSeries(0).add(new Millisecond(),in_x);
     this.timeSeriesCollection.getSeries(1).add(new Millisecond(),in_y);
     this.timeSeriesCollection.getSeries(2).add(new Millisecond(),in_z);
    }
    
    System.out.println(inputLine);
   }
   catch(Exception ex)
   {
    ex.printStackTrace();
   }
  }
 }

We also have to write a method to properly close the serial port event.

public synchronized void close()
 {
  if(serialPort != null)
  {
   serialPort.removeEventListener();
   serialPort.close();
  }
 }

Finally it's the main method to bring everything together.

 public static void main(String[] args) {

  SerialChart serialChartDemo = new SerialChart("Time Series Chart Demo");
        serialChartDemo.pack();
        RefineryUtilities.centerFrameOnScreen(serialChartDemo);
        serialChartDemo.setVisible(true);

    }

Now run the application and see the results :-). You'll get an output like this.


Following is the complete code. 

package com.dc.rxtxjfreechart;

import java.awt.Color;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Enumeration;

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.time.Millisecond;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;

public class SerialChart extends ApplicationFrame implements SerialPortEventListener {

 private TimeSeriesCollection timeSeriesCollection; // Collection of time series data
 private XYDataset xyDataset; // dataset that will be used for the chart
 private TimeSeries seriesX; // X series data
 private TimeSeries seriesY; // Y series data
 private TimeSeries seriesZ; // X series data
 
 private BufferedReader input; // input reader
 private OutputStream output; //output reader
 private SerialPort serialPort; // serial port object
 
 private String [] PORT_NAMES = {"COM7"}; // available ports
 
 public SerialChart(String title) {
  super(title);
  
  initializeSerial();
  
  timeSeriesCollection = new TimeSeriesCollection();
  seriesX = new TimeSeries("SensorX");
  seriesY = new TimeSeries("SensorY");
  seriesZ = new TimeSeries("SensorZ");
  
  timeSeriesCollection.addSeries(seriesX);
  timeSeriesCollection.addSeries(seriesY); 
  timeSeriesCollection.addSeries(seriesZ);
  
  JFreeChart chart = createChart();
  ChartPanel chartPanel = new ChartPanel(chart);
  chartPanel.setFillZoomRectangle(true);
  chartPanel.setMouseWheelEnabled(true);
  chartPanel.setPreferredSize(new java.awt.Dimension(1000,500));
  setContentPane(chartPanel);
 }

 @Override
 public synchronized void serialEvent(SerialPortEvent event) {
  if(event.getEventType() == SerialPortEvent.DATA_AVAILABLE)
  {
   try
   {
    String inputLine = input.readLine();
    String [] inputValues = inputLine.split(",");
    
    if(inputValues[0].equals("STX") && inputValues[inputValues.length-1].equals("ETX"))
    {
     float in_x = new Float(inputValues[1]).floatValue();
     float in_y = new Float(inputValues[2]).floatValue();
     float in_z = new Float(inputValues[3]).floatValue();
     
     this.timeSeriesCollection.getSeries(0).add(new Millisecond(),in_x);
     this.timeSeriesCollection.getSeries(1).add(new Millisecond(),in_y);
     this.timeSeriesCollection.getSeries(2).add(new Millisecond(),in_z);
    }
    
    System.out.println(inputLine);
   }
   catch(Exception ex)
   {
    ex.printStackTrace();
   }
  }
 }
 
 private void initializeSerial()
 {
  CommPortIdentifier portId = null;
  Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
  
  while(portEnum.hasMoreElements())
  {
   CommPortIdentifier currentPortIdentifier = (CommPortIdentifier)portEnum.nextElement();
   for(String portName : PORT_NAMES)
   {
    if(currentPortIdentifier.getName().equals(portName))
    {
     portId = currentPortIdentifier;
     break;
    }
   }   
  }
  
  if(portId == null)
  {
   System.out.println("Port not found");
   return;
  }
  
  try {
   
   serialPort = (SerialPort)portId.open(this.getClass().getName(), 2000);
   serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
   
   input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
   output = serialPort.getOutputStream();
   
   serialPort.addEventListener(this);
   serialPort.notifyOnDataAvailable(true);
   
  } catch (Exception e) {
   System.err.println("Initialization failed : " + e.toString());
  }
 }

 private JFreeChart createChart() {

        JFreeChart chart = ChartFactory.createTimeSeriesChart(
            "Sensor Data Display",  // title
            "Time",             // x-axis label
            "Sensor Value",   // y-axis label
            timeSeriesCollection,            // data
            true,               // create legend?
            true,               // generate tooltips?
            false               // generate URLs?
        );

        chart.setBackgroundPaint(Color.white);

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

        DateAxis axis = (DateAxis) plot.getDomainAxis();
        axis.setAutoRange(true);
  axis.setFixedAutoRange(60000.0);

        return chart;
 }

 public synchronized void close()
 {
  if(serialPort != null)
  {
   serialPort.removeEventListener();
   serialPort.close();
  }
 }
 
 public static void main(String[] args) {

  SerialChart serialChartDemo = new SerialChart("Time Series Chart Demo");
        serialChartDemo.pack();
        RefineryUtilities.centerFrameOnScreen(serialChartDemo);
        serialChartDemo.setVisible(true);

    }
}




Hope that helps. Thank You. :-) 

Tuesday, August 5, 2014

Develop a Time Series Chart Using JFreeChart

Hi All,

When we want to show a chart in our java application we can use JFreeChart library for that. Here I am going to show you how we can develop a Time Series Chart. Later we will be using this chart to display values returned from an Arduino Sensor. So lets get started.

First we have to download the JFreeChart library, extract it to a location and find the necessary jar files. You can download JFreeChart here. JFreeChart site is here.

Create a new project in Eclipse and make a folder named 'lib' inside the project folder. Then extract the library zip file and copy the 'jfreechart-1.0.19' and 'jcommon-1.0.23' jars to the 'lib' folder. Then Right Click on the project -> Build Path -> Configure Build Path -> Libraries -> Add JARs and add the two jar files in the 'lib' folder to the project.

Create a class named 'JFreeDemo1.java' and extend it from the 'ApplicationFrame' class. Then add the constructor.










Then let's create the method to generate the dataset. Here we are using a XYDataset with Time Series Collection. There are two Time Series Used here. You can add Time Series to the Time Series Collection.


private XYDataset createXYDataSet()
 {  
  TimeSeriesCollection dataset = new TimeSeriesCollection();
  TimeSeries series2012 = new TimeSeries("Car Sales");
  TimeSeries series2013 = new TimeSeries("Van Sales");
  
  Random rand = new Random();
  
  for(int type = 0 ; type <2 ; type++ ){
   for(int mon = 1 ; mon < 13 ; mon++ )
   {
    Month month = new Month(mon, 2013); 
    int value = rand.nextInt(700)+300;
    
    if(type == 0)
    {
     series2012.add(month, value);
    }
    
    if(type == 1)
    {
     series2013.add(month, value);
    }
   }
  }
  
  dataset.addSeries(series2012);
  dataset.addSeries(series2013);
  
  return dataset;
 }


Now the dataset is ready. Next we will create a method that will return a JFreeChart. We are passing a dataset as parameter for the method. This data set will be used to create the chart.
private JFreeChart createChart(XYDataset dataset){
  JFreeChart chart = ChartFactory.createTimeSeriesChart(
      "Sales Chart", // Title
      "Month",     // Time Axis
      "Sales",     // Value Axis
      dataset,     // Dataset 
      true,      // legend
      true,      // tooltips
      false);     // generate urls
  
  XYPlot plot = (XYPlot)chart.getPlot();
  
  DateAxis dateAxis = (DateAxis)plot.getDomainAxis();
  dateAxis.setDateFormatOverride(new SimpleDateFormat("MMM-yyyy"));
  
  return chart;
 }
Now we will complete the constructor of the class.
public JFreeDemo1(String title) {
  super(title);
  JFreeChart chart = createChart(createXYDataSet());
  ChartPanel chartPanel = new ChartPanel(chart);
  chartPanel.setFillZoomRectangle(true);
  chartPanel.setMouseWheelEnabled(true);
  chartPanel.setPreferredSize(new java.awt.Dimension(800,400));
  setContentPane(chartPanel);
 }
Now we can complete the main method.
public static void main(String[] args) {
  JFreeDemo1 jfd = new JFreeDemo1("Time Series Chart Demo 01");
  jfd.pack();
  jfd.setVisible(true);
 }

Run the application and you will get a chart like this with the generated random dataset.
















Following is the complete code.

package com.dc.jfreedemo;

import java.text.SimpleDateFormat;
import java.util.Random;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.time.Month;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;
import org.jfree.ui.ApplicationFrame;

public class JFreeDemo1 extends ApplicationFrame{

 public JFreeDemo1(String title) {
  super(title);
  JFreeChart chart = createChart(createXYDataSet());
  ChartPanel chartPanel = new ChartPanel(chart);
  chartPanel.setFillZoomRectangle(true);
  chartPanel.setMouseWheelEnabled(true);
  chartPanel.setPreferredSize(new java.awt.Dimension(800,400));
  setContentPane(chartPanel);
 }
 
 private XYDataset createXYDataSet()
 {  
  TimeSeriesCollection dataset = new TimeSeriesCollection();
  TimeSeries series2012 = new TimeSeries("Car Sales");
  TimeSeries series2013 = new TimeSeries("Van Sales");
  
  Random rand = new Random();
  
  for(int type = 0 ; type <2 ; type++ ){
   for(int mon = 1 ; mon < 13 ; mon++ )
   {
    Month month = new Month(mon, 2013); 
    int value = rand.nextInt(700)+300;
    
    if(type == 0)
    {
     series2012.add(month, value);
    }
    
    if(type == 1)
    {
     series2013.add(month, value);
    }
   }
  }
  
  dataset.addSeries(series2012);
  dataset.addSeries(series2013);
  
  return dataset;
 }

 private JFreeChart createChart(XYDataset dataset){
  JFreeChart chart = ChartFactory.createTimeSeriesChart(
      "Sales Chart", // Title
      "Month",     // Time Axis
      "Sales",     // Value Axis
      dataset,     // Dataset 
      true,      // legend
      true,      // tooltips
      false);     // generate urls
  
  XYPlot plot = (XYPlot)chart.getPlot();
  
  DateAxis dateAxis = (DateAxis)plot.getDomainAxis();
  dateAxis.setDateFormatOverride(new SimpleDateFormat("MMM-yyyy"));
  
  return chart;
 }
 
 public static void main(String[] args) {
  JFreeDemo1 jfd = new JFreeDemo1("Time Series Chart Demo 01");
  jfd.pack();
  jfd.setVisible(true);
 }
}



Hope this was helpful :-) Thank You.

Saturday, August 2, 2014

Using Java RxTx library for Serial Communication With Arduino - Part 2

Hi All,

In the previous post I showed you how you can use the Java RxTx library to find the Arduino connected COM port. Now let's do something useful. We can use this for reading values sent from the Arduino. With the values, we can play around and do whatever we like. In this post I'm using the code provided by Arduino.

First let's write a tiny Arduino program that prints some strings to Serial.



Then lets use the code provided by Arduino for reading values from Arduino. So here it is. I have just modified the code to split the chunks from the input string. (Line 81)



So that it.

Hope it would help.

Thank you. :-)