0

I have a .java class to read a mongodb collection and copy the contents into the .json file.

.json file is then provided to the chart (created using Fusion Charts as it only accepts data either in json format or in xml format) written in javascripts in html and then the chart is build on the basis of the data provided to the chart.

My requirement is to call a java class from java script so that it will get the data in .json file and chart would get created based on it.

How to do so?

    public class Write {

    //@SuppressWarnings("null")
    public void connect() throws Exception{

        MongoClient mongo = new MongoClient( "localhost" , 27017 );
        DB db = mongo.getDB("Age");
        DBCollection collection = db.getCollection("agegroup");



        try{

                File file = null;
                String content = "{ "+
      "  \"chart\": { \n"+ 

          "      \"caption\" : \"Weekly Sales Summary\" ,\n"+
           "  \"xAxisName\" : \"Week\",\n" +
              "  \"yAxisName\" : \"Sales\",\n"+
             " \"numberPrefix\" : \"$\" \n"+
        "},\n"+

         "\"data\":[\n";

                // if file doesnt exists, then create it
                file = new File("C:/Users/ila/Desktop/pie.json");


                file.createNewFile();


                FileWriter fw = new FileWriter(file.getAbsoluteFile());
                BufferedWriter bw = new BufferedWriter(fw);
                bw.write(content);

                DBObject s;


                String str;
                String delimiter=",";

                DBCursor cursorDoc = collection.find();
                while (cursorDoc.hasNext()) {
                    s=cursorDoc.next();

                     str=s.toString();
                     String[] str1= str.split(delimiter);

                            bw.write("{\n");
                            bw.write(str1[1]+", \n");
                            bw.write(str1[2]+"\n");

                            if(cursorDoc.hasNext())
                            bw.write(",");

                            System.out.println(Arrays.toString(str1));
                }

                bw.write("]\n");
                bw.write("}\n");

                bw.close();

                System.out.println("Done");

          }catch(Exception e){
             e.printStackTrace();
          }

    }
}

.html code

    <!DOCTYPE html>
<html>
<head>
<title>Pie chart</title>
<script type="text/javascript" src="fusioncharts/fusioncharts.js"></script>
<script type="text/javascript" src="fusioncharts/fusioncharts.charts.js"></script>
<script type="text/javascript" src="fusioncharts/themes/fusioncharts.theme.zune.js"></script>

<script type="text/javascript">

FusionCharts.ready(function(){

    var revenueChart = new FusionCharts({
     //type: "pie2d",
     type: "pie2d",
      renderAt: "chart-container",
      width: "430",
      height: "450",
      dataFormat: "json",

   events: {
       'slicingStart': function(evtObj, argObj){
           var label = argObj.data.categoryLabel;
          //  alert(label);
            var n= label.localeCompare("Teenage")
            if(n==0)
                {
                   alert("An alert Msg!!!Teenage");
                 //  document.getElementById('iframe1').contentWindow.location.reload();


                 parent.frames['iframe2'].location.href = parent.frames['iframe2'].location.href

                }
          //  document.getElementById("iframe_a").contentDocument.location.reload(true);

          var m= label.localeCompare("Child")
             if(m==0)
                {
                   alert("An alert Msg!!!Child");
 parent.frames['iframe2'].location.href = parent.frames['iframe2'].location.href

                }

          var l= label.localeCompare("Adult")
             if(l==0)
            {
               alert("An alert Msg!!!Adult");
parent.frames['iframe2'].location.href = parent.frames['iframe2'].location.href

            }

          var p= label.localeCompare("Senior")
             if(p==0)
            {
               alert("An alert Msg!!!Senior");
parent.frames['iframe2'].location.href = parent.frames['iframe2'].location.href

            }
       }
       }
  });
  revenueChart.setJSONUrl("pie.json");
 //  revenueChart.setJSONData("C:/data/db/Age.json");
     revenueChart.render("chart-container");
   }
);


</script>

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


</body>
</html>

3 Answers 3

1

Convert your Java Class into Servlet and using Ajax hit the servlet and do the required tasks. look into this link for a starter.

Sign up to request clarification or add additional context in comments.

Comments

0

You can either use a servet engine like tomcat, and write a servlet that will serve your JSON document, or use the com.sun.net.httpserver.* classes that is in the JRE.

Comments

0

Here you can take the use of REST client and ajax call in order to connect with the java class without the page refresh

For example let it be your ajax call.

$.ajax(
    {   url: 'in/your_class_name/path_name',
        type : 'POST',
        dataType: 'json',
        success : function (data) {
          //your script code
        },
        error:function(data,status,er) {
        alert("Error Loading Section Data: "+data);
    }
});

And then you need to configure your web.xml file as follows

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

  <display-name>Application Name</display-name>

      <context-param>
            <param-name>resteasy.servlet.mapping.prefix</param-name>
            <param-value>/in/</param-value>
      </context-param>

      <context-param>
            <param-name>resteasy.scan</param-name>
            <param-value>true</param-value>
      </context-param>

      <listener>
            <listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
      </listener>

      <filter>
            <filter-name>Resteasy</filter-name>
            <filter-class>org.jboss.resteasy.plugins.server.servlet.FilterDispatcher</filter-class>
      </filter>

      <filter-mapping>
            <filter-name>Resteasy</filter-name>
            <url-pattern>/in/*</url-pattern>
      </filter-mapping>

      <welcome-file-list>
        <welcome-file>index.html</welcome-file>    
      </welcome-file-list>

</web-app>

This is for jboss server for apache similar , and this configuarion you can google easily

Next is setting the class. In the java class the actions and class selections are controlled by annotation please look at the example below.

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;

import org.apache.commons.beanutils.BeanUtils;

@Path("/your_class_name")
public class Write {

    @Context
    HttpServletResponse res;

    @SuppressWarnings("unchecked")
    @POST
    @Produces("application/json")
    @Path("/path_name")
    public String your_function(@Context HttpServletRequest request )throws IOException{

        //your code
        return "succcess";
    }
}

Here your_class_name and path_name are the alternative names you are giving for access

And finally you need to download the jar file from the flowing link and add in your library

http://www.java2s.com/Code/Jar/c/Downloadcommonsbeanutils183jar.htm

3 Comments

Is there any other way without using servlet or applet?
this answer which i specified is without using servlet and applet. Here you are using the java class only. Just we are using the servlet features by HttpServletResponse and HttpServletRequest . here in one class you can write any number of functions. For accessing each function we are specifying the path using @path
here i just specified the changes. thats why i made the class name as write only. rest all same as yours.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.