Applet JavaScript Communication - java

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);
}

Related

Jquery to Java method call issue

I have a jquery function which calls a java method as defined below.
JSObject window = (JSObject) webEngine.executeScript("window");
window.setMember("clickController", new RecordProcessor());
executejQuery( webEngine, new String(Files.readAllBytes(Paths.get("record.js"))));
webEngine is a JavaFX web engine used to load some website.
RecordProcessor is as below:
public class RecordProcessor {
public void process(Object object, String returnValue, String action) {
System.out.println(action);
}
}
Now in my record.js, I have a jquery function like this:
$(document).ready(function(){
$('*').click(function(event) {
clickController.process(event.target, "someString", "click");
});
}
clickController is the handle used to access the process method of RecordProcessor.
The problem is, when I click once on an element in the webpage, the process method is getting called multiple times. I have no idea why. Can anyone please explain what is going on? Also, a possible solution?
Here, for example, "click" is getting printed in the console many times, and it is not in constant number. Each time I execute, it prints different number of times.
The problem is this line:
$('*').click(function(event) { ...
The * is telling jQuery to bind the 'click' to every element on the page. The DOM is hierarchical, and the event will propagate by default to all the elements up the DOM.
Have you considered binding to document instead?
$(document).click(function(event) { ...

While loop in JSP to execute javascript not working?

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.

Is it possible to pass a JavaScript Variable to Java code inside a Scriptlet

I have a Scriptlet inside a function , which gets data from a Session and checks for a value inside the Map
Can i pass the User Selected Option which is a javascript variable to a Map ??
function checker()
{
var selObj = document.getElementById('selSeaShells');
var optionselectedvalue = selObj.options[selObj.selectedIndex].value.split(':')[0];
if(optionselectedvalue==''||optionselectedvalue==null)
{
alert('Select a Book');
return false;
}
if (!text_form.quan.value)
{
alert('Enter Quantity');
return false;
}
var selectedbook = optionselectedvalue;
var selectedquantity = text_form.quan.value;
<%
Map cart = (Map) session.getAttribute("cart");
if(cart.containsKey(selectedbook))
{
String quant = (String) cart.get(str);
}
%>
return true;
}
javascript plays on client side and JSP plays on server side.
What you need is you have to make a server request. And send that string a query parameter.
You might misunderstand that jsp and javascript existed on same document. Yes but JSP part compiles on server side itself and JSP output is sent to the client.
So solutions are: either go for html form submit or go for Ajax request.
java processing is done at server side and javacript executes on client side. If you do view source on html page you wont find any map.So you can not pass the javascript value to java code (as java code has already been processed by server and its no more).
If you are really want to pass the javascript value to server side you can take help help of ajax or form submission as Baadshah pointed above

check the checkbox if exists if not refresh in iMacros

I am trying to make a script for page, all I need is just simple java script, if there is a text on the page in example - no found the macros should hit the button find work. The macros must hit the button find work in 1 second interval.
Sorry for my english
This is an example how you could make JavaScript script for iMacros. The main part is CONTENT=EVENT:MOUSEOVER since that part hovers over a page element. If element is present it will return true else it will return false. Try it out.
var macroTest;
macroTest ="CODE:";
macroTest +="TAG POS=1 TYPE=INPUT:CHECKBOX FORM=NAME:TestForm ATTR=NAME:C9&&VALUE:ON CONTENT=EVENT:MOUSEOVER"+"\n";
if(iimPlay(macroTest)>0)
{
alert("Checkbox found");
}
else
{
alert("Checkbox not found");
}

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