How to Pass the hashmap value from a java file to Javascript - javascript

I am trying to retrieve the value from DataBase using Java File and storing it to HashMap. Please find the below code (Sample.java):
import java.sql.*;
import java.util.HashMap;
public class Sample {
static Connection conn;
static PreparedStatement stmt;
static ResultSet rs;
String sql;
static String project="Project1";
public static HashMap< String, String> map = new HashMap< String, String>();
public static void main(String[] args) {
try{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost:3309/graphvalue","root","root");
stmt=conn.prepareStatement("select * from TestCase where ProjectName= ?");
stmt.setString(1,project);
rs=stmt.executeQuery();
while(rs.next())
{
System.out.println(rs.getString(1)+" "+rs.getInt(2)+" "+rs.getInt(3)+" "+rs.getInt(4)+" "+rs.getInt(5));
map.put("ProjectName", rs.getString(1));
map.put("Total TestCase", String.valueOf(rs.getInt(2)));
map.put("TestCase Executed", String.valueOf(rs.getInt(3)));
map.put("Failed TestCase", String.valueOf(rs.getInt(4)));
map.put("TestCase Not Executed", String.valueOf(rs.getInt(5)));
System.out.println("ProjectName "+map.get("ProjectName"));
}
conn.close();
}
catch(Exception e)
{ System.out.println(e);}
}
}
Please find the below data which I am retrieving from the databse:
ProjectName TotalTestCase TestCaseExecuted TestCaseFailed TestCaseNotExecuted
Project1 50 30 8 20
I want to pass this value to Javascript and so that I am able to draw a chart using these values. Please find my HTML/Javascript code below (test.html):
<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();
str = stri.split(",");
// How to call the value from java file so that I will be able to draw the below graph by passing the value.
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>
Please let me know how to proceed or if anyone have any other example. Please share it with me. Thank you

