Site icon FusionBrew – The FusionCharts Blog

Creating Charts using JSP and MongoDB

FusionCharts offers a set of JavaScript charts that use simple XML and JSON formats to feed data to the graphs. FusionCharts provides a large variety of different types of charts that you can use in your demos. JSP is one of the most widely used technologies that help software developers create dynamically generated web pages. While we already have detailed documentation on how JSP can be easily integrated with FusionCharts using the FusionCharts-JSP wrapper, this article talks about how you can use the MongoDB database along with FusionCharts and JSP for rendering charts. MongoDB, one of the most popular document-oriented databases, that also stores data records as documents, which helps in handling big data and provides high scalability and performance. In this article, we’ll explore how to integrate JSP with MongoDB and create a chart using FusionCharts. We choose MongoDB over others because it is an open-source and document-oriented. It works on the concept of document and collections, stored data in the JSON format and can also vary in structure as per the requirement.

Now, as we have covered the basics sufficiently, let’s get started with the steps to create charts using JSP and MongoDB…

To get the code (for creating charts) in this blog working, we need to first install the following components: Make sure that all the above mentioned components have been downloaded in your system. To setup MongoDB on your operating system, please refer to the documentation here. Next, we move on to how you can configure MongoDB and create a database Only three steps and we will be done with the database part! To know how you can set up MongoDb on your OS, refer to the documentation here. Step 1: Create a json file that contains the data that goes into the database and will be used as the source data for the chart. We’ll name this file as country.json.
[{
	"label": "China",
	"value": 8800.0
}, {
	"label": "India",
	"value": 5800.0
}, {
	"label": "United States",
	"value": 4200.0
}, {
	"label": "Indonesia",
	"value": 6200.0
}, {
	"label": "Australia",
	"value": 7900
}, {
	"label": "Brazil",
	"value": 4400.0
}]
Step 2: Import the .json file created in Step 1 into mongodb using the “mongoimport” command as shown below. Step 3: Next, open another shell to run the “mongo” command. Step 4: Now we need to verify if our data has been imported correctly into the database or no. To do this, you need to execute the following commands: You can import this demo database from here. With this, we are done with creating the database. Now we move on to creating chart objects and then finally rendering the chart. Step 1: Create a JSP page and import all the packages in a script tag. The code below imports the com.google.gson package that enables the conversion from JSON to Java and Java to JSON. Before getting into the code, let’s first talk about the google-gson library. The google-gson library: Now, here is the code to import the com.google.gson package:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="com.mongodb.*" %>
<%@page import="java.util.*" %>
<%@page import="com.google.gson.*" %>
<%@page import="fusioncharts.FusionCharts" %>
Click here for more information on google-gson package. Step 2: Establish database connectivity to fetch values from the database and place them inside a hashmap, as shown in the code snippet below.
<%

//Make sure you have included MongoDB jar files in order to use the MongoDB java driver classes

         Mongo mongoClient = new Mongo("localhost" , 27017 );
			
         //connecting to the database
         DB db = mongoClient.getDB( "fusioncharts" );
         System.out.println("Connected to database successfully");
         
         //Hashmap is created to store the values from the database
         HashMap<String,Integer> labelValue = new HashMap<String,Integer>();
         
         //fetching the collection from the database
        DBCollection collection = db.getCollection("simpledata");
        
        //Selects the documents in a collection and returns a cursor to the selected        documents
         DBCursor cursor = collection.find();
         
         while(cursor.hasNext()) {
           
             DBObject o = cursor.next();
             
                String label = (String) o.get("label") ; 
                int value = ((Number) o.get("value")).intValue();
              labelValue.put(label, value);
            
                }
  %>
Once the database connectivity is established, structure your data in the Fusioncharts format and convert the java objects to their JSON representation using the GSON library. Step 3: Finally, create a constructor and pass the necessary parameters to render the chart.
<%
    
            Gson gson = new Gson();
            
            // The 'chartobj' map object holds the chart attributes and data.
            chartobj.put("caption", "Split of Visitors by Age Group");
            chartobj.put("subCaption" , "Last year");
            chartobj.put("paletteColors" , "#0075c2");
            chartobj.put("bgColor" , "#ffffff");
            chartobj.put("showBorder" , "0");
            chartobj.put("theme","fint");
            chartobj.put("showPercentValues" , "1");
            chartobj.put("decimals" , "1");
            chartobj.put("captionFontSize" , "14");
            chartobj.put("subcaptionFontSize" , "14");
            chartobj.put("subcaptionFontBold" , "0");
            chartobj.put("toolTipColor" , "#ffffff");
            chartobj.put( "toolTipBorderThickness" , "0");
            chartobj.put("toolTipBgColor" , "#000000");
            chartobj.put("toolTipBgAlpha" , "80");
            chartobj.put("toolTipBorderRadius" , "2");
            chartobj.put("toolTipPadding" , "5");
            chartobj.put("showHoverEffect" , "1");
 
          // to store the entire data object
            ArrayList arrData = new ArrayList();
            for(Map.Entry m:labelValue.entrySet()) 
            {
                // to store the key value pairs of label and value object of the data object
                Map<String, String> lv = new HashMap<String, String>();
                lv.put("label", m.getKey().toString() );
                lv.put("value", m.getValue().toString());
                arrData.add(lv);             
            }
            //close the connection.
            cursor.close();
 
            //create 'dataMap' map object to make a complete FC datasource.
             Map<String, String> dataMap = new LinkedHashMap<String, String>();  
        /*
            gson.toJson() the data to retrieve the string containing the
            JSON representation of the data in the array.
        */
         dataMap.put("chart", gson.toJson(chartobj));
         dataMap.put("data", gson.toJson(arrData));

            FusionCharts columnChart= new FusionCharts(
            "column2d",// chartType
                        "chart1",// chartId
                        "600","400",// chartWidth, chartHeight
                        "chart",// chartContainer
                        "json",// dataFormat
                        gson.toJson(dataMap) //dataSource
                    );
            %>
                            
            <%=columnChart.render()%>
