Getting PhantomJS to work with a java application - java

I am testing around with PhantomJS a bit.
But I am not sure how to make it work with a java application, th examples I have found are mostly just against files or sites.
So this is what I have now.
var page = require('webpage').create();
address = "http://localhost:8080/logon.do";
page.open(address, function(status) {
wait(5000);
if (status !== 'success') {
console.log('Unable to access network');
} else {
var ua = page.evaluate(function () {
return document.getElementsByTagName('html')[0].outerHTML;
});
console.log(ua);
}
phantom.exit();
});
function wait(ms){
var start = new Date().getTime();
var end = start;
while(end < start + ms) {
end = new Date().getTime();
}
}
Now I know this wait is ugly but it is not important right now.
The server is running and if I go to the url I get a log in page.
I was expecting this log in page to be the output of console.log(ua);
Instead I get the output:
<-html><-head><-/head><-body><-/body><-/html>
What am I missing?

OK this turned out to be very secific for our application so lets close this.
Sascha, yes it is the script called by phantomjs which in turn

Related

How to fix [WARNING]: Timed out connecting to Chrome, retrying

I access Websites in a loop via selenium Java based. Some of the sites crash imediately so that i get the error
[1618982990.911][WARNING]: Timed out connecting to Chrome, retrying...
after a short time.
So this is not a selenium issue i assume, since even chrome crashes if i visit the site manually because of js errors, saying unresonsive Website
My problem is, that every time a site crashes, chromedriver and a chrome instance will stay alive so that i have high CPU usage after a short time.
Can i tell selenium to quit the instance if it is frozen? But i dont know how this should be possible if it does not get answer from chrome anymore?
Thankful for any solution or idea
Sometimes with some Windows version driver.quit() will not kill the chrome process which I have come across.
So at the end of the script you can kill the chrome processes if exists using java code, if the driver.quit doesn't work.
Please refer stackoverflow link which has the code to kill the process if exists in Java and pass the chrome process to it.
i found a workaround for anyone who would be interested. First setting up a pageLoadTimeout, after that force any chrome instance to be killed if an Exception is being thrown.
try{
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
//some excecution code....
}
catch (Exception e) {
System.out.println("Error. Closing");
driver.quit();
Runtime.getRuntime().exec("taskkill /F /IM chrome.exe");}
timerChromeKillListener = new Timer();
timerChromeKillListener.schedule(new TimerTask()
{
#Override
public void run()
{
if (driver != null)
{
try
{
final Logs logs = driver.manage().logs();
final LogEntries driverLog = logs.get("driver");
if (driverLog != null)
{
final List<LogEntry> logEntries = driverLog.getAll();
for (final LogEntry logEntry : logEntries)
{
final String message = logEntry.getMessage();
if (message.contains("Unable to evaluate script: disconnected: not connected to DevTools") || message.contains("Timed out connecting to Chrome, retrying..."))
{
disconnect();
}
}
}
}
catch (Exception ignored)
{
}
}
}
} , 1 , 100);

Identify downloaded file in windows selenium node from unix machine

My selenium code is deployed in jenkinns which is in unix machine. When my schedulers trigger a job suite, job will run on selenium nodes which are in windows. Gere, i have a test case where file is downloaded in one of the node and i need to verify that downloaded file.
How can i identify a downloaded file in windows from unix machine
(Both are different environments).
If you are wish to verify this on chrome, following code is a solution.
Note: its written on typescript so you have to adapt it.
function checkChromeForDownloadedFile(fileName: string, state: string = 'COMPLETE') {
// open new tab
await browser.executeScript('return window.open()');
// switch to downloads tab window
let tabs: string[] = await browser.getAllWindowHandles();
await browser.switchTo().window(tabs[1]);
// open downloads page
await browser.get('chrome://downloads');
// 1 sec delay.
await browser.sleep(1000);
let downloadedItems;
try {
await browser.wait(() => {
// fetch downloaded items
return browser.executeScript('return downloads.Manager.get().items_').then((result) => {
downloadedItems = result;
if (!downloadedItems) {
return false;
}
// search for downloaded file with state complete and filename
return downloadedItems.some(i => i.file_name === fileName && i.state === state.toUpperCase());
}).catch( () => {
return false;
});
}, 10000, `File ${fileName} with download sate ${state} was not found within 10 seconds`);
} catch (error) {
console.log('there was an error while trying to fetch downloaded files');
throw error;
}
// close the tab
await browser.close();
// switch back to original window
await browser.switchTo().window(tabs[0]);
}

