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 Charts, a feature of MongoDB, allows for easy visualization of data stored in MongoDB databases. 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.
Table of Contents
What are MongoDB charts?
MongoDB Charts is a data visualization tool built for MongoDB. It enables users to generate, distribute, and integrate visual representations of their data. Its standout feature is its smooth integration with MongoDB, guaranteeing real-time data visualization as your databases evolve.Advantages of MongoDB Charts
MongoDB Charts provides numerous advantages compared to traditional relational databases:- Comprehensive cloud-based developer data platform.
- Flexible document schemas for versatile data structures.
- Widely supported with code-native data access for easy integration.
- Change-friendly design accommodating dynamic data.
- Powerful querying and analytics capabilities.
Disadvantages of MongoDB Charts
Here are several disadvantages of MongoDB Charts:- Transactions are limited to each document, which can be problematic for applications.
- MongoDB imposes a maximum document size limit of 16 MB
- MongoDB doesn’t support joins in the same way as relational databases
Now, as we have covered the basics sufficiently, let’s get started with the steps to create charts using JSP and MongoDB…
Creating Charts with JSP and MongoDB: A Step-by-Step Guide
To get the code (for creating charts) in this blog working, we need to first install the following components:- MongoDB [Download Link]
- MongoDB Driver for Java [Download Link]
- FusionCharts Suite XT [Download Link]
- FusionCharts JSP Wrapper [Download Link]
Quick MongoDB Setup: 3 Easy Steps
Setting up MongoDB is a straightforward process that can be completed in just a few steps.Step 1: Database Source Data in JSON
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: Importing Step 1 .json File
Import the .json file created in Step 1 into mongodb using the “mongoimport” command as shown below.
Step 3: Run ‘Mongo’ in a New Shell
Next, open another shell to run the “mongo” command.Step 4: Verifying Your Data
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:- Use the “show dbs” command to see your database. A list of the databases present is shown.
- From this list, select the required database using the “use ” command.
- Next, use the “show collections” command to see the collections inside your database.
- For seeing the contents of a specific collection, execute the “db..find().pretty()” command.
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 MongoDB charts.
How to Create and Render Charts
In this section, you’ll learn to create and render charts:Step 1: JSP Page with Google Gson Library
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:- Provides the toJson() and fromJson() methods for converting Java objects to JSON and the other way round
- Allows conversion of the already existing unmodifiable objects to and from JSON
- Supports Java Generics extensively
- Allows custom representations of objects
- Supports arbitrarily complex objects (with deep inheritance hierarchies and extensive use of generic types)
<%@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: Database Connection
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: Construct Chart with Parameters
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:- The chart ID should be unique for each chart rendered on the same page. Otherwise, it will result in a JavaScript error.
- If the chart does not show up at all, check if the fusioncharts.js and fusioncharts wrapper FusionCharts.java was loaded. Also, check if the path to fusioncharts.js and FusionCharts.java file is correct, and whether the file exists in that location.