While loop in JSP to execute javascript not working? - java

Please don't hesitate to edit the question or ask more details if I missed anything.
I know it's bad to use Scriptlets in JSP.
But I am assigned to maintain the existing JAVA project which is build only with only JSP and servlets(No framework).
My task is to implement the load balancing for my applicaiton using Apache HTTP Server.
The application works fine with out load balancing. When I implement the load balancing using the Apache HTTP Server, I am facing the problem with JSP.
I will give a scenario. My JSP has one while loop and it runs the javascript to update the content .
My JSP has,
<%
String jsPreAppend = "<script language=JavaScript >push('";
String jsPostAppend = "')</script> ";
String s=null;
int i = 0;
try {
while (true) {
System.out.println("count :"+i);
out.print(jsPreAppend + i + jsPostAppend);
out.flush();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
out.print(jsPreAppend + "InterruptedException: " + e + jsPostAppend);
}
i++;
}
} catch (Exception e) {
out.print(jsPreAppend + "Exception: " + e + jsPostAppend);
}
%>
My JavaScript has,
function push(content) {
document.getElementById('update').innerHTML = content;
}
The console output will be,
count :1
count :2
count :3
.
.
.
count : n
count :n+1
But the content will not updated in JSP. I thing the javascript fails in while loop.
But the SysOut() works because the updated content will be printed for every sec in the console .
But the same applicaiton work's fine with out load balancing(only one tomcat).
Hope our stack users will help me.

When your HTML gets rendered, JSP would have already got executed. So what you are trying to do cannot be achieved by that code.
You need to write a Java script method which does some update once in sometime. Check this thread to write the same logic using Javascript

Take into account that the while(true) loop will be executed server side. At that point, the response document (the HTML) is being built, and it can't be yet interpreted by the client. This loop is only writing javascript calls to a kind of buffer where the response is stored before it is sent to the client.
As an example, what that loop is doing is writing ad-infinitum to the response:
<script language=JavaScript >push('1')')</script>
...
<script language=JavaScript >push('n')')</script>
The fact that every line is being written at every second is irrelevant. You see the traces in the standard output at the correct times because that's what is being executed on the server.
This will make the request get stuck in that infinite loop unless there's an exception of some kind. Even if the loop ended at some point, and the request finished processing, when these statements would get executed by a client, they would be executed sequentially without any delay.
You should move those calls to client side, and schedule its execution with a client-side mechanism such as setTimeout(), like #sanbhat suggested in his answer.

Related

Java - How to wait until uploadFileToBlockBlob has finished?

Having a problem with Azure's sdk v10, when I'm uploading files the code carries on while the upload does its thing, but I'd really like to hold until the upload finishes.
I saw c# has an 'await' function, is there a Java way to handle this?
try{
AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(file.toPath());
TransferManager.uploadFileToBlockBlob(fileChannel, blob, 8*1024*1024, null, null)
.subscribe( azureResponse -> {
logger.info("Status code: " + azureResponse.response().statusCode());
if( azureResponse.response().statusCode() != 201){
logger.error("upload failed - " + azureResponse.response().body());
// throw exception
}
});
} catch( Exception e ) {
// handle the exception
}
I am not familiar with azure in particular but perhaps you can write a while loop that blocks thread executing until the upload process has finished. Something as simple as this should do the trick provided you have a separate boolean method that returns true when the file has finished uploading:
while(!hasFileUploaded())
{
// do nothing here
}
I am sorry if this answer seems a bit generic but without further knowledge about how and where the file is being uploaded I can't tell you exactly how to validate the upload process.

Trying to suppress errors while attaching browser

