Detecting whether browser can load Java Applet successfully - Unexpected behaviour on Firefox - java

I have an ASP.NET page which loads a Java Applet. I am first checking that the client computer has the ability to run the applet (Java version etc) by giving the tag an ID of "AppletID" - then I call a function of this applet which always returns "true".
So, the following line of code: var isRunning = document.getElementById('AppletID').appletRunning() will return "true" if the method "appletRunning" in the applet is called successfully (indicating that the client can load the applet correctly).
This was always working until recently. However, lately, Firefox browsers give me an intermettent dialog box showing the "You do not have the required minimum version of Java..." message. (Other times it correctly detects that the applet can be loaded). The applet then proceeds to load correctly, but the dialog should not be shown in the first place. I wonder why this is happening - it possibly could be that document.getElementById('AppletID') is being null when it is checked, thus leading to the "catch" part of the "checkAppletRunning" method? IE is always OK and never returns this dialog box.
Below is the code of the .aspx page.
<script type="text/javascript" language="javascript">
window.onload = function()
{
var appletCheck = checkAppletRunning();
if (appletCheck == 1)
{
alert("Server is down...please try again later.");
window.location.href = "Default.htm";
}
else if (appletCheck == 2)
{
alert("You do not have the required minimum version of Java enabled or installed. Java must be enabled or downloaded from http://www.java.com");
window.location.href = "Default.htm";
}
}
function checkAppletRunning()
{
var OK = 0;
var serverDown = 1;
var appletNotSupported = 2;
try
{
var isRunning = document.getElementById('AppletID').appletRunning();
if (isRunning)
{
return OK;
}
else
{
return appletNotSupported;
}
}
catch (e)
{
return appletNotSupported;
}
}
</script>
I would appreciate any help in this matter,
Thanks in advance,
Timothy

may be that the applet has not finished starting up.
try returning different result for an exception (or log the exception) to get a better idea why its failing.

A simpler approach is to rely on the fact that if Java is not available then the APPLET tag is not interpreted.
<HTML><HEAD></HEAD><BODY>
<APPLET CODE="MyApplet.class"
NAME="myApplet"
HEIGHT=400 WIDTH=400>
Oups! You don't have JAVA enabled, click here.
</APPLET>
</BODY></HTML>

Related

PrivilegedActionException trying to invoke a signed Java applet from JavaScript

First off, I am not a Java developer. I had to create a Java applet to invoke some code in a native DLL I wrote from the browser.
I use JNA to load a native DLL and invoke its methods.
I have signed the applet using a self-signed certificate.
The browser asks me whether or not to allow the execution of the applet.
The applet code which loads my DLL is enclosed within AccessController.doPrivileged block.
Like this:
public String Test()
{
pHelper = AccessController.doPrivileged(new PrivilegedAction<IHelper>()
{
#Override
public IHelper run()
{
return (IHelper)Native.loadLibrary("Helper", IHelper.class);
}
});
return "test";
}
The code works fine when debugged inside Eclipse.
It does not work when invoked from JavaScript. Causes PrivilegedActionException.
If I remove the entire AccessController.doPrivileged block and leave return "test" only, the code runs when invoked from JavaScript. Any code that doesn't require privileges runs fine when invoked from JavaScript.
Tested from Chrome version 40.something and Firefox 36 on Windows 8.1 64-bit.
The native DLL is 32-bit as well as JRE used to run the applet.
Any tips?
I have never resolved this particular mystery. However, I was able to find a workaround, thanks to my applet design specification which doesn't require exposing any applet methods which need to be invoked to perform privileged operations.
I have found that executing privileged operations inside the applet init() function will work. Only privileged operations executed by invoking from JavaScript seem to cause problems. Consider the following code.
public class MyApplet extends JApplet {
private IHelper pHelper = null;
private MyReturnedInfo pInfo = null;
public void init() {
pHelper = (IHelper)Native.loadLibrary("Helper", IHelper.class);
if (pHelper != null) {
pInfo = pHelper.GetInfo();
}
}
public String GetInfoString() {
if (pInfo != null) {
// need to call toString to convert from native wide char to something JavaScript will be able to interpret
return pInfo.MyInfoString.toString();
}
return null;
}
}
Upon loading this applet, calling document.myApplet.GetInfoString() from JavaScript (providing the applet has an ID "myApplet") will return the required information.
Interestingly though, after signing the applet with a certificate issued by a trusted authority such as VeriSign, even this would not work in IE, while it would work properly in FF and Chrome. I have seen signed Java applets which work fine when called from JavaScript in IE, but I guess my applet is special because it requires all-permissions attribute in the manifest and IE probably doesn't like that. It's a guess. However, I have never found the real reason for that either, because I was able to resort to another workaround. :) If you are reading this answer then I bet you are interested in it as well.
Java applets allow us to provide additional parameters which we are able to obtain by calling this.getParameter() from inside the init() function. Also, if we allow the applet to call JavaScript functions from our HTML document by using mayscript attribute, we can easily combine these two facts to provide the JavaScript function for applet to call after the information from our native DLL has been obtained.
Let's say that in our HTML, we define the JavaScript like this.
<script type="text/javascript" src="https://www.java.com/js/deployJava.js"></script>
<script type="text/javascript">
var attributes = {
id: "myApplet",
name: "myApplet",
code: "MyApplet.class",
mayscript: "true",
scriptable: "true",
archive: "/path(s)/to/jar(s)",
width: 0,
height: 0
};
var params = {
"AppletReady": "appletInitialized",
};
// For convenience, it's easier to deploy the applet using deployJava,
// so it writes the applet HTML tag for us after checking if Java is installed.
// We have included it above.
deployJava.runApplet(attributes, params, "1.8.0");
function appletInitialized(myString, someOtherArgument) {
// do something with your parameters
// NOTE: do NOT call alert() from this function!
// Because it will most likely cause your browser to freeze,
// I've found that's also one of the things Java doesn't like.
};
</script>
Then, we modify the Java applet code to look like this.
public class MyApplet extends JApplet {
private IHelper pHelper = null;
private MyReturnedInfo pInfo = null;
public void init() {
// Read the AppletReady parameter as passed from JavaScript
String paramKey = "AppletReady";
String jsLoadedCallback = this.getParameter(paramKey);
// Load the library and get the information
pHelper = (IHelper)Native.loadLibrary("Helper", IHelper.class);
if (pHelper != null) {
pInfo = pHelper.GetInfo();
if (pInfo != null && jsLoadedCallback != null) {
// Get the window which contains "this" applet
JSObject jsObject = JSObject.getWindow(this);
// Call the provided JavaScript function.
// You can use as many parameters as you need.
jsObject.call(jsLoadedCallback, new Object[] {
pInfo.MyInfoString.toString(),
pInfo.SomeOtherStringMaybe.toString()
});
}
}
}
}
However, if you need the applet to call your native DLL methods dynamically during runtime (I.E. you require the applet to expose functions which need to be called to perform privileged operations dynamically) this solution will not work for you and you are out of luck, at least if using JNA.

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

mixing javascript with 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.

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

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