You can convert your map to JSON. Instead of this
HelloWorld class, you can convert it into a service that returns this `JSON
import java.sql.*;
import java.util.HashMap;
public class Sample {
static Connection conn;
static PreparedStatement stmt;
static ResultSet rs;
String sql;
static String project = "Project1";
public static HashMap < String, String > map = new HashMap < String, String > ();
//Notice how your main class is now converted into a service
public static String getProjects() {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3309/graphvalue", "root", "root");
stmt = conn.prepareStatement("select * from TestCase where ProjectName= ?");
stmt.setString(1, project);
rs = stmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getString(1) + " " + rs.getInt(2) + " " + rs.getInt(3) + " " + rs.getInt(4) + " " +
rs.getInt(5));
map.put("ProjectName", rs.getString(1));
map.put("Total TestCase", String.valueOf(rs.getInt(2)));
map.put("TestCase Executed", String.valueOf(rs.getInt(3)));
map.put("Failed TestCase", String.valueOf(rs.getInt(4)));
map.put("TestCase Not Executed", String.valueOf(rs.getInt(5)));
System.out.println("ProjectName " + map.get("ProjectName"));
/*______________ NEW CODE ______________*/
JSONObject resultMap = new JSONObject(map);
return resultMap.toString();
}
} catch (Exception e) {
System.out.println(e);
} finally {
conn.close();
}
return "";
}
}
Now convert your test.html to test.jsp and call that service
that we've created in previous step and output the resultant JSON
into a javascript variable.
test.jsp
<%#page import="com.path.to.Sample"%>
<html>
<head>
<script>
<!-- call that service and output that json into a javascript variable -->
var resultantJSON = <%= Sample.getProjects() %>
<!-- Now all that's left is to parse that json -->
var projects = JSON.parse(resultantJSON);
</script>
</head>
<body>
...
...
</body>
</html>
Now all your results that you fetched from your database are in projects variable in Test.jsp. You can use them like conventional javascript object in your jsp file.

You have to make the Java code accessable via http. There are several ways to do this. You can implement a servlet which retrieves the http request and can send data back as httpresponse. Search for a tutorial on java servlet, e.g. like this http://www.tutorialspoint.com/servlets/servlets-first-example.htm
You could also use a java rest service to supply the information. Search for java rest tutorial, e.g. like this http://www.vogella.com/tutorials/REST/article.html

Related

Pass Javascript variable to java in jsp

After getting the user_name on client side using the below code :
<script type="text/javascript">
var WinNetwork = new ActiveXObject("WScript.Network");
var user_name = WinNetwork.UserName;
</script>
I was blocked how to pass the value of the variable "user_name" to the java code below,in order to test if this user exists on an oracle table :
<%
try {
ResultSet rs1 = stmt
.executeQuery("select * from utilisateur where upper(login) like upper('" + user_c + "')");
if (!rs1.next()) {
int i6 = stmt.executeUpdate("insert into utilisateur(login) values('" + user_c + "')");
}
}
catch (Exception e) {
System.out.print(e);
e.printStackTrace();
}
%>
In this case,you can’t get the user variable ,because jstl,el,is java code,when you render this page,it will go first ,then the html go second.
So you will see the blank in this two variable .

Javascript alert in code behind

I need to call Javascript alert function in c# method if web service is not available. I am using as.net core and webapi for webservice.
Here is the code
public List<EmployeeModel> GetEmployeeByEmpNo(string empNo)
{
try
{
string Baseurl = sys_ser.getApiURL();
EmployeeModel EmpInfo = new EmployeeModel();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(Baseurl);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage Res = client.GetAsync("api/Values/GetEmployeeByEmpNo/" + empNo).Result;
if (Res.IsSuccessStatusCode)
{
var EmpResponse = Res.Content.ReadAsStringAsync().Result;
var empobjList = JsonConvert.DeserializeObject<List<EmployeeModel>>(EmpResponse);
//var EmpObj = empobjList[0];
if (empobjList != null)
{
return empobjList;
}
}
}
}
catch(Exception ex)
{
//<Srcript> alert('WebService is not available' + ex.message)</>
}
return null;
}
If AJAX isn't an option, you can pass a flag to tell the client to create the window:
Controller:
return View("Index", (object)errorDetails);
View:
#model string
<!--Your HTML-->
#if (!string.IsNullOrEmpty(Model)
{
<script type="text/javascript">
alert(Model);
</script>
}

return array from c# function to js var

Hi I am trying to pass an array to js from c# but it keep telling me compilation error. Here is my code:
C#.net
public string calls()
{
string[] listing = new string[5];
listing[0] = "20-05-2015";
listing[1] = "22-05-2015";
listing[2] = "24-05-2015";
listing[3] = "26-05-2015";
listing[4] = "28-05-2015";
string jsonlisting = JsonConvert.SerializeObject(listing);
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('" + jsonlisting + "')", true);
return jsonlisting;
}
jquery/javascript
<script>
function pageLoad() {
var unavailableDates = <%=this.calls();%>
);
</script>
Remove the semi-colon directly after calls(). The following simplified version worked for me in an example I created:
<script type="text/javascript">
var unavailableDates = <%= this.calls() %>
</script>

Web server code not working properly

I'm trying to compile some code and get it to work properly in this web service index program that I have created, via a virtual machine.
package com.cs330;
import javax.ws.rs.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
#Path("ws2")
public class IngredientServices
{
#Path("/ingredients")
#GET
#Produces("text/plain")
public String getIngredients() throws SQLException, ClassNotFoundException {
String connectStr="jdbc:mysql://localhost:3306/fooddb";
//database username
String username="root";
//database password
String password="csci330pass";
/* The driver is the Java class used for accessing
* a particular database. You must download this from
* the database vendor.
*/
String driver="com.mysql.jdbc.Driver";
Class.forName(driver);
//Creates a connection object for your database
Connection con = DriverManager.getConnection(connectStr, username, password);
/* Creates a statement object to be executed on
* the attached database.
*/
Statement stmt = con.createStatement();
/* Executes a database query and returns the results
* as a ResultSet object.
*/
ResultSet rs = stmt.executeQuery("SELECT id, name, category FROM ingredient");
/* This snippet shows how to parse a ResultSet object.
* Basically, you loop through the object sort of like
* a linkedlist, and use the getX methods to get data
* from the current row. Each time you call rs.next()
* it advances to the next row returned.
* The result variable is just used to compile all the
* data into one string.
*/
String result = "";
while (rs.next())
{
int theId = rs.getInt("id");
String theName = rs.getString("name");
String theCategory = rs.getString("category");
result += "id: "+theId+ " , name: "+theName + "("+theCategory+")" + "\n" + "\n";
}
return result;
}//END METHOD
#Path("/ingredients/{id}")
#GET
#Produces("text/plain")
public String getIngredientById(#PathParam("id") String theId)
throws SQLException, ClassNotFoundException {
int intId = 0;
try
{
intId = Integer.parseInt(theId);
}
catch (NumberFormatException FAIL)
{
intId = 1;
}//Obtaining an ingredient from the database
String connectStr="jdbc:mysql://localhost:3306/fooddb";
String username="root";
String password="csci330pass";
String driver="com.mysql.jdbc.Driver";
Class.forName(driver);
Connection con = DriverManager.getConnection(connectStr, username, password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT id, name, category FROM ingredient
WHERE id=" +intId);
String result = "";
while (rs.next())
{
int theId2 = rs.getInt("id");
String theName2 = rs.getString("name");
String theCategory = rs.getString("category");
result += "id: "+theId2+ " , name: "+theName2 + "("+theCategory+")" + "\n" + "\n";
}
return result;
}//END METHOD
#Path("/ingredients/name")
#GET
#Produces("text/plain")
public String getIngredientByName(#QueryParam("name") String theName)
throws SQLException, ClassNotFoundException
{
//Obtaining an ingredient from the database
String connectStr="jdbc:mysql://localhost:3306/fooddb";
String username="root";
String password="csci330pass";
String driver="com.mysql.jdbc.Driver";
Class.forName(driver);
Connection con = DriverManager.getConnection(connectStr, username, password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT id, name, category FROM ingredient WHERE
name='" + theName + "'");
String result = "";
while (rs.next())
{
int theId3 = rs.getInt("id");
String theName3 = rs.getString("name");
String theCategory = rs.getString("category");
result += "id: "+theId3+ " , name: "+theName3 + "("+theCategory+")" + "\n" + "\n";
}
return result;
}//END METHOD
}//END CODE
Now, the first two methods, which are to retrieve everything and to retrieve items by ID are working properly, it's by retrieve by NAME code that isn't. While it is compiling correctly when I run it on cmd on my virtual machine and not showing any errors on Tomcat 8, The only code that is properly giving me results are the first two methods. For some reason, the third method keeps spitting out the first result and only the first result.
I have also attached the index.html file code to show you what the code above works with...
<html>
<head>
<title>Shakur (S-3) Burton's Web Services</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready( function() {
alert("running script");
$("#btnAll").click(function() {
alert("clicked");
$.ajax( {
url:"http://localhost:8080/webserv1/resources/ws2/ingredients/",
type: "GET",
dataType: "text",
success: function(result) {
alert("success");
$("#p_retrieveAll").html(result); },
error:function(xhr) {
alert("error");
$("#p_retrieveAll").html("Error:"+xhr.status + " " + xhr.statusText);}
} );
});
$("#btnOneId").click(function() {
alert("clicked");
var inputId=document.getElementById("t_ingredId").value;
var theUrl = "http://localhost:8080/webserv1/resources/ws2/ingredients/"+inputId;
$.ajax( {
url: theUrl,
type: "GET",
dataType: "text",
success: function(result) {
alert("success");
$("#p_retrieveOneId").html(result); },
error:function(xhr) {
alert("error");
$("#p_retrieveOneId").html("Error:"+xhr.status+" "+xhr.statusText);}
} );
});
$("#btnOneName").click(function() {
alert("clicked");
var inputName=document.getElementByName("t_ingredName").value;
var theUrl: "http://localhost:8080/webserv1/resources/ws2/ingredients/ingredient?name="+inputName;
$.ajax( {
url: theUrl,
type: "GET",
dataType: "text",
success: function(result) {
alert("success");
$("#p_retrieveOneName").html(result); },
error:function(xhr) {
alert("error");
$("#p_retrieveOneName").html("Error:"+xhr.status+" "+xhr.statusText);}
} );
});
});
</script>
</head>
<body>
<h3>Testing Web Services</h3>
<div id="retrieveAll">
<button id="btnAll">Click to Retrieve All</button>
<p id="p_retrieveAll">Ingredients List Goes here</p>
</div>
<div id="retrieveOneId">
<input type="text" id="t_ingredId" value="type id here" />
<button id="btnOneId">Click to Retrieve by Id</button>
<p id="p_retrieveOneId">Ingredient By Id Goes here</p>
</div>
<div id="retrieveOneName">
<input type="text" id="t_ingredName" value="type name here"/>
<button id="btnOneName">Click to Retrieve by Name</button>
<p id="p_retrieveOneName">Ingredient By Name Goes here</p>
</div>
</body>
</html>
Are there any suggestions that can be offered here as to why the GET by NAME method in my IngredientServices javascript isn't working properly? Am I missing something?
EDIT - 11/4/2014 - 16:05...
I figured that this problem might be in this part of the database program... Instead of searching for an ingredient by name by finding said element by ID, I should search within given parameters for it by NAME. Hopefully, this fixes the problem I was having...
BTW, this is the previous code I have modified: var inputName=document.getElementByName("t_ingredName").value;
When I added your code to the Firefox and Clicked on the Add-in called Firebug, it showed me the following error:
SyntaxError: missing ; before statement
var theUrl: "http://localhost:8080/webserv1/resources/ws2/ingredients/
Therefore it should be var theUrl= "http://localhost:8080/webserv1/resources/ws2/ingredients/ingredient?name="+inputName;
Have you tried debugging?
Also, instead of using alerts, use console.log("your message here"); - it will show up in the console in Firebug.
It turns out that that code I've created in the above question is thankfully working properly, despite some unfortunate bugs in the Retrieve Ingredient By Name method of my Java code... That was ultimately what needed some fixing.

How to update data using real-time (SignalR)

I am writing to seek help, in regards creating a real-time data update using SignalR. I am currently having issue on the client-side, where I am unable to render the data content.
I have a tested the query command and it seems to be returning data. This leads me to believe, that my client-side code, maybe incorrect.
<script src="~/Scripts/jquery-1.8.2.min.js" type="text/javascript" ></script>
<script src="~/Scripts/jquery.signalR-2.0.1.min.js" type="text/javascript" ></script>
<script src="~/signalr/hubs" type="text/javascript" ></script>
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var notifications = $.connection.NotificationHub;
// Create a function that the hub can call to broadcast messages.
notifications.client.recieveNotification = function (role, descrip) {
// Add the message to the page.
$('#spanNewMessages').text(role);
$('#spanNewCircles').text(descrip);
};
// Start the connection.
$.connection.hub.start().done(function () {
notifications.server.sendNotifications(function () {
alert("does it work");
});
}).fail(function (e) {
alert(e);
});
</script>
<h1>New Notifications</h1>
<div>
<b>New <span id="spanNewMessages"></span> role.</b><br />
<b>New<span id="spanNewCircles"></span> descrip.</b><br />
</div>
Hub Class:
[HubName("NotificationHub")]
public class notificationHub : Hub
{
string role = "";
string descrip = "";
[HubMethodName("sendNotifications")]
public void SendNotifications()
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["dummyConnectionString"].ConnectionString))
{
string query = "SELECT [role],[description] FROM [dbo].[User]";
connection.Open();
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Notification = null;
DataTable dt = new DataTable();
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
var reader = command.ExecuteReader();
dt.Load(reader);
if (dt.Rows.Count > 0)
{
role = dt.Rows[0]["role"].ToString();
descrip = dt.Rows[0]["description"].ToString();
}
}
}
Clients.All.RecieveNotification(role, descrip);
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
notificationHub nHub = new notificationHub();
nHub.SendNotifications();
}
}
}
StartUp CLass:
using Microsoft.Owin;
using Owin;
using WebApplication2;
namespace WebApplication2
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}
Could anyone, please provide some assistant, to where I may be going wrong with this task. Thank you.
I mocked up your app. Your issue was you are returning a string from your hub action:
public string SendNotifications()
{
return context.Clients.All.RecieveNotification(role, descrip);
}
this should be void (you aren't returning anything, but actually calling the clients), and you also don't need to use GlobalHost to get the context here, only when the context isn't available (I.E. calling the hub from the server). Try making these changes:
[HubMethodName("sendNotifications")]
public void SendNotifications()
{
//using...
//IHubContext context = GlobalHost.ConnectionManager.GetHubContext<notificationHub>();
//return context.Clients.All.RecieveNotification(role, descrip);
Clients.All.RecieveNotification(role, descrip);
}
Put a breakpoint at Clients.All... and see if it is being triggered. Let me know if these updates fix your issue.

Categories