How to create file from java applet? - java

I'm trying to create an excel file and save to local file system using java applet. After sign the application, i can successfully create the file by directly invoking the applet. However, when i try to call the method from javascript, it failed without any error message. I'm wondering if there is any policy control to prevent java method to be called from javascript?
<html>
<script language="JavaScript">
function createExcel()
{
document.excel.createExcel();
document.excel.setMessage("hello world from js");
}
</script>
<body>
<input type="button" value="Generate Excel" onclick="createExcel()" />
<applet id='applet' name='excel' archive='Office.jar,poi-3.7-20101029.jar' code='com.broadridge.Office.class' width='100' height='100'></applet>
</body>
</html>

Methods in a trusted applet that are invoked using JavaScript need to be wrapped in a PrivilegedAction and called using one of the AccessController.doPrivileged(..) variants.
Sandboxed file-system access
Plug-In 2 JREs (Oracle's 1.6.0_10+ JRE for example) offer sandboxed access to the local file-system using the JNLP API file services (specifically the FileSaveService). See the file service demo. for an example.
Applet element
An applet called by JS should declare that it is scriptable in the HTML. As for getting that 'HTML', the best way to write it is using Oracle's deployJava.js. It will not only write the applet element the best way that is currently known for each browser, but does JRE presence (is Java installed?) and minimum version (is the JRE the minimum version needed to run this applet?) checking.

There may be several issues here.
1) You have to use the JavaScript deployment method for the applet (see link).
2) If the method you try to invoke is not in the applet-child itself, you first have to get an instance of the class in question and then invoke it's method, e.g. (for Calculator class):
var calculator = mathApplet.getCalculator();
calculator.setNums(numA, numB);
Moor info

Related

Calling Java from JavaScript and vice-versa why?

I know that we can call Java from JavaScript and vice-versa, but I'm wondering myself about when take that power and use it in a healthy way. I'm talking about real world applications, not "hello world".
As many developers usually I'm developing java and javascript but I not have the enough experience for know when mix those guys is a good idea.
Please if there is some developer who can share his knowlege about how has constructed real world applications using this mix would be great :).
Apologies, I failed to convey my doubt in a worthwhile way, so, Did you hear about Narshorm?, for instance you could call Javascript code from a Java Class, but I dont see a business case in which those capabilities increase the worth to my server side applications.
This is a nashorn hello world, in this application there is a Java Main which "eval" the content of a .js file calling the functions inside the .js file.
My mainly doubt is when this power would be really useful
In web application development (which is the usual scenario where Java and JavaScript interact):
there are 2 places where you can make the server and client side languages interact with each other:
At rendering time, this is, when generating the HTML output to the user.
At runtime, this is, when the HTML has been generated and it is at client side (e.g. browser client).
For the first case, let's say we have a Servlet that adds an attribute to the request and forward to a new (JSP) view. This is an example of the servlet:
#WebServlet("/hello")
public class HelloServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
// Prepare messages.
request.setAttribute("name", name);
request.getRequestDispatcher("/WEB-INF/hello.jsp").forward(request, response);
}
}
Then in your view (hello.jsp file inside WEB-INF folder), you have a code like this:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Servlet Hello World</title>
<script>
function changeName(var newName) {
document.getElementById('divName').innerHtml = 'Hello ' + newName;
}
window.onload = function () {
changeName('${name}');
}
</script>
</head>
<body>
<div id="divName">
</div>
<form id="name" action="hello">
Change name to: <input type="text" name="name" />
<br />
<input type="text" value="Change the name" />
</form>
</body>
</html>
By using this approach, we can communicate Java generates variables (NEVER SCRIPTLETS) directly to JavaScript when rendering the view. So we can access to Java page, request, session and context attributes only when creating the HTML that is going to the client.
Note that if you want to re-execute this Java code, you should fire a new request to the server in order to execute the Java code. This is where ajax come handy.
Ajax lets you communicate with the server side asynchronously, the server will prepare a response for your request, and then in client side you will define how to use it. For this purpose, it is better to use a common format for the communication. The most preferred format nowadays is JSON. Ajax interactions to servlet is widely covered here: How to use Servlets and Ajax? (no need to reinvent the wheel in this post).
In standalone or mobile applications:
Java will run on the client machine. Note that here Java can execute JavaScript code through a JavaScript engine like Rhino or nashorn. This is useful when you have lot of functionalities already written in javascript (like an external library) and do not want to migrate all the code to Java. You can just use ScriptEngineManager and StringEngine classes to execute the code in JavaScript in your Java application. A real-world example of using JavaScript in a Java application is Pentaho Kettle, written in Java, that allows applying transformations to your code through JavaScript scripts.
More info on Nashorn:
Oracle Nashorn: A Next-Generation JavaScript Engine for the JVM
Javascript is a client-side scripting language. This is used to interact with what a user can see and do on a website (html) For instance, you can use javascript to make something happen when you click on a button, or hover over a menu item.
Java is a server-side language. This is compiled code which runs on a server and the user generally has no idea of what happens here. A good real world application of using server-side code (Java in your case) is for database queries and updates.
For example, if you have a web page that asks a user to register for an account, there might be a form with a text box for username and password. When the user clicks "register" this information is to be stored in the database.
In this, your javascript will have code that is executed when the button is pressed which captures this data. It then sends this to the server with an HTTP Post (ajax is often used to send this) The server gets this data and executes the Java code you write to insert this into the database.
A very simple website which does not need to store user data may not need any server side code at all, but in most real world scenarios, there is some server code working alongside your html and javascript
One common place for these technologies to be used together is AJAX. The server side web services might be written in Java and the client side Javascript calls web services.
It's worth pointing out that Java and Javascript are actually completely different languages. The web services could be written in any language.