HTML5 Server Side Events (SSE)

I am working on implementing SSE in a Web Application on Java Stack using Servlets. I have facing 2 key issues currently. Let me first place my code both for the Web page and the Servlet followed by the issue I am facing.
Web Page Code:
<script type="text/javascript">
function registerSSE() {
var source = new EventSource("http://www.sample.com/BootStrap/NotificationServlet");
source.addEventListener('StartProductionRun', function(e) {
// Get the data and identify the instrument Name/Id
var dataReceived = e.data;
document.getElementById(dataReceived + "_button").disabled = true;
}, false);
}
function StartProduction(instrument) {
var dataString = 'instrumentName='+ instrument;
// call ajax to submit the form and start the production run
$.ajax({
type: 'POST',
url: 'http://localhost:8080/BootStrap/ProductionRunServlet',
data: dataString,
success: function() {
$('#Status').html("<div id='message'></div>");
$('#message').html("<h4 aling=\"centre\">Prudction Run for Instrument " + instrument + " initiated.</h4>")
.hide()
.fadeIn(5000);
}
});
}
</script>
Servlet Code :
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/event-stream;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
PrintWriter out = response.getWriter();
NotificationService notificationService = null;
while (true) {
notificationService = NotificationService.getInstance();
if (notificationService.getNotificationCount() > 0 ) {
String notificationValue = notificationService.getNotification(0);
String[] keyValue = notificationValue.split(":");
out.print("event:" + keyValue[0] + "\n");
out.print("data: " + keyValue[1] + "\n");
out.print("retry:" + 1000 + "\n\n");
out.flush();
}
else {
out.print(": time stream \n");
out.print("retry:" + 1000 + "\n\n");
out.flush();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Now the issues:
The Web Page will be viewed by multiple users at the same time. And I want that the data to be pushed to all the users who viewing that page. Currently when I am running locally in my machine, even if I open Chrome and Firefox, I don't get the notification in both the Browsers. It comes only in one.
Also, If I leave the browser running for some time, I find that even if the servlet is pushing out data based on certain events. I don't get the notification on the Browser.
I need to make sure that:
The notification gets pushed to all the clients who are viewing that particular page irrespective of what they are doing on the page or the page is just used for viewing the information.
Looking forward to all the help I can get to make this working. Also, would be interested to know if there are other alternative which I can use.
Your servlet code is working perfectly, although i haven't worked so much on it(once did a jsp project). What i think is, you have missed something in javascript?
I think there should be a timer/thread/loop in javascript too, to get all pushed data continuously. i.e,
setInterval(
function(){
// code which needs to run every 5sec
},5000);
I hope this will help out a bit.
You should check if EventSource is available in that browser before using it. Maybe one of the browsers has not support for it.

Applet java throws exception with chrome

I'm developing a Django site with an applet Java.
Some days ago the applet start to fail loading in my chrome browser. I was still in developing and I tought that was a cache problem, so to test I started to use firefox.
At today the applet is developed at 90%, and on firefox works smoothy. No problems at all.
So I was working on some JS and I opened chrome (like its debugger), so I cleaned the chrome's cache folder and the java plugin cache, and I open the site.
The applet failed to load. Here is the error:
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at sun.applet.PluginAppletSecurityContext$5.run(PluginAppletSecurityContext.java:943)
at java.security.AccessController.doPrivileged(Native Method)
at sun.applet.PluginAppletSecurityContext.handleMessage(PluginAppletSecurityContext.java:940)
at sun.applet.AppletSecurityContextManager.handleMessage(AppletSecurityContextManager.java:70)
at sun.applet.PluginStreamHandler.handleMessage(PluginStreamHandler.java:235)
at sun.applet.PluginMessageHandlerWorker.run(PluginMessageHandlerWorker.java:78)
Caused by: java.lang.NumberFormatException: For input string: "0,000000"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1241)
at java.lang.Double.valueOf(Double.java:504)
at java.lang.Double.<init>(Double.java:597)
... 10 more
java.lang.NullPointerException
at sun.applet.PluginAppletViewer.getMember(PluginAppletViewer.java:1020)
at netscape.javascript.JSObject.getMember(JSObject.java:155)
at objects.CommunicationWithJS.parseFloors(CommunicationWithJS.java:75)
at main.MapGenerator.start(MapGenerator.java:27)
at sun.applet.AppletPanel.run(AppletPanel.java:476)
at java.lang.Thread.run(Thread.java:722)
The strange thing is that on Firefox works with no problems...
On loading, the applet calls some JS on the page to load a Json from the site.
This Json is than passed to the applet.
The communication between the applet and the page is managed by the netscape library.
The JS that loads the JSON:
function getFloors() {
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", GET_FLOORS, false );
xmlHttp.send(null);
var json = JSON.parse(xmlHttp.responseText);
return json;
}
And the code on the applet:
public Floor[] parseFloors(URL codebase) {
JSObject jsonFloors = (JSObject) window.eval(GET_FLOORS);
// counter of the number of objects
int i=0;
for (; i < 50; i++)
try {
if (jsonFloors.getSlot(i) == null)
break;
} catch (JSException jse) {
break;
}
Floor[] floors = new Floor[i];
for (int t=0; t < i; t++) {
JSObject jsonFloor = (JSObject) jsonFloors.getSlot(t);
try {
int numero_di_piano = Integer.parseInt(jsonFloor.getMember(NUMERO_DI_PIANO)+"");
URL link = new URL(codebase, jsonFloor.getMember(LINK).toString());
float bearing = Float.parseFloat(jsonFloor.getMember(BEARING).toString());
int id = Integer.parseInt(jsonFloor.getMember(ID).toString());
Floor floor = new Floor(numero_di_piano, link, bearing, id);
floors[t] = floor;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
return floors;
}
The error CommunicationWithJS.java:75 is in
int numero_di_piano = Integer.parseInt(jsonFloor.getMember(NUMERO_DI_PIANO)+"");
The value *NUMERO_DI_PIANO* returned from the server is an integer, I don't understand this strange behaviour.
EDIT:
I cross-tested the japplet with firefox and chrome, using some println.
It comes out that the exception shows up only when I try to extract from the Json an int value.
I succesfully extracted a double and a string.
On firefox the applet still working...
On chrome 0 becames "0,000000" and 4 becomes "4,000000".
ADDITION
I solved the problem forcing the server to convert the integers in strings.
But I don't think it's the correct way to work, it's a workaround.
So, if somebody can come out with a valid answer, I will assign the points.
This is not a complete answer, but based on the error you are getting and the similar issue we're running into loading the website detailed in http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=647706 I believe the issue is related to the system locale. Is the system locale something different from en_US?
For a reason I haven't yet been able to understand, when running Java inside Firefox the locale does not influence the formatting methods, but on Chrome/Chromium it does, which leads to it generating locale-formatted floats ("0,0" instead of "0.0" in the Brazilian pt_BR locale, for instance) which Java can then not parse properly (presumably using a locale-independent conversion).
See also Problems using DecimalFormat

File Upload in fire fox

Iam not able to upload files in FireFox and safari but iam able to do it successfully in explorer.
When i tried to debug i found out that in case of IE the upload browser is giving the entire file as eg C:\Documents and Settings\jjayashree\My Documents\price.csv
but where as in FF and safari the upload widget is just giving the file name with no extension.
previously code was like this
if (fileName.contains("\")) {
index = fileName.lastIndexOf("\");
}
if (this.fileName != null && this.fileName.trim().length() > 0 && index >= 0) {
this.fileName = this.fileName.substring(index + 1, this.fileName.length());
int dotPosition = fileName.lastIndexOf('.');
String extension = fileName.substring(dotPosition + 1, fileName.length());
try {
if (profileType.equalsIgnoreCase("sampleProfile")) {
if (extension.equalsIgnoreCase("csv")) {
//fileNameTextBox.setText(this.fileName);
this.form.submit();
} else {
new CustomDialogBox(Nexus.INFO_MESSAGE, MessageConstants.SPECIFY_FILE_NAME_MSG).show();
}
}
} catch (Exception e) {
Window.alert("SPECIFY_VALID_FILE_NAME_MSG");
}
} else {
Window.alert("SPECIFY_A_FILE_MSG");
}
i changed it as
if (this.fileName != null && this.fileName.trim().length() > 0) {
this.fileName = this.fileName.substring(this.fileName.lastIndexOf("\") + 1, this.fileName.length());
}
i found it working but when the same is deployed in linux iam getting an error
I also hav a doubt becos in the doPost of servlet iam using fileName.replace("\", "/");
is this the problem. . How wil mozilla encounter this fileName.replace() wil it just see and find nothing can be replced and go or wil it throw any kind of Exception
Maybe try gwtupload? It simplifies file loading to one function call, and handles all the backend for you. It's a little complicated to get working but there's a tutorial on the site on how to do it.
http://code.google.com/p/gwtupload/

Categories

Resources