EDIT: I'm using the LeanFT Java SDK 14.50
EDIT2: for text clarification
I'm writing test scripts for a web application that sometimes opens popup browsers for specific actions. So natually when that happens, I will attach the new browser using BrowserFactory.attach(...). The problem is that leanFT does not seem to have a way to validate that the browser exists before attaching it, and if I try to attach it too early, it will fail. And I don't like to use an arbitrairy wait/sleep time as I can never really know how much time it's going to take for the browser to get be ready. So my solution to this is below
private Browser attachPopUpBrowser(BrowserType bt, RegExpProperty url){
Browser browser = null;
int iteration = 0;
//TimeoutLimit.SHORT = 15000
while (browser == null && iteration < TimeoutLimit.SHORT.getLimit()) {
try {
Reporter.setReportLevel(ReportLevel.Off);
browser = BrowserFactory.attach(
new BrowserDescription.Builder()
.type(bt)
.url(url)
.build()
);
Reporter.setReportLevel(ReportLevel.All);
} catch (GeneralLeanFtException e) {
try {
Thread.sleep(1000);
iteration += 1000;
} catch (InterruptedException e1) {
}
}
}
return browser;
}
Now, this works wonderfully with one exception. It generates errors in the leanft test result. Errors that I want to ignore because I know that it will fail a few times before it will succeed. As you can see, I've tried changing the ReportLevel while doing this in order to suppress the error logging, but it doesn't work. I've tried using
Browser[] browsers = BrowserFactory.getallOpenBrowsers(BrowserDescription);
thinking that it will return an empty Array if it finds nothing, but I still get errors while the browser is not ready. Does anyone have suggestions as to how I could work around this?
TL;DR
I'm looking for a way to either suppress the errors generated within my While..Loop or to validate that the browser is ready before attaching it. All of that, so that I can have a nice and clean Run Result at the end of my test (because these errors will present false negatives in all nearly all of my tests)
Addendum
Also, when the attach fails for the first time, I get a an exception
com.hp.lft.sdk.ReplayObjectNotFoundException: attachApplication
as expected, but all subsequent failures are throwing
com.hp.lft.sdk.GeneralLeanFtException: Cannot read property 'match' of null
I've compared both stack traces and they are identical except for the last 2 lines which happen within the ReplayExceptionFactory.CreateDefault() so I think that there is something that gets corrupted during the exception generation, but that is within the leanft.sdk.internal package so there might not be a lot we can do about it right now.I'm guessing that if I did not get that second "cannot read property" exception, I would correctly get the ReplayObjectNotFoundException until the browser is correctly attached.
I'd rather not force an attach endlessly until it works. Even if we'd solve the false negatives, we'd still have a not so good approach to the problem.
The cleanest solution would be to see if there is anything to attach to in the first place.
And you can do just that by getting all the browser instances that meets your description.
Browser[] browsers = BrowserFactory.getAllOpenBrowsers(new BrowserDescription.Builder().build());
Any element in this collection is an already "attached" browser - you can start using it.
If the list doesn't contain your browser instance, rerun the query.

Google Drive script doesn't work,