Given below is the full JSP code of the example we worked on:
<%-- 
    Document   : singleseries-mongodb-example
    Author     : fusioncharts
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="com.mongodb.*" %>
<%@page import="java.util.*" %>
<%@page import="com.google.gson.*" %>
<%@page import="fusioncharts.FusionCharts" %>

<%

         Mongo mongoClient = new Mongo("localhost" , 27017 );
			
         //connecting to the database
         DB db = mongoClient.getDB( "fusioncharts" );
         System.out.println("Connected to database successfully");
         
         //Hashmap is created to store the values from the database
         HashMap<String,Integer> labelValue = new HashMap<String,Integer>();
         
         //fetching the collection from the database
        DBCollection collection = db.getCollection("simpledata");
        
        //Selects the documents in a collection and returns a cursor to the selected documents
         DBCursor cursor = collection.find();

         while(cursor.hasNext()) {
           
             DBObject o = cursor.next();
             
                String label = (String) o.get("label") ; 
                int value = ((Number) o.get("value")).intValue();
              labelValue.put(label, value);
            
                }
  %>

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Creating Charts with Data from a Database - fusioncharts.com</title>

 
        <script src="fusioncharts.js"></script>
        <script src="fusioncharts.theme.fint.js"></script>
        <script src="fusioncharts.charts.js"></script>

    </head>
    <body>
         <div id="chart"></div>

        <%
         
            Gson gson = new Gson();
            
            // The 'chartobj' map object holds the chart attributes and data.
            chartobj.put("caption", "Split of Visitors by Age Group");
            chartobj.put("subCaption" , "Last year");
            chartobj.put("paletteColors" , "#0075c2");
            chartobj.put("bgColor" , "#ffffff");
            chartobj.put("showBorder" , "0");
            chartobj.put("theme","fint");
            chartobj.put("showPercentValues" , "1");
            chartobj.put("decimals" , "1");
            chartobj.put("captionFontSize" , "14");
            chartobj.put("subcaptionFontSize" , "14");
            chartobj.put("subcaptionFontBold" , "0");
            chartobj.put("toolTipColor" , "#ffffff");
            chartobj.put( "toolTipBorderThickness" , "0");
            chartobj.put("toolTipBgColor" , "#000000");
            chartobj.put("toolTipBgAlpha" , "80");
            chartobj.put("toolTipBorderRadius" , "2");
            chartobj.put("toolTipPadding" , "5");
            chartobj.put("showHoverEffect" , "1");
         
           // to store the entire data object
            ArrayList arrData = new ArrayList();
            for(Map.Entry m:labelValue.entrySet()) 
            {
                // to store the key value pairs of label and value object of the data object
                Map<String, String> lv = new HashMap<String, String>();
                lv.put("label", m.getKey().toString() );
                lv.put("value", m.getValue().toString());
                arrData.add(lv);             
            }
            //close the connection.
            cursor.close();
 
            //create 'dataMap' map object to make a complete FC datasource.
             Map<String, String> dataMap = new LinkedHashMap<String, String>();  
        /*
            gson.toJson() the data to retrieve the string containing the
            JSON representation of the data in the array.
        */
         dataMap.put("chart", gson.toJson(chartobj));
         dataMap.put("data", gson.toJson(arrData));

            FusionCharts columnChart= new FusionCharts(
            "column2d",// chartType
                        "chart1",// chartId
                        "600","400",// chartWidth, chartHeight
                        "chart",// chartContainer
                        "json",// dataFormat
                        gson.toJson(dataMap) //dataSource
                    );
            %>
            
<!--    Step 5: Render the chart    -->                
            <%=columnChart.render()%>
        
    </body>
</html>
Finally, simply run your JSP file using MongoDB. You output looks like as shown below: If you see any errors in your code, click here to download the complete source code of the sample project we have created for this tutorial.

Was There a Problem Rendering Charts?

In case something went wrong and you are unable to see the chart, check for the following:
Exit mobile version