InvalidSelectorException - Xpath shielding - selenium-webdriver

The variable may come across characters that are used in Xpath, respectively, there is a syntax error, how can you win ?
Example variable (this is just an example, the characters in it can be different):
string textElementa = "it ' is"
Search element by Xpath:
IWebElement elem = diver.FindElement(By.XPath("//div[normalize-space()='" + textElementa + "']"));
The Html code to:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div>
<span>it</span> <span>'</span> <span>is</span>
</div>
</body>
</html>
I've tried all this, but it doesn't work for me.
https://stackoverflow.com/questions/35854525
I also tried this:
public static string ToXPath(string value)
{
return "'" + XmlEncode(value) + "'";
}
public static string XmlEncode(string value)
{
StringBuilder text = new StringBuilder(value);
text.Replace("&", "&");
text.Replace("'", "&apos;");
text.Replace(#"""", """);
text.Replace("<", "<");
text.Replace(">", ">");
return text.ToString();
}

Related

How to automatically update Google Gauge

I'm kinda rookie in this, but I need help with Google Gauge that should take latest entry in database and display it, while updating automatically without the need to reload the site. Right now I have code that displays it, but for it to update to new values I need to reload the page.
Here's what I have so far:
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['gauge']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
['ProductPurity', <?php
$servername = "localhost";
$username = "u644759843_miki";
$password = "plantaze2020!";
$dbname = "u644759843_plantazeDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT ProductPurity FROM `Precizno ProductPurity` ORDER BY TimesStamp DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo $row["ProductPurity"];
}
} else {
echo "0 results";
}
mysqli_close($conn);
?> ],
]);
var options = {
width: 400, height: 120,
redFrom: 90, redTo: 100,
yellowFrom:75, yellowTo: 90,
minorTicks: 5
};
var chart = new google.visualization.Gauge(document.getElementById('chart_div'));
chart.draw(data, options);
setInterval(function() {
data.setValue(0 ,1 , <?php
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT ProductPurity FROM `Precizno ProductPurity` ORDER BY TimesStamp DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo $row["ProductPurity"];
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
);
chart.draw(data, options);
}, 5000);
setInterval(function() {
data.setValue(1, 1, 40 + Math.round(60 * Math.random()));
chart.draw(data, options);
}, 5000);
setInterval(function() {
data.setValue(2, 1, 60 + Math.round(20 * Math.random()));
chart.draw(data, options);
}, 26000);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 400px; height: 120px;"></div>
</body>
</html>
php runs on the server, so it is only going to run once per page load.
to update the chart without reloading the page,
you will need to separate the php from the html / javascript.
save the php to a different file, all by itself.
you need to include the rest of the data in the php,
including the column headings.
see following snippet for the php.
for example purposes, we'll name the file --> getdata.php
<?php
$servername = "localhost";
$username = "u644759843_miki";
$password = "plantaze2020!";
$dbname = "u644759843_plantazeDB";
// Create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = mysqli_connect($servername, $username, $password, $dbname);
$conn->set_charset('utf8mb4');
$sql = "SELECT ProductPurity FROM `Precizno ProductPurity` ORDER BY TimesStamp DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
// create data array
$data = [];
$data[] = ["Label", "Value"];
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$data[] = ["ProductPurity", $row["ProductPurity"]];
}
mysqli_close($conn);
// write data array to page
echo json_encode($data);
?>
next, save the html / javascript to its own file.
for example purposes, we'll name the file --> chart.html
to get the data from php,
we'll use jquery ajax.
see following snippet...
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script>
google.charts.load('current', {
packages: ['gauge']
}).then(function () {
var options = {
width: 400, height: 120,
redFrom: 90, redTo: 100,
yellowFrom:75, yellowTo: 90,
minorTicks: 5
};
var chart = new google.visualization.Gauge(document.getElementById('chart_div'));
drawChart();
function drawChart() {
$.ajax({
url: 'getdata.php',
dataType: 'json'
}).done(function (jsonData) {
// use response from php for data table
var data = google.visualization.arrayToDataTable(jsonData);
chart.draw(data, options);
// draw again in 5 seconds
window.setTimeout(drawChart, 5000);
});
}
});
</script>
</head>
<body>
<div id="chart_div" style="width: 400px; height: 120px;"></div>
</body>
</html>
EDIT
need to make sure the Value column...
is a number --> 99.9594
not a string --> "99.9594"
you can convert using --> (float)
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$data[] = ["ProductPurity", (float) $row["ProductPurity"]];
}
and / or use the JSON_NUMERIC_CHECK constant on the encode statement...
echo json_encode($data, JSON_NUMERIC_CHECK);

How to print output on new line?

