0

I have written the code below in java to retrieve the value from database and stored in Json file. File name is DatabaseGraphValue.java.

package com;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.GraphValue;
import com.google.gson.Gson;


@WebServlet("/GraphJsonValueServlet")
public class DataBaseGraphValue extends HttpServlet
{
static Connection conn = null;
static PreparedStatement stmt;
static ResultSet rs;
String sql;
static String project="Project1";


public static Connection getDataBaseVale()
{
    if(conn != null)
    {
        return conn;
    }

    else
    {
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
                         conn=DriverManager.getConnection("jdbc:mysql://localhost:3309/graphvalue","root","root");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        return conn;
    }


}


public DataBaseGraphValue()
{
    super();
}

protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
{
    List<GraphValue> listOfGraphValue = getGraphValue();

    Gson gson = new Gson();

    String jsonString = gson.toJson(listOfGraphValue);

    response.setContentType("application/json");

    response.getWriter().write(jsonString);


}

private List<GraphValue> getGraphValue()
{
    conn = getDataBaseVale();

    List<GraphValue> listOfGraphValue = new ArrayList<GraphValue>();


    try 
    {
        stmt=conn.prepareStatement("select * from TestCase where ProjectName= ?");
        stmt.setString(1,project);
        rs=stmt.executeQuery();
        while(rs.next())
        {
            GraphValue gv1 = new GraphValue();
            gv1.setProjectName(rs.getString(1));
            gv1.setTotalTestCase(rs.getInt(2));
            gv1.setTestCaseExecuted(rs.getInt(3));
            gv1.setFailedTestCase(rs.getInt(4));
            gv1.setTestCaseNotExecuted(rs.getInt(2));

            listOfGraphValue.add(gv1);
        }
    } 
    catch (SQLException e) 
    {
        e.printStackTrace();
    }


    return listOfGraphValue;
}

}

And the other file name is GraphValue.java.

package com;

public class GraphValue {

private String projectName;
private int totalTestCase;
private int testCaseExecuted;
private int failedTestCase;
private int testCaseNotExecuted;

public String getProjectName()
{
    return projectName;
}

public void setProjectName(String projectName)
{
    this.projectName =  projectName;
}

public int getTotalTestCase()
{
    return totalTestCase;
}

public void setTotalTestCase(int totalTestCase)
{
    this.totalTestCase =  totalTestCase;
}

public int getTestCaseExecuted()
{
    return testCaseExecuted;
}

public void setTestCaseExecuted(int testCaseExecuted)
{
    this.testCaseExecuted =  testCaseExecuted;
}

public int getFailedTestCase()
{
    return failedTestCase;
}

public void setFailedTestCase(int failedTestCase)
{
    this.failedTestCase =  failedTestCase;
}

public int getTestCaseNotExecuted()
{
    return testCaseNotExecuted;
}

public void setTestCaseNotExecuted(int testCaseNotExecuted)
{
    this.testCaseNotExecuted =  testCaseNotExecuted;
}

}

Now I need help in writing a JavaScript so that I can access the value which I am retrieving from the database and can draw a graph. Below is my code where I want the Json data.

<html>
<head>
</head>
<body>
<select id="ChartType" name="ChartType" onchange="drawChart()">
<option value = "PieChart">Select Chart Type
<option value="PieChart">PieChart
<option value="Histogram">Histogram
<option value="LineChart">LineChart
<option value="BarChart">BarChart
</select>
<div id="chart_div" style="border: solid 2px #000000;"></div>
<p id="demo"></p>
<p id="demo1"></p>

 <script type="text/javascript" src="https://www.google.com/jsapi"></script>

 <script type="text/javascript">
 var row = [];
 var temp;
 var stri;
 google.load('visualization', '1.0', {'packages':['corechart']});
 google.setOnLoadCallback(getValues);
     function getValues() {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        stri = xmlhttp.responseText;
            drawChart();
        }
    };
    xmlhttp.open("GET", "sample.java", true);
    xmlhttp.send();
    }

    function drawChart() 
    {
    var data = new google.visualization.DataTable();
     ----How to get the jason data here for the graph

    }
    data.addRows(row);
    var a = document.getElementById("ChartType").value;
    document.getElementById("demo1").innerHTML = "You selected: " + a;
    var options = {'title':'How Much Pizza I Ate Last Night',
                   'width':400,
                   'height':300
                   };
    var chart = new  google.visualization[document.getElementById("ChartType").value](document.getElementById('chart_div'));
    chart.draw(data, options);
    }
</script>
</body>
</html>

Value which I am retrieving from the database is:

 ProjectName TotalTestCase TestCaseExecuted TestCaseFailed TestCaseNotExecuted    
 Project1       50              30              8                20

Please let me know how to proceed further. Thank you

halil
  • 800
  • 16
  • 33
Anubhav Mishra
  • 106
  • 2
  • 17
  • the xmlhttp object will have the data from the request - [MDN docs](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) – Jaromanda X Sep 06 '16 at 11:16
  • tip: drag yourself into the 21st century - no need for status and readystate gymnastics if you use the current spec for [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest) – Jaromanda X Sep 06 '16 at 11:19

1 Answers1

0

Pass xmlhttp.responseText to drawChart() at onreadystatechange handler

if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
  stri = xmlhttp.responseText;
  drawChart(stri);
}

at drawChart()

function drawChart(response) {
 var data = new google.visualization.DataTable();
 // How to get the jason data here for the graph
 // do stuff with `response`:`stri`
 console.log(response);
}
guest271314
  • 1
  • 15
  • 104
  • 177
  • Hi @guest271314, could you please share any links or example which will help me to understand this in a better way. Thank you – Anubhav Mishra Sep 06 '16 at 11:49
  • @AnubhavMishra There appears to be an extra `}` before `data.addRows(row);`? `XMLHttpRequest` `.onreadystatechange` handler returns results asynchronously. You need to pass the result to `drawChart()` as a parameter when you call `drawChart()`. See also [A: How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call/) – guest271314 Sep 06 '16 at 16:57
  • I am new to all this and getting confused. Could you please help me with the whole code if possible for you. Thank you – Anubhav Mishra Sep 07 '16 at 10:00