mixing javascript with java - java

basically my problem is when I want to mix javascript with java code since I did not take the variable (var nombreRodamiento javascript) when I put the "<%" to start putting java code.
please note the bold line, which is what the compiler does not like.
<script type="text/javaScript">
function moveToRightOrLeft(side) {
var listLeft = document.getElementById('selectLeft');
var listRight = document.getElementById('selectRight');
if (side == 1) {//izquierda
if (listLeft.options.length == 0) {
alert('Ya aprobaste todos los items');
return false;
} else {
var rodamientoElegido = listLeft.options.selectedIndex;
var nombreRodamiento = listLeft.options[rodamientoElegido].text;
move(listRight, listLeft.options[rodamientoElegido].value,
listLeft.options[rodamientoElegido].text);
listLeft.remove(rodamientoElegido);
<%
**String nombreRodamiento = '%> nombreRodamiento;<%'**
for (int i=0;i<listaItems.size();i++){
if (listaItems.get(i).equals(nombreRodamiento))
listaItems.remove(i);
}
%>
if (listLeft.options.length > 0) {
listLeft.options[0].selected = true;
}
}
}
}
</script>
Regards

Assuming that this is all inside of a JSP. The java code (scriptlet, everything inside the <% %> tags) will execute server side, and the javascript will execute client side (in the user's browser). Yet you seem to be assigning a java variable the value of a javascript variable, nombreRodamiento. That is not going to work. The javascript is just text, with no values, execution context, etc, whenever the scriplet is being evaluated.

Java strings require double quotes, and you're missing a semicolon, which Java will not automatically insert.

Assuming this is a part of jsp file java code and js code executes separately. first java code get execute on server side and then the javascript code and that is on client side. Infact the java scriplet in jsp renderes the js code to be executed later on client which in this case is a browser.
Hence one cannot assign javascript variable value to a java variable but the reverse is possible.T
Edit:
I can give you the steps as I dont know your server side implementation.
render the page. You must be rendering the list by some type of array or equivaletn object on server side. save both right and left side element on session.
when the list box do some element exchange. exucute your js code.
you have to update the same on server side so send the selected element index and side information to server side using ajax.
update the server side list objects in the session accordingly. Update db if needed.
From next time render this list box suing this objects on ths server side sessions.
Hope this helps.

Related

How to speed up page parsing in Selenium

What can I do in case if I load the page in Selenium and then I have to do like 100 different parsing requests to this page?
At this moment I use different driver.findElement(By...) and the problem is that every time it is a http (get/post) request from java into selenium. From this case one simple page parsing costs me like 30+ seconds (too much).
I think that I must get source code (driver.getPageSource()) from first request and then parse this string locally (my page does not change while I parse it).
Can I build some kind of HTML object from this string to keep working with WebElement requests?
Do I have to use another lib to build HTML object? (for example - jsoup) In this case I will have to rebuild my parsing requests from webelement's and XPath.
Anything else?
When you call findElement, there is no need for Selenium to parse the page to find the element. The parsing of the HTML happens when the page is loaded. Some further parsing may happen due to JavaScript modifications to the page (like when doing element.innerHTML += ...). What Selenium does is query the DOM with methods like .getElementsByClassName, .querySelector, etc. This being said, if your browser is loaded on a remote machine, things can slow down. Even locally, if you are doing a huge amount of round-trip to between your Selenium script and the browser, it can impact the script's speed quite a bit. What can you do?
What I prefer to do when I have a lot of queries to do on a page is to use .executeScript to do the work on the browser side. This can reduce dozens of queries to a single one. For instance:
List<WebElement> elements = (List<WebElement>) ((JavascriptExecutor) driver)
.executeScript(
"var elements = document.getElementsByClassName('foo');" +
"return Array.prototype.filter.call(elements, function (el) {" +
" return el.attributes.whatever.value === 'something';" +
"});");
(I've not run the code above. Watch out for typos!)
In this example, you'd get a list of all elements of class foo that have an attribute named whatever which has a value equal to something. (The Array.prototype.filter.call rigmarole is because .getElementsByClassName returns something that behaves like an Array but which is not an Array so it does not have a .filter method.)
Parsing locally is an option if you know that the page won't change as you examine it. You should get the page's source by using something like:
String html = (String) ((JavascriptExecutor) driver).executeScript(
"return document.documentElement.outerHTML");
By doing this, you see the page exactly in the way the browser interpreted it. You will have to use something else than Selenium to parse the HTML.
Maybe try evaluating your elements only when you try to use them?
I dont know about the Java equivalent, but in C# you could do something similar to the following, which would only look for the element when it is used:
private static readonly By UsernameSelector = By.Name("username");
private IWebElement UsernameInputElement
{
get { return Driver.FindElement(UsernameSelector); }
}

js function containing php executes when not called

I have the following code within the tag of my page:
<script>
function LogInOut()
{
// Get the current login status
alert("executing LogInOut");
$loginStatus = "<?php echo $_SESSION['login']; ?>";
if ($loginStatus == "true")
{
<?php
echo "<br />script function";
$_SESSION['login'] = "false";
session_destroy();
?>
document.getElementById("loginState").innerHTML = "login";
}
else
{
window.location = 'login.php';
}
}
</script>
I find that the php code executes when the page loads. The function (for debugging) is NEVER called yet the php code executes while none of the rest of the script executes! Can anyone clarify why this could be happening?
thank you,
Shimon
Classic case of mixing Javascript, a client side language, with PHP, a server side language. They run at two different locations and that being said this will never be possible.
PHP runs before javascript and if your trying to mix it with javascript, use it to echo dynamic data. eg:
var logged_in = <?=($_SESSION['login'] ? 'true' : 'false')?> ;
Javascript runs within the browser and after PHP, do not use php code thinking it will run inside of the browser
You will need something to call the function
In your case, call it when page is ready.
$(document).ready(function(){
LogInOut();
});
Or using a console for modern browser type in:
LogInOut();

preventing string concatenation in javascript function during JSP compilation

var result = null;
function setSendButton(userInput){
var clicked=userInput;
result = "<%=mb.myMethod(clicked)%>";
}
where myMethod is a java method called through using jsp tags. it is defined as:
public boolean myMethod(String isClicked){
if(isClicked.equals("true")){
return true;
}else{
return false;
}
}
for some reason stepping i got a JSP compilation error that compiles the code where var clicked value of "true" is not passed and clicked becomes a string during JSP compilation like so: mb.myMethod(clicked) instead of mb.myMethod("true")
It can't work like that.
The Java code in JSP is translated and compiled on the server side before sending to the client's browser. The javascript variable is available only after the JSP is translated and compiled to become a HTML file and sent to the client browser. At that time, The mb.myMethod is already already executed on the server side.
In short, you can passed java code to js assignment but not the other way around.
Wouldn't this work?
var result = null;
function setSendButton(){
result = "<%=mb.myMethod(true)%>";
}

Include page javascripts conflicting with outer page javascripts

My problem is a little difficult to explain, but I will try.
I have 2 jsp pages Outer.jsp and Inner.jsp
Outer.jsp
Script: src="tabs.js"
var PageTabs = "Tab1"
#include "Inner.jsp"
Inner.jsp
Script: src="tabs.js"
var PageTabs = "Tab2~Tab3~Tab4"
Both the jsp pages use the same tabs.js to render some tab elements on the page. The "PageTabs" variable is one of the many common variables that are used by tabs.js. So what happpens is while rendering, the tabs.js takes the latest "PageTabs" variable i'e var PageTabs = "Tab2~Tab3~Tab4" even while rendeing tabs of Outer.jsp.
Note: The page variables and tabs.js are part of standard elements recieved from client. So they have to be used to give the same look and feel for application.
What I need is a way to isolate the "Inner.jsp" from accessing scripts of "Outer.jsp". This will prevent the tabs element from being confused over which variables to use.
I hope I am somewhat clear. Please let me know if I need to provide any more clarifications. Thanks.
JavaScript is interpreted top-to-bottom inside a page, so your second PageTabs value overrides the first one. One option is to use a different name for the variable (and parameterize tabs.js functions rather than rely on global vars.)
When using jsp include, one of a very useful skill is to make your .js code modular . This is also an important method to encapsulate code and avoid conflict.
tab.js:
var tabModule = (function(my){
var model;
return {
setModel: function(model){/*....*/}
//other api functions
}
})(tabModoule||{});
Outer.jsp:
tabModule.setModel({PageTabs : "Tab1"});
Innder.jsp:
tabModule.setModel({PageTabs : "Tab2~Tab3~Tab4"});

How can I embed a Java applet dynamically with Javascript?

I want to be able to insert a Java applet into a web page dynamically using a Javascript function that is called when a button is pressed. (Loading the applet on page load slows things down too much, freezes the browser, etc...) I am using the following code, which works seamlessly in FF, but fails without error messages in IE8, Safari 4, and Chrome. Does anyone have any idea why this doesn't work as expected, and how to dynamically insert an applet in a way that works in all browsers? I've tried using document.write() as suggested elsewhere, but calling that after the page has loaded results in the page being erased, so that isn't an option for me.
function createPlayer(parentElem)
{
// The abc variable is declared and set here
player = document.createElement('object');
player.setAttribute("classid", "java:TunePlayer.class");
player.setAttribute("archive", "TunePlayer.class,PlayerListener.class,abc4j.jar");
player.setAttribute("codeType", "application/x-java-applet");
player.id = "tuneplayer";
player.setAttribute("width", 1);
player.setAttribute("height", 1);
param = document.createElement('param');
param.name = "abc";
param.value = abc;
player.appendChild(param);
param = document.createElement('param');
param.name = "mayscript";
param.value = true;
player.appendChild(param);
parentElem.appendChild(player);
}
document.write()
Will overwrite your entire document. If you want to keep the document, and just want an applet added, you'll need to append it.
var app = document.createElement('applet');
app.id= 'Java';
app.archive= 'Java.jar';
app.code= 'Java.class';
app.width = '400';
app.height = '10';
document.getElementsByTagName('body')[0].appendChild(app);
This code will add the applet as the last element of the body tag. Make sure this is run after the DOM has processed or you will get an error. Body OnLoad, or jQuery ready recommended.
I would have suggested doing something like what you're doing; so I'm baffled as to why it's not working.
Here's a document that looks pretty authoritative, coming from the horse's mouth as it were. It mentions the idiosyncrasies of different browsers. You may end up needing to do different tag soups for different implementations.
But maybe there's something magic about applet/object tags that keeps them from being processed if inserted dynamically. Having no more qualified advice, I have a crazy workaround to offer you: Howzabout you present the applet on a different page, and dynamically create an IFRAME to show that page in the space your applet should occupy? IFRAMEs are a bit more consistent in syntax across browsers, and I'd be surprised if they were to fail the same way.
Maybe you should use your browser's debugging tools to look at the DOM after you swap in your applet node. Maybe it's not appearing where you think it is, or not with the structure you think you're creating. Your code looks OK to me but I'm not very experienced with dynamic applets.
There is a JavaScript library for this purpose:
http://www.java.com/js/deployJava.js
// launch the Java 2D applet on JRE version 1.6.0
// or higher with one parameter (fontSize)
<script src=
"http://www.java.com/js/deployJava.js"></script>
<script>
var attributes = {code:'java2d.Java2DemoApplet.class',
archive:'http://java.sun.com/products/plugin/1.5.0/demos/plugin/jfc/Java2D/Java2Demo.jar',
width:710, height:540} ;
var parameters = {fontSize:16} ;
var version = '1.6' ;
deployJava.runApplet(attributes, parameters, version);
</script>
I did something similar to what Beachhouse suggested. I modified the deployJava.js like this:
writeAppletTag: function(attributes, parameters) {
...
// don't write directly to document anymore
//document.write(startApplet + '\n' + params + '\n' + endApplet);
var appletString = startApplet + '\n' + params + '\n' + endApplet;
var divApplet = document.createElement('div');
divApplet.id = "divApplet";
divApplet.innerHTML = appletString;
divApplet.style = "visibility: hidden; display: none;";
document.body.appendChild(divApplet);
}
It worked ok on Chrome, Firefox and IE. No problems so far.
I tried at first to have a div already created on my html file and just set its innerHTML to the appletString, but only IE were able to detect the new applet dynamically. Insert the whole div direclty to the body works on all browsers.
Create a new applet element and append it to an existing element using appendChild.
var applet = document.createElement('applet');
applet.id = 'player';
...
var param = document.createElement('param');
...
applet.appendChild(param);
document.getElementById('existingElement').appendChild(applet);
Also, make sure the existing element is visible, meaning you haven't set css to hide it, otherwise the browser will not load the applet after using appendChild. I spent too many hours trying to figure that out.
This worked for me:
// my js code
var app = document.createElement('applet');
app.code= 'MyApplet2.class';
app.width = '400';
app.height = '10';
var p1 = document.createElement('param');
p1.name = 'sm_UnwindType';
p1.value='200';
var p2 = document.createElement('param');
p2.name = 'sm_Intraday';
p2.value='300';
app.appendChild(p1);
app.appendChild(p2);
var appDiv = document.getElementById('applet_div');
appDiv.appendChild(app);
-----html code:
<div id="applet_div"></div>

Categories