Java Embedding Into HTML

I'm sure this question has been asked a million times, but no matter how many Google searches I do I cannot get this working. I'm basically trying to get a project with multiple packages in it to be embedded in a webpage. I made a test program which just made some balls bounce around the screen and was able to get that running. I put the main class in one package and the ball class in another just to test it and it seems to be running fine. But the program that I actually need in a web page (just called FinalProject) refuses to do it.
The best thing I can get it to do is give me a blank screen, without giving an error but just white. If I try clicking where it should be nothing happens, I think because the applet is there but is just showing white so I can't see it. I did use the applet tag, which from my understanding is now depreciated but I need to turn this project in on a webpage just so the teacher can see it. We've already tested that other people's projects (which used the applet tag) work, so I was trying to stick with that for now and worry about getting it working on every browser afterwards. Though that could very well be the problem. Maybe it would work on his browser but not mine here. I've tried running my program on Google Chrome, Mozilla Firefox, and Internet Explorer with no luck.
Here is the HTML code:
<html>
<head>
</head>
<body>
<applet code = "main.FinalProject.class" width = "700px" height = "500px"></applet>
</body>
</html>
The HTML file this is written in is in [Eclipse Workspace]/FinalProject/bin/test.htm. The FinalProject.class file referenced in the HTML exists in [Eclipse Workspace]/FinalProject/bin/ main/FinalProject.class. The FinalProject.class file acts as the main class, so I'm pretty sure that's the one I need to run. It's the one with the init(), actionPerformed(), paint() methods and all that good stuff.
Currently I'm trying to run this offline on my computer, so there shouldn't be any net URL's I would think. I used Eclipse to write the Java code, dunno if that makes any difference. Unfortunately, the Java code is rather large, too much to reproduce here, if there's something specific you think is the problem I can look and post that small section.
A few of my friends managed to get theirs working, however they said they had to remove all their .png files (annoying but doable for my project). They also said had to remove all their mouse movement code. My program is kind of dependent on that, I need that for it to work at all. I know there MUST be a way to use all the MouseListener and MouseMoveListener code online, maybe it's a little different though. I dunno if that has something to do with this, but I figured I'd point it out just to be safe.
Any help here would be greatly appreciated.
Basically you're asking something like: How to deploy a java applet for today's browsers (applet, embed, object)?
Based on that, I think what you want is:
<object
classid="clsid:CAFEEFAC-0015-0000-0000-ABCDEFFEDCBA"
style="height: 500px; width: 700px;">
<param name="code" value="FinalProject.class">
<comment>
<embed code="FinalProject.class"
type="application/x-java-applet"
height="500" width="700">
<noembed>
This browser appears to lack support for Java Applets.
</noembed>
</embed>
</comment>
</object>
Now, you have a filename of main.FinalProject.class in your code. It seems like FinalProject.class would be more likely. But yours could be right. In any case, this html file needs to be in the same folder as main.FinalProject.class or FinalProject.class and whatever classes may also be required.
Now, you may also need to make sure your browsers can actually run an applet. See: How do I enable Java in my web browser?
Update
Based on feedback from Andrew Thompson, the preferred solution is to use JavaScript from Oracle, like this:
<script src="http://www.java.com/js/deployJava.js"></script>
<script>
var attributes = {
code:'FinalProject.class',
width:700, height:500} ;
var parameters = {}; // does the Applet take parameters?
var version = '1.6' ; // does the Applet require a minimum version of Java
deployJava.runApplet(attributes, parameters, version);
</script>
This requires the ability to load arbitrary JavaScript, but you could also capture that deployJava.js and have that be local as well. Might be worth a look.

Can web developers stop IE popup dialog that Java is not installed?

