Jquery to Java method call issue - java

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) { ...

Related

Can Selenium web driver track web page changes?

Each time the web page has changes I want to get the text elements of web page. So for having the text elements, here is my method:
public void getContentPage(WebDriver driver) {
WebDriverWait wait = new WebDriverWait(driver, 15);
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.tagName("body")));
System.out.println(element.getText());
}
What I need is a kind of listener using Selenium to call the above method each time there are changes in HTML body content:
public void listen (WebDriver driver) {
// some kind of listner that waits for any changes to happen in HTML
if (changed) getContentPage(driver);
else keeplistning()
}
I'm not sure there is a way to track all and every change on the page and I'm not sure you want this since this will trigger you on many irrelevant changes.
What can be useful here is to track changes on some specific relevant element(s).
So, to wait until some specific element is changed you can use refreshed ExpectedCondition like the following:
WebElement button = driver.findElement(By.id("myBtn"));
wait.until(ExpectedConditions.refreshed(button));
In case you wish to monitor several elements it will be something like this:
wait.until(ExpectedConditions.or(
ExpectedConditions.refreshed(element1),
ExpectedConditions.refreshed(element2),
ExpectedConditions.refreshed(element3)));
You should, of cause, wrap this in some method according to your specific code use. I wrote here the basic idea only.
UPD
To track the entire page you can use driver.getPageSource(); method. Polling the page state with some time interval and comparing the value of previous result of this method with the new result will give you indication of any page content change.

Struts 1 - Calling more actions via one post without altering struts-config

I'm working on a legacy app (struts 1, own framework, java 6, on WebSphere 7) where I need to change the behavior of an operation.
Let's call them (1) CopyItem, (2) AlterItem, (3) MarkAsCopied.
A button called one service which needs to be replaced with three other services.
Depending on the result of the first one, invoke the second one and so on.
I want to navigate in the end where the first one would take me (so it would look like the original behavior from user point of view).
Initially I thought I wrap every parameter I need into a form, POST it, and then on the Java side, I would call action execute for each service. Technically from CopyItemAction.execute() of CopyItem I would call AlterItem and MarkAsCopied executes as well.
I feel that this is pretty far from a clean solution.
Do you have a better idea, how to do this?
In the end I did it via synchronized Ajax. Which is definitely bad practice, so I do not recommend if you have the access on the backend code. However in my case now it turned out to be a working not-that-ugly solution. Based on Dave Newton's (https://stackoverflow.com/users/438992/dave-newton) proposal.
Keep that in mind the struts actions are still called according to the configuration defined in struts-config.xml.
I created the js function below and invoked the services with the specified forms one by one. This way a form (POST) submit calls the struts action, but doesn't navigate away. After they run successfully I redirected the page.
function submitForm(form) {
if (form !== null && form !== undefined) {
let formData = new FormData(form);
let xhr = new XMLHttpRequest();
xhr.open('POST', form.getAttribute('action'), false);
var successResponse = false;
xhr.onreadystatechange = function() {
if(xhr.readyState == XMLHttpRequest.DONE) {
successResponse = xhr.status == 200;
}
}
xhr.send(formData);
return successResponse;
}
}
In conclusion: this is not a recommended solution, but if you're in such a situation like me, then it works.

How to set the input for the UI part in eclipse e4?

I am using eclipse e4 application. I am using the eventBroker to pass values from one part to another part. If many parts(Kind of tabs) are open , how to pass values to the part(tab) that is currently selected. ? I am using the #UIEventTopic to get the values for the part. But the problem is ,the values are replicated to all the tabs. In other words , I am trying to show different JFreechart in different tabs, but the charts are replicated to the previous tabs.
Can anyone please suggest me some ideas?
Thanks in advance
The event broker always broadcasts to anything that is dealing with the event, you can't use it to send to one specific thing.
If you are in a Handler you can get the current part in the #Execute method and set a value directly in your class - something like:
#Execute
public void execute(#Named(IServiceConstants.ACTIVE_PART) MPart activePart)
{
Object part = activePart.getObject();
if (part instanceof MyClass)
{
((MyClass)part).setValue(xxxx);
}
}
Update:
If you are in another part use the EPartService to get the active part:
#Inject
EPartService partService;
...
MPart activePart = partService.getActivePart();
Object part = activePart.getObject();
if (part instanceof MyClass)
{
((MyClass)part).setValue(xxxx);
}
You can also use EPartService.findPart("part id") to find a part with a given id.

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

Integrate jquery.validate with bootstrap popover

I've a registration form validated with jquery.validate plugin.
Now, if the form its not valid, i want to put the result of validate in a bootstrap popover, but really, i don't have idea how i can do this.
Some help?
Checkout this: https://github.com/mingliangfeng/jquery.validate.bootstrap.popover
it is a plugin integrating jQuery validate and bootstrap popover, you may get some idea there.
The jQuery.validate plugin has a method called errorPlacement.
This takes 2 arguments:
error: the error message created by the validator on that element.
element: the element being validated.
The Validator sends the error/valid message here and you can handle all the placement logic in there. What I tend to do is put all that in .setDefaults before initialising the validator.
Example:
jQuery.validator.setDefaults({
ignore: "",
errorPlacement: function (error, element){
// Insert error messgae placement logic here
}
});
For showing and hiding tooltips for your errors, you'd need to use the errorPlacement and success callback functions.
Since you've shown no code of your own, here is a similar setup using the Tooltipster plugin, just to give you an idea about how to use these callback functions. Adjust as needed for Bootstrap popovers or whatever other tooltip plugin you may use.
$(document).ready(function () {
$('#myform').validate({
// rules and options here,
errorPlacement: function (error, element) {
// construct tooltip with message as per plugin method
$(element).tooltipster('update', $(error).text());
// show tooltip as per plugin method
$(element).tooltipster('show');
},
success: function (label, element) {
// hide tooltip as per plugin method
$(element).tooltipster('hide');
}
});
});
DEMO: http://jsfiddle.net/kyK4G/
Reference: https://stackoverflow.com/a/14741689/594235
Documentation: http://jqueryvalidation.org/validate

Categories

Resources