case Constants.QUEUEESCALATION:
{
var body = '';
angular.forEach(caseChangeRecord, function(change, key) {
body += change.fieldName + Constants.QUEUEESCALATION_MSG + checkIfDate(change.originalValue) + Constants.TO + checkIfDate(change.newValue) + Constants.FULLSTOP + '\n';
});
return {
objectType: Constants.TYPE_INFO,
objectIcon: 'fa-list-ul',
objectBody: body
};
}
After appending \n in last it will shown output on same line instated of new line.
ACTUAL OUTPUT:
assignedQueue has been changed from Q1 to Q48. assignedQueueDate has been changed from 06/27/2017 to 07/03/2017.
REQUIRE OUTPUT:
assignedQueue has been changed from Q1 to Q48.
assignedQueueDate has been changed from 06/27/2017 to 07/03/2017.
Add a space before \n. It's working from my side.
body += change.fieldName + Constants.QUEUEESCALATION_MSG + checkIfDate
(change.originalValue) + Constants.TO + checkIfDate(change.newValue) +
Constants.FULLSTOP + ' \n';
Update :
and your html should be like using innerHtml
<div class="timeline-body" [innerHTML]="item.body"></div>
Divide rows by '\n' token and wrap your item.body into <pre>:
<div class="timeline-body">
<pre>
{{item.body}}
</pre>
</div>

Copy a file's contents while ignoring characters between < and > in Java

I'm looking to write a program that reads from a html file and copies the contents but it ignores the html tags without using replaceAll. Also the stripping of html tags must be done in a different method. The file looks like this :
<html>
<head>
<title>My web page</title>
</head>
<body>
<p>There are many pictures of my cat here,
as well as my <b>very cool</b> blog page,
which contains <font color="red">awesome
stuff about my trip to Vegas.</p>
Here's my cat now:<img src="cat.jpg">
</body>
</html>
And I'd like my program to display the following:
My web page
There are many pictures of my cat here,
as well as my very cool blog page,
which contains awesome
stuff about my trip to Vegas.
Here's my cat now:
public static void main(String[] args) {
String html = " <html>\n"
+ " <head>\n"
+ " <title>My web page</title>\n"
+ " </head>\n"
+ " <body>\n"
+ " <p>There are many pictures of my cat here,\n"
+ " as well as my <b>very cool</b> blog page,\n"
+ " which contains <font color=\"red\">awesome\n"
+ " stuff about my trip to Vegas.</p>\n"
+ "\n"
+ "\n"
+ " Here's my cat now:<img src=\"cat.jpg\">\n"
+ " </body>\n"
+ " </html>";
boolean inTag = false;
StringBuilder finalString = new StringBuilder();
int length = html.length();
for (int i = 0; i < length; i++) {
char c = html.charAt(i);
if ('<' == c) {
inTag = true;
} else if ('>' == c) {
inTag = false;
} else if (!inTag) {
finalString.append(c);
}
}
System.out.print(finalString);
}

Rename a file (file upload in servlet)