I've developed a website (internal website behind a firewall) that uses a Java applet. If Java is not installed on the client, then it will fall back to other solutions.
The issue I now have is that at least IE9 pops-up a dialog saying that my webpage uses Java and how to install this. I'm already taking care of this on my webpage, so can I use some Meta tag or other to stop IE9 from ruining the user experience?
Users will think my webpage can't be run without Java when this pop-up is shown!
HTML
<applet
id="tinyApplet"
width="0"
height="0"
codebase="/applet"
archive="se.lu.ldc.tiny.jar"
code="se.lu.ldc.tiny.applet.Tiny">
Some HTML text
</applet>
Have JS check that Java is installed before ever writing the applet element. E.G.
When you type..
alert(java.lang.System.getProperty("java.version"));
In the FF JS console input line, you might see something like:
[02:55:46.025] alert(java.lang.System.getProperty("java.version"));
[02:55:46.027] ReferenceError: java is not defined
..if Java is not installed. If it is not installed, use the alternate content/strategy.
If the call to getProperty(String) returns a non null value, then Java is installed (and java.version is a property defined in that JRE).

Prototype / Scriptaculous Javascript plugin for a file browser that integrates with JSP / Java?

I've been tasked with building a new Javascript file browser but unfortunately I have to use Prototype and can't use Jquery (at least not at the moment) due to some issues that may arise from conflicts (they have said they plan to resolve this but for the moment it looks like I may have to go with prototype). I've been searching on google for plugins that I can use for Prototype / Scriptaculous but they seem few and far between and all the ones I have found are geared towards use with PHP. I figure I may be able to rewrite the PHP end to Java / JSP as our application is built with Java. I just figured I would post here to see if anyone can recommend a good plugin for this that could easily be made to integrate with Java. Thanks
EDIT: This is what I mean:
http://abeautifulsite.net/blog/2008/03/jquery-file-tree/ (this is in Jquery) so I need something like this for Prototype
This is for browsing the file system of the server, not the client, so there would be a server-side page / controller that returns an HTML list, of sorts, of the files / folders and then the JavaScript manipulates this as needed to collapse / expand. There are a bunch of these written in Jquery but unfortunately I can't seem to find one written with Prototype
As pointed out by Diodeus, and as demonstrated by your own example, and as probably used by most file browser plugins available it works on HTML being rendered and returned by the server. All the javascript needs to do is insert the returned HTML, Prototype has a function which does most of that for you, Ajax.Updater. You could write your own very quickly.
function expandCollapseFolder(event, folder) {
var list = folder.down('ul');
if (list) list.toggle();
else new Ajax.Updater(folder, 'URL-OF-SERVER-PAGE',
{
parameters: { path: folder.readAttribute('data-path') },
insertion: 'bottom'
});
}
Event.on('ID-OF-FILE-BROWSER', 'click', 'li.folder', expandCollapseFolder);
The above is not tested code, it is meant to show how little is needed in total. The hard work is done by the server, it needs to scan and return folder contents with the appropriate file icons and URLs.
<ul>
<li class="folder" data-path="/folder">
<img src="folder-icon.png" />This is a folder
</li>
<li>
<a href="URL-OF-FILE" target="_blank">
<img src="file-icon.png" />This is a file
</a>
</li>
</ul>
I've been searching on google for plugins that I can use for Prototype
/ Scriptaculous but they seem few and far between and all the ones I
have found are geared towards use with PHP.
Based on your question I'm not sure exactly what you need to accomplish.
Prototype & Scriptaculous are add-on libraries for JavaScript, just as jQuery is. They have absolutely nothing to do with PHP, Java or any other server-side language because they are part of the client side: JavaScript.
If you're making one to browse files on the server, you're simply sending a HTML representations of the file listing to the browser. You would use Prototype to manipulate this HTML.
There are no Javascript-based client-side file browsers, regardless of whether you're using jQuery or Prototype because JavaScript cannot see the local filesystem on the client machine. This was deliberately designed this for security reasons.

How do I tell which web browser a Java applet is running under, from the applet? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
How to get browser type and version from within an applet?
I need to get the web browser version / vendor that an applet is running in. I can get the Java version and the OS from the System properties, but I don't see anything similar for the browser.
You need to use Javascript and modify param values.
Browser info can be fetched using navigator object
few of the methods
navigator.appName
navigator.appVersion
navigator.userAgent
and pass those values into applet tags dynamically,which are actual parameters of method in an applet.
a small but good example can be found here on integrating javascript and java applets.
http://www.ibiblio.org/java/course/week5/16.html
after which you can set values using following snippet.
<applet >
<PARAM id="browserAgent" name="browserAgent" value=""/>
</applet>
<script type="text/javascript">
document.getElementById("browserAgent").value=navigator.userAgent;
</script>

Categories

Resources