I found online google drive script that sends an email with the changes on the prices of Amazon products that I insert.
This is the file
I couldn't make it work for 100%.. It work sometimes only for some of the products, and I cant find the reason.
Please help me to understand what is wrong.
Also, I wanted to know if I could modify the script so it will send me an alert twice a day and not only once, as it is now.
Configuring Email Notification Intervals
The email notifications are configured as Google Apps Scripts triggers invoking the priceEmail function. They're randomly assigned when you initialize the spreadsheet (refer to the Start_Tracking implementation).
To configure email notifications manually – e.g. adding a second daily email – open the Copy of Amazon Price Tracker by ctrlq.org script associated with the spreadsheet (via the spreadsheet Tools > Script editor... menu command). Then proceed to opening the triggers dialog (Resources > Current project's triggers menu command) and add a new time-driven trigger for the priceEmail hook.
Script Errors
By default, the priceEmail function handles all errors silently. There's not much clue to what would cause the script to not work 100% of the time. If you'd like to be notified of the errors, either remove the exception handling in the current implementation or update the priceEmail body.
I'd advice making the following modifications (again via the spreadsheet Tools > Script editor... menu command):
function priceEmail() {
var sheet, data, page, table="";
sheet = SpreadsheetApp.getActiveSheet();
data = sheet.getRange(2, 2, 21, 2).getValues(); // Note that the script will only look at the first 20 rows.
try {
for (i in data) {
if (data[i][0] !== "") {
page = UrlFetchApp.fetch(
"http://ctrlq.org/aws/lookup/", {
"method": "post", "payload": {"url":data[i][0]}
}).getContentText();
table = table + tableRow(page);
}
}
} catch (e) {
Logger.log(e.toString());
// Following line inserted to include any error messages in your daily email(s).
table += "<tr><td><strong>Error:</strong></td><td>" + e + " (url: \"" + data[i][0] + "\")</td></tr>";
}
// ...

Applet JavaScript Communication

On my web page I am running an applet and in order to warn user for certain inputs to the applet, I am using printing the errors to the html page. In order to do this I am using javascript applet communication. Below is the code for the Javascript:
<script type="text/javascript">
var counter=0;
function RemoveAppletErrorMessage()
{
var AppletErrorTag=document.getElementById("AppletErrorMessages");
if(AppletErrorTag!=null)
{
document.body.removeChild(AppletErrorTag);
}
}
function updateWebPage(s)
{
if(counter>=1) RemoveAppletErrorMessage();
var parag=document.createElement('P');
parag.setAttribute("id","AppletErrorMessages");
var txt=document.createTextNode(s);
parag.appendChild(txt);
document.body.appendChild(parag);
counter++;
}
</script>
Here, the Javascript function updateWebPage(s) function is called from the Java applet when a JButton is clicked with the following code:
if(jso != null && !errorMessage.isEmpty())
try {
jso.call("updateWebPage", new String[] {errorMessage});
return;
}
catch (Exception ex) { ex.printStackTrace(); }
In terms of communication everything works fine. However, when the JButton is clicked the second time, I am trying to clear up the error messages with RemoveAppletErrorMessage() calling from updateWebPage(s). It seems like every time I hit the JButton the error messages are appended to the web page which I do not want. I have tried to clear it with .innerHTML='' which did not work in the first place, so I changed my strategy to adding a node and checking if the node exists, clearing that node and adding again. What might be going on wrong?
May be you're appending to your errorMessage variable in Java?
I'd open a div with an id of AppletErrorMessages and use jQuery in my updateWebPage() function like this (e.g. stop creating a new paragraph every time).
function updateWebPage(s)
{
$("#AppletErrorMessages").html(s);
}

selenium.waitForPageToLoad doesn't seem to be waiting

I'm updating a Selenium program I wrote a while back and part of it has stopped working. I want to go through a whole series of links on a page, click on each, making sure that some expected text is present. But sometimes a log-in page (https://library.med.nyu.edu/sso/ezproxy_form.php) appears before the desired page, in which case I need to log in before checking the page. The problem is, no matter what string I put in to check whether I've landed on the log in page, Selenium concludes it's not present and skips logging in, obviously causing everything else to fail. See below--I'm not sure that was actually the problem. It seems to be instead that it's rushing through the "if we need to sign in" code without actually signing in, then obviously failing the main part of the test because it's not on the right page.
Here's the code--does anyone see my mistake?
for (int i = 0; i < Resources.size(); i++) {
try {
selenium.open("/");
selenium.click("link=" + Resources.get(i).link);
selenium.waitForPageToLoad("100000");
if (selenium.isTextPresent("Please sign in to access NYUHSL e-resources")) {
selenium.type("sso_user", kid);
selenium.type("sso_pass", password);
selenium.click("name=SignIn");
selenium.waitForPageToLoad("100000");
}
if (!selenium.isTextPresent(Resources.get(i).text)) {
outfile.println(Resources.get(i).name + " failed");
}
} catch (Exception e) {
outfile.println(Resources.get(i).name + " could not be found--link removed?");
}
}
Does the login page have a page title? If yes, try validating the page title using selenium.getTitle() method to check if you are headed to login page. If not, proceed clicking on the link without logging in.
I think page title validation can help resolve this issue
Try putting:
selenium.setSpeed("1000");
Right after the selenium.open this will inject 1 second delay (1000ms) between selenium commands. You should make it a standard practice to add this, especially if you're not running headless browsers.
Also you might consider using, since you know the url you are expecting to be on if on the login page, the selenium command getLocation. This will return the absolute URL of the current page. Might be more effective than trying to look for elements that can change at any time within the page.
So to use getLocation in your code above:
if (selenium.getLocation() == "your reference url"){
do your login stuff here
}
Again this is just a sample to illustrate what I'm saying. Hope it helps you out.

Categories

Resources