I have a piechart from google that I am trying to populate with data from my database. I can get a result set with my desired results but I am unable to get this to work because I am not sure how to take my java variables and make them into javascript variables so that they work with the google code.
When I try the code below I get an error on this line
var zipie = <%= zip1 %>;
saying that zip1 cannot be resolved to a variable
Trying to call my java variable in the javascript directly doesn't work
<script type="text/javascript">
google.load('visualization', '1', {
'packages' : [ 'corechart' ]
});
<%
try {
PieChartDAO pDao = new PieChartDAO();
String sql = PieChartSQLCreation. getTopZipCode();
ResultSet zipr = pDao.getTopZip(sql);
int[] zip = new int[5];
String[] zips = new String[5];
for(int i = 0; i <5; i++) {
zip[i] = zipr.getInt("num");
zips[i] = zipr.getString("zip_code");
zipr.next();
}
int zip1 = zip[0];
}
catch (Exception e) {
e.printStackTrace();
}
%>
var zipie = <%= zip1 %> ;
google.setOnLoadCallback(drawVisualization);
function drawVisualization() {
visualization_data = new google.visualization.DataTable();
visualization_data.addColumn('string', 'Zip Code');
visualization_data.addColumn('number', 'Number of Students');
visualization_data.addRow([ 'Work', zipie ]);
visualization_data.addRow([ 'Eat', 2 ]);
visualization_data.addRow([ 'Commute', 2 ]);
visualization_data.addRow([ 'Watch TV', 2 ]);
visualization_data.addRow([ 'Sleep', 7 ]);
visualization = new google.visualization.PieChart(
document.getElementById('piechart'));
visualization.draw(visualization_data, {
title : 'Zip Codes',
height : 260
});
}
</script>
zip1 is local to the try block. Declare this beforehand for it to be in the correct scope.
int zip1 = -1; // some default value
try {
// [...]
}
Related
I have more than 6 environments against which i have to run the same set of rest api scripts. For that reason i have stored all that test data and the end points/resource paths in a json file. I then try to read this json file into my karate-config.js file, this is because i want to fetch the data corresponding to the environment that is being passed from the command line (karate.env), which am reading into my karate-config.js file
Below is my json file sample
[
{
"qa":{
"username_cm_on":"test_cm_on_qa",
"password_cm_on":"Test123$",
"nonadmin_username_cm_on":"test_non_admin_cm_on_qa",
"nonadmin_password_cm_on":"Test123$",
"username_cm_off":"test_cm_off_qa",
"password_cm_off":"Test123$",
"nonadmin_username_cm_off":"test_non_admin_cm_off_qa",
"nonadmin_password_cm_off":"Test123$",
"zuul_urls":{
"home-sec-uri":"https://qa.abc.com/qa/home-sec-uri",
"home-res-uri":"https://qa.abc.com/qa/home-res-uri"
}
}
},
{
"uat":{
"username_cm_on":"test_cm_on_uat",
"password_cm_on":"Test123$",
"nonadmin_username_cm_on":"test_non_admin_cm_on_uat",
"nonadmin_password_cm_on":"Test123$",
"username_cm_off":"test_cm_off_uat",
"password_cm_off":"Test123$",
"nonadmin_username_cm_off":"test_non_admin_cm_off_uat",
"nonadmin_password_cm_off":"Test123$",
"zuul_urls":{
"home-sec-uri":"https://uat.abc.com/qa/home-sec-uri",
"home-res-uri":"https://uat.abc.com/qa/home-res-uri"
}
}
}
]
and below is my karate-config.js file
function() {
// var env = karate.env; // get system property 'karate.env'
var env = 'qa';
var cm = 'ON';
var envData = call read('classpath:env_data.json'); //require("./env_data.json");
// write logic to read data from the json file _ Done, need testing
karate.log('karate.env system property was:', env);
switch(env) {
case "qa":
if(cm === 'ON'){
config.adminusername_cm_on = getData().username_cm_on;
config.adminpassword_cm_on = "";
config.nonadminusername_cm_on = getData().nonadmin_username_cm_on;
config.nonadminpassword_cm_on = "";
}else if(cm === "OFF") {
config.adminusername_cm_off = getData().username_cm_off;
config.adminpassword_cm_off = "";
config.nonadminusername_cm_off = getData().nonadmin_username_cm_off;
config.nonadminpassword_cm_off = "";
}
break;
case "uat":
break;
default:
break;
}
// This method will return the data from the env_data.json file
var getData = function() {
for(var i = 0; i < obj.length; i++) {
for(var e in obj[i]){
var username_cm_on = obj[i][e]['username_cm_on'];
var nonadmin_username_cm_on = obj[i][e]['nonadmin_username_cm_on'];
var username_cm_off = obj[i][e]['username_cm_off'];
var nonadmin_username_cm_off = obj[i][e]['nonadmin_username_cm_off'];
return {
username_cm_on: username_cm_on,
nonadmin_username_cm_on: nonadmin_username_cm_on,
username_cm_off: username_cm_off,
nonadmin_username_cm_off: nonadmin_username_cm_off
}
}
}
}
var config = {
env: env,
data: getData(),
}
return config;
}
I tried several ways to load the env-data.json file into karate-config.js as below
var envData = call read('classpath:env_data.json');
I know the above is not valid from this stackover flow answer Karate - How to import json data by Peter Thomas
So,tried with the below ones
var envData = read('classpath:env_data.json');
var envData = require("./env_data.json");
var envData = require('./env_data.json');
But, still facing issues with reading the json file. Appreciate help on this.
I think you over-complicated your JSON. You just need one object and no top-level array. Just use this as env_data.json:
{
"qa":{
"username_cm_on":"test_cm_on_qa",
"password_cm_on":"Test123$",
"nonadmin_username_cm_on":"test_non_admin_cm_on_qa",
"nonadmin_password_cm_on":"Test123$",
"username_cm_off":"test_cm_off_qa",
"password_cm_off":"Test123$",
"nonadmin_username_cm_off":"test_non_admin_cm_off_qa",
"nonadmin_password_cm_off":"Test123$",
"zuul_urls":{
"home-sec-uri":"https://qa.abc.com/qa/home-sec-uri",
"home-res-uri":"https://qa.abc.com/qa/home-res-uri"
}
},
"uat":{
"username_cm_on":"test_cm_on_uat",
"password_cm_on":"Test123$",
"nonadmin_username_cm_on":"test_non_admin_cm_on_uat",
"nonadmin_password_cm_on":"Test123$",
"username_cm_off":"test_cm_off_uat",
"password_cm_off":"Test123$",
"nonadmin_username_cm_off":"test_non_admin_cm_off_uat",
"nonadmin_password_cm_off":"Test123$",
"zuul_urls":{
"home-sec-uri":"https://uat.abc.com/qa/home-sec-uri",
"home-res-uri":"https://uat.abc.com/qa/home-res-uri"
}
}
}
And then this karate-config.js will work:
function() {
var env = 'qa'; // karate.env
var temp = read('classpath:env_data.json');
return temp[env];
}
And your tests can be more readable:
Given url zuul_urls['home-sec-uri']
If you have trouble understanding how this works, refer to this answer: https://stackoverflow.com/a/59162760/143475
How can i show the special characters(~!##...etc) and numeric number(0-9) not in tag when user key in the value from the input tag? Is it possible to restrict special characters and numeric display in normal text? Any help would be appreciated.
Current output :
<%
ArrayList alTag = new ArrayList();
Vector vTag = new Vector();
String SQL = "SELECT CODE, DESCP FROM TB_FRUIT WITH UR";
TEST.makeConnection();
TEST.executeQuery(SQL);
while(TEST.getNextQuery())
{
Vector vRow = new Vector();
ArrayList alInner = new ArrayList();
String field =TEST.getColumnString("CODE");
String descp =TEST.getColumnString("DESCP");
alInner.add(field);
alInner.add(descp);
alTag.add(alInner);
vTag.addElement(field);
}
TEST.takeDown();
%>
<script>
var dbArray = [<%
String dbCode = "";
String dbList = "";
for(int i=0;i<vTag.size();i++)
{
dbCode = (String) vTag.elementAt(i);
dbList += "\"" + dbCode + "\",";
}
out.print(dbList); %>
];
$(document).ready(function() {
$("#myTags").tagit({
availableTags: dbArray
});
});
</script>
<html>
<body>
<input type="text" id="myTags" name="TYPE">
</body>
</html>
This restricts the input only to alphabets
$('#myTags').keypress(function (event) {
var regex = new RegExp("^[a-zA-Z]+$");
var str = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(str)) {
e.preventDefault();
return false;
}
});
If you are open to introducing a jquery plugin, the easiset way is to include the [alphanum jquery plugin] and then do
$('#myTags').alpha();
[alphanum jquery plugin] : https://github.com/KevinSheedy/jquery.alphanum
UPDATED :
You could extent the jquery tagit plugin and override the cleaned input method as shown below so as to replace non alphabets .
$.widget( "ui.tagit", $.ui.tagit, {
_cleanedInput: function() {
var cleanedInput = this.tagInput.val().replace(/[^a-zA-Z0-9\s]+/,"");
return $.trim(cleanedInput.replace(/^"(.*)"$/, '$1'));
}
});
I am trying to use jsoup so as to have access to a table embedded inside multiple div's of an html page.The table is under the outer division with id "content-top". I will give the inner divs leading to the table: content-top -> center -> middle-right-col -> result .
Under the div result; is table round. This is the table that i want to access and whose rows I need to traverse and print out the data contained in them. Below is the java code I have been trying to use but yielding no results :
Document doc = Jsoup.connect("http://www.calculator.com/#").data("express", "sin(x)").data("calculate","submit").post();
// give the application time to calculate result before retrieving result from results table
try {
Thread.sleep(10000);
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
Elements content = doc.select("div#result") ;
Element tables = content.get(0) ;
Elements table_rows = tables.select("tr") ;
Iterator iterRows = table_rows.iterator();
while (iterRows.hasNext()) {
Element tr = (Element)iterRows.next();
Elements table_data = tr.select("td");
Iterator iterData = table_data.iterator();
int tdCount = 0;
String f_x_value = null;
String result = null;
// process new line
while (iterData.hasNext()) {
Element td = (Element)iterData.next();
switch (tdCount++) {
case 1:
f_x_value = td.text();
f_x_value = td.select("a").text();
break;
case 2:
result = td.text();
result = td.select("a").text();
break;
}
}
System.out.println(f_x_value + " " + result ) ;
}
The above code crashes and hardly does what I want it to do. PLEASE CAN ANYONE PLEASE HELP ME !!!
public static String do_conversion (String str)
{
char c;
String output = "{";
for(int i = 0; i < str.length(); i++)
{
c = str.charAt(i);
if(c=='e')
output += "{mathrm{e}}";
else if(c=='(')
output += '{';
else if(c==')')
output += '}';
else if(c=='+')
output += "{cplus}";
else if(c=='-')
output += "{cminus}";
else if(c=='*')
output += "{cdot}";
else if(c=='/')
output += "{cdivide}";
else output += c; // else copy the character normally
}
output += ", mathrm{d}x}";
return output;
}
#Syam S
The page doesnt directly give you a table in a div with id as "result". It uses an ajax class to a php file and get the process done. So what you need to do here is to first build a json like
{"expression":"sin(x)","intVar":"x","upperBound":"","lowerBound":"","simplifyExpressions":false,"latex":"\\displaystyle\\int\\limits^{}_{}{\\sin\\left(x\\right)\\, \\mathrm{d}x}"}
The expression key hold the expression that you want to evaluate, the latex is a mathjax expression and then post it to int.php. This expects two arguments namely q which is the above json and v which seems to a constant value 1380119311. I didnt understand what this is.
Now this will return a response like
<html>
<head></head>
<body>
<table class="round">
<tbody>
<tr class="">
<th>$f(x) =$</th>
<td>$\sin\left(x\right)$</td>
</tr>
<tr class="sep odd">
<th>$\displaystyle\int{f(x)}\, \mathrm{d}x =$</th>
<td>$-\cos\left(x\right)$</td>
</tr>
</tbody>
</table>
<!-- Finished in 155 ms -->
<p id="share"> <img src="layout/32x32xshare.png.pagespeed.ic.i3iroHP5fI.png" width="32" height="32" /> <a id="share-link" href="http://www.integral-calculator.com/#expr=sin%28x%29" onclick="window.prompt("To copy this link to the clipboard, press Ctrl+C, Enter.", $("share-link").href); return false;">Direct link to this calculation (for sharing)</a> </p>
</body>
</html>
The table in this expression gives you the result and the site uses mathjax to display it like
A sample program would be
import java.io.IOException;
import org.apache.commons.lang3.StringEscapeUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
public class JsoupParser6 {
public static void main(String[] args) {
try {
// Integral
String url = "http://www.integral-calculator.com/int.php";
String q = "{\"expression\":\"sin(4x) * e^(-x)\",\"intVar\":\"x\",\"upperBound\":\"\",\"lowerBound\":\"\",\"simplifyExpressions\":false,\"latex\":\"\\\\displaystyle\\\\int\\\\limits^{}_{}{\\\\sin\\\\left(4x\\\\right){\\\\cdot}{\\\\mathrm{e}}^{-x}\\\\, \\\\mathrm{d}x}\"}";
Document integralDoc = Jsoup.connect(url).data("q", q).data("v", "1380119311").post();
System.out.println(integralDoc);
System.out.println("\n*******************************\n");
//Differential
url = "http://www.derivative-calculator.net/diff.php";
q = "{\"expression\":\"sin(x)\",\"diffVar\":\"x\",\"diffOrder\":1,\"simplifyExpressions\":false,\"showSteps\":false,\"latex\":\"\\\\dfrac{\\\\mathrm{d}}{\\\\mathrm{d}x}\\\\left(\\\\sin\\\\left(x\\\\right)\\\\right)\"}";
Document differentialDoc = Jsoup.connect(url).data("q", q).data("v", "1380119305").post();
System.out.println(differentialDoc);
System.out.println("\n*******************************\n");
//Calculus
url = "http://calculus-calculator.com/calculation/integrate.php";
Document calculusDoc = Jsoup.connect(url).data("expression", "sin(x)").data("intvar", "x").post();
String outStr = StringEscapeUtils.unescapeJava(calculusDoc.toString());
Document formattedOutPut = Jsoup.parse(outStr);
formattedOutPut.body().html(formattedOutPut.select("div.isteps").toString());
System.out.println(formattedOutPut);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Update based on comment.
The unescape works perfectly well. In MathJax you could right click and view the command. So if you go to your site http://calculus-calculator.com/ and try the sin(x) equation there and right click the result and view TexCommand like
The you could see the commands are exactly the ones which we get after unsescape. The demo site is not rendering it. May be a limitation of the demo site, thats all.
Hi I want to scrape some text from a website using the JSoup library. I have tried the following code, and that gives me the whole webpage, I want to just extract a specific line. Here is the code I am using:
Document doc = null;
try {
doc = Jsoup.connect("http://www.example.com").get();
} catch (IOException e) {
e.printStackTrace();
}
String text = doc.html();
System.out.println(text);
That prints out the following
<html>
<head></head>
<body>
Martin,James,28,London,20k
<br /> Sarah,Jackson,43,Glasgow,32k
<br /> Alex,Cook,22,Liverpool,18k
<br /> Jessica,Adams,34,London,27k
<br />
</body>
</html>
How can I extract just the 6th line that reads Alex,Cook,22,Liverpool,18k and put it into an array where each element is a word before a comma (eg: [0] = Alex, [1] = Cook, etc)
Maybe you have to format (?) the Result a bit:
Document doc = Jsoup.connect("http://www.example.com").get();
int count = 0; // Count Nodes
for( Node n : doc.body().childNodes() )
{
if( n instanceof TextNode )
{
if( count == 2 ) // Node 'Alex'
{
String t[] = n.toString().split(","); // you have an array with each word as string now
System.out.println(Arrays.toString(t)); // eg. output
}
count++;
}
}
Output:
[ Alex, Cook, 22, Liverpool, 18k ]
Edit:
Since you cant select TextNode's by its ccntent (only possible with Elements) you need a small workaround:
for( Node n : doc.body().childNodes() )
{
if( n instanceof TextNode )
{
str = n.toString().trim();
if( str.toLowerCase().startsWith("alex") ) // Node 'Alex'
{
String t[] = n.toString().split(","); // you have an array with each word as string now
System.out.println(Arrays.toString(t)); // eg. output
}
}
}
I have two dropdown fields in a JSP page and I have type4 connection with oracle 10g. I want that based on one dropdown selection I want that second dropdown should get filled by fetching data from database based on data in first dropdown automatically just like refreshing that JSP page or showing an alert something like "please wait". How can I do it in JSP-Servlet?
<select name="dropdown1">
<option value="<%out.println(name);%>"><%out.println(name);%></option>
</select>
My objective is: This below dropdown should get filled base don above selection:
<select name="dropdown2">
<option value="<%out.println(rollno);%>"><%out.println(rollno);%></option>
</select>
I have found one solution :
<body onload="setModels()">
<% // You would get your map some other way.
Map<String,List<String>> map = new TreeMap<String,List<String>>();
Connection con=null;
String vehtypeout="";
String vehtypeout1="";
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("");
PreparedStatement ps=null;
ResultSet rs=null;
ps=con.prepareStatement("select c1.name, c2.roll from combo1 c1 left join combo2 c2 on c1.name=c2.name order by name");
rs=ps.executeQuery();
while(rs.next()){
vehtypeout=rs.getString(1);
vehtypeout1=rs.getString(2);
map.put(vehtypeout, Arrays.asList((vehtypeout1)));// here i want to show multiple value of vehtypeout1 from database but only one value is coming from databse, how can i fetch multiple value?
map.put("mercedes", Arrays.asList(new String[]{"foo", "bar"}));
}
rs.close();
ps.close();
con.close();
}
catch(Exception e){
out.println(e);
}
%>
<%! // You may wish to put this in a class
public String modelsToJavascriptList(Collection<String> items) {
StringBuilder builder = new StringBuilder();
builder.append('[');
boolean first = true;
for (String item : items) {
if (!first) {
builder.append(',');
} else {
first = false;
}
builder.append('\'').append(item).append('\'');
}
builder.append(']');
return builder.toString();
}
public String mfMapToString(Map<String,List<String>> mfmap) {
StringBuilder builder = new StringBuilder();
builder.append('{');
boolean first = true;
for (String mf : mfmap.keySet()) {
if (!first) {
builder.append(',');
} else {
first = false;
}
builder.append('\'').append(mf).append('\'');
builder.append(" : ");
builder.append( modelsToJavascriptList(mfmap.get(mf)) );
}
builder.append("};");
return builder.toString();
}
%>
<script>
var modelsPerManufacturer =<%= mfMapToString(map) %>
function setSelectOptionsForModels(modelArray) {
var selectBox = document.myForm.models;
for (i = selectBox.length - 1; i>= 0; i--) {
// Bottom-up for less flicker
selectBox.remove(i);
}
for (i = 0; i< modelArray.length; i++) {
var text = modelArray[i];
var opt = new Option(text,text, false, false);
selectBox.add(opt);
}
}
function setModels() {
var index = document.myForm.manufacturer.selectedIndex;
if (index == -1) {
return;
}
var manufacturerOption = document.myForm.manufacturer.options[index];
if (!manufacturerOption) {
// Strange, the form does not have an option with given index.
return;
}
manufacturer = manufacturerOption.value;
var modelsForManufacturer = modelsPerManufacturer[manufacturer];
if (!modelsForManufacturer) {
// This modelsForManufacturer is not in the modelsPerManufacturer map
return; // or alert
}
setSelectOptionsForModels(modelsForManufacturer);
}
function modelSelected() {
var index = document.myForm.models.selectedIndex;
if (index == -1) {
return;
}
// alert("You selected " + document.myForm.models.options[index].value);
}
</script>
<form name="myForm">
<select onchange="setModels()" id="manufacturer">
<% boolean first = true;
for (String mf : map.keySet()) { %>
<option value="<%= mf %>" <%= first ? "SELECTED" : "" %>><%= mf %></option>
<% first = false;
} %>
</select>
<select onChange="modelSelected()" id="models">
<!-- Filled dynamically by setModels -->
</select>
But i am getting only one value in vehtypeout1 where databse contains multiple values. How can i do it?
Using jquery, bind a function to the onchange event of "combobox1" select box.
In that function, send an ajax request (you can use jquery get function) to a jsp page in your server.
In that jsp page, retrieve the relevant data from database and send the response back to the client with those data (may be you need to use JSON format).
In the jquery get function, you can add a callback function to execute after server send you back the response.
Inside that call back function, write the code to fill "combobox2" using response data sent by the server.
You'll want an ajax call like below. Have your function that is called return a html-string of
"<option value='myVal'>myText</option>".
The jQuery/Ajax would be:
$("#ddl1").change(function() {
$.ajax({
url: "URLyouwanttoaddress",
data: "myselection=" + $("#ddl1").val();
type:"get",
success: function(data) {
$("#ddl2").html(data);
}
});
});