I'm trying to rename a file after upload but the error I get is:
File Upload Failed due to java.io.FileNotFoundException: C:\Users\Akhil\Documents\CryptographicSteganography\Image\toshaMon Dec 29 22:21:41 IST 2014.jpg (The filename, directory name, or volume label syntax is incorrect).
I went through almost all the possible related topics in stackoverflow as well as other sites but couldn't resolve this error.
my servlet class:
package FileUploadHandler;
import com.pointerunits.web.*;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
/**
* Servlet implementation class FileUploadServlet
*/
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
Date date = new Date();
String name = null;
public String UPLOAD_DIRECTORY = "";
/**
* #see HttpServlet#HttpServlet()
*/
public FileUploadServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//process only if its multipart content
String FileType = (String)request.getSession().getAttribute("FileType");
//System.out.println(FileType);
String usrnam = (String) request.getSession().getAttribute("name");
//System.out.println(usrnam);
switch (FileType) {
case "image":
//UPLOAD_DIRECTORY = "C:/Users/Akhil/Downloads/SpringMain/SpringMain/WebContent/WEB-INF/Uploads/Image";
UPLOAD_DIRECTORY = "C:/Users/Akhil/Documents/CryptographicSteganography/Image";
break;
case "audio":
UPLOAD_DIRECTORY = "C:/Users/Akhil/Documents/CryptographicSteganography/Image";
break;
case "video":
UPLOAD_DIRECTORY = "C:/Users/Akhil/Documents/CryptographicSteganography/Image";
break;
default:
System.out.println("invalid path");
break;
}
//UPLOAD_DIRECTORY = getServletContext().getRealPath(UPLOAD_DIRECTORY);
//System.out.println(UPLOAD_DIRECTORY);
if(ServletFileUpload.isMultipartContent(request)){
try {
List<FileItem> multiparts = new ServletFileUpload(
new DiskFileItemFactory()).parseRequest(request);
// System.out.println(getName());
String nam = usrnam+date.toString();
for(FileItem item : multiparts){
if(!item.isFormField()){
String name = item.getName();
//System.out.println(name);
File uploadedFile = new File(UPLOAD_DIRECTORY+File.separator+nam+name.substring(name.indexOf('.')));
item.write(uploadedFile);
//File uploadedFile = new File(UPLOAD_DIRECTORY, name);
// item.write( new File(UPLOAD_DIRECTORY + File.separator + nam + name));
// System.out.println("uploaded file : "+uploadedFile.toString());
// System.out.println(nam);
// String f1 = uploadedFile.getAbsolutePath();
// System.out.println(f1);
//
// File oldName = new File(f1);
// //File newName = new File(UPLOAD_DIRECTORY+File.separator+nam+"."+FilenameUtils.getExtension(oldName.toString()));
// File newName = new File(UPLOAD_DIRECTORY,nam+name.substring(name.indexOf('.')));
// File uploadedFile = new File ("C:\\Users\\Akhil\\Documents\\CryptographicSteganography\\Image\\IMAG0187.jpg");
// File newName = new File("C:\\Users\\Akhil\\Documents\\CryptographicSteganography\\Image\\toshaMon Dec 29 22:01:40 IST 2014.jpg");
// boolean flag = uploadedFile.renameTo(newName);
//
// System.out.println(newName.toString());
//
//// File uploadedFile = new File(UPLOAD_DIRECTORY , nam);
//// item.write(uploadedFile);
//
}
}
System.out.println();
//File uploaded successfully
request.setAttribute("message", "File Uploaded Successfully");
} catch (Exception ex) {
request.setAttribute("message", "File Upload Failed due to " + ex);
}
}else{
request.setAttribute("message",
"Sorry this Servlet only handles file upload request");
}
request.getRequestDispatcher("/result.jsp").forward(request, response);
}
}
below is the .jsp webpage:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Upload File</title>
</head>
<h1><%
String FileType = request.getParameter("select");
out.println("File Type is: "+FileType);
session.setAttribute("FileType", FileType);
%>
</h1>
<body>
<body>
File:
<%if (FileType.equalsIgnoreCase("image")){%>
<form method="POST" action="FileUploadServlet" enctype="multipart/form-data" >
<input type="file" name="<%=session.getAttribute("FileType")%>" accept="image/*"> <br/>
<input type="submit" value="Upload" name="upload" >
</form>
<% }
else if (FileType.equalsIgnoreCase("audio")){%>
<form method="POST" action="FileUploadServlet" enctype="multipart/form-data" >
<input type="file" name="<%=session.getAttribute("FileType") %>" accept="audio/*" > <br/>
<input type="submit" value="Upload" name="upload" >
</form>
<% }
else if (FileType.equalsIgnoreCase("video")){%>
<form method="POST" action="FileUploadServlet" enctype="multipart/form-data" >
<input type="file" name="<%=session.getAttribute("FileType") %>" accept="video/*" > <br/>
<input type="submit" value="Upload" name="upload" >
</form>
<% }
%>
</body>
</body>
</html>
Sorry about that awful lot of comments:
my program was going through a testing phase
May be there is right issue, it cannot access the folder as it does not have right.
If this is not the case then.
You should try to remove space from the file name format data value to a format that does not contains any space Sample Format Date . Because space can create problems.
Before item.write(uploadedFile); check
if(!uploadedFile.exists()){
uploadedFile.createNewFile();
}

autocomplete extender not working

I tried to find my answer in many sites but I think every thing is correct in my code but still the Auto Complete Extender doesn't work.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods = "true">
</asp:ScriptManager>
<asp:TextBox ID="txtName" runat="server" Width="190px" CssClass="TextBox"></asp:TextBox>
<cc1:AutoCompleteExtender
ID="AutoCompleteExtender1" ServiceMethod="GetNamesList"
MinimumPrefixLength="1"
CompletionInterval="1000" EnableCaching="true" CompletionSetCount="10"
TargetControlID="txtName" UseContextKey="True"
runat="server">
</cc1:AutoCompleteExtender>
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public string[] GetNamesList(string prefixText, int count, string contextKey)
{
DataSet dtst = new DataSet();
SqlConnection sqlCon = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["ConStr"]);
string strSql = "SELECT FirstName FROM finex.tbl_SenderInfo WHERE FirstName LIKE '" + prefixText + "%' ";
SqlCommand sqlComd = new SqlCommand(strSql, sqlCon);
sqlCon.Open();
SqlDataAdapter sqlAdpt = new SqlDataAdapter();
sqlAdpt.SelectCommand = sqlComd;
sqlAdpt.Fill(dtst);
string[] cntName = new string[dtst.Tables[0].Rows.Count];
int i = 0;
try
{
foreach (DataRow rdr in dtst.Tables[0].Rows)
{
cntName.SetValue(rdr["FirstName"].ToString(), i);
i++;
}
}
catch { }
finally
{
sqlCon.Close();
}
return cntName;
}
You will probably need something like this within your <asp:AutoCompleteExtender> tag with the name of the page that contains your web method:
ServicePath="MyFile.aspx"
Also try the following at the top of your aspx file:
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
<%# Register TagPrefix="asp" Namespace="AjaxControlToolkit" Assembly="AjaxControlToolkit" %>
And this somewhere within the main contents of your page, say after the opening body tag:
<ajaxToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" EnablePageMethods="true"
runat="server">
</ajaxToolkit:ToolkitScriptManager>
I just cut those lines out of one of my projects that works, some may have already been included by the IDE depending on how you added things, so check if they're there already before adding.

Resources