I know in scripting languages like Python that this is possible but I know that Java applets can't access other servers other than their own.
I don't know/think I can get this applet signed. Is there a way to use PHP to do what I want to accomplish?
I also know that this code will go to google.com
import java.applet.*;
import java.awt.*;
import java.net.*;
import java.awt.event.*;
public class tesURL extends Applet implements ActionListener{
public void init(){
String link_Text = "google";
Button b = new Button(link_Text);
b.addActionListener(this);
add(b);
}
public void actionPerformed(ActionEvent ae){
//get the button label
Button source = (Button)ae.getSource();
String link = "http://www."+source.getLabel()+".com";
try
{
AppletContext a = getAppletContext();
URL u = new URL(link);
// a.showDocument(u,"_blank");
// _blank to open page in new window
a.showDocument(u,"_self");
}
catch (MalformedURLException e){
System.out.println(e.getMessage());
}
}
}
That is assuming that source.getLabel() is "google"
But how would I get the source html of that page?
The source html is dynamic and is updated every few seconds or miliseconds. But, the html is also updated, so I can still read the dynamic content directly from the html. I already did this in vb.net, but now I need to port it to Java, but I can't figure out how to access a page's html source; that's why I'm asking.
AppletContext.showDocument opens a page in the browser, much like a hyperlink in HTML or a similar call in JavaScript would do. Under the Same Origin Policy you will not have access to this page if it is from a different site, even if the page is in an iframe.
Some sites may have a crossdomain.xml policy file that allows access if you were to read the contents of the java.net.URL directly. However, www.google.com appears to be using a restricted form that I don't believe is currently supported by the Java PlugIn.
Someone will probably suggest signing your applet, which turns off the "sandbox" security feature of Java. You would then need to persuade your users to trust your ability to publish safe signed code.
Related
I'm experimenting with Weebly, and I'm currently trying to add an arbitrary swing program to the Weebly editor. I have tried two approaches thus far, as shown here:
1: (Note: - replaces < and >)
-embed height=400 width=400 src="siteName/uploads/someNumbers/testapplet.class"--/embed-
2: (Same substitution as above)
-applet codebase="siteName/uploads/someNumbers" code="testapplet.ckass" width=400 height=400--/applet-
Upon publishing and viewing the page, the first one says I need a plugin to display the content, and the second one says my security preferences won't let me run java on the site, whereas I can run java pretty much everywhere else just fine.
What should I do to make this work? This could include some of the following:
Modifying my program (i.e. the java code itself)
Modifying how I upload the program (i.e. .class vs .jar)
Modifying how I display the program (i.e. the actual -applet- or -embed-)
For reference, here is the java code- just a basic JButton and JLabel, with the JLabel's value increasing upon each click of the button:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class TestApplet extends JApplet
{
static int x = 0;
static JLabel l = new JLabel(x+"");
public void init()
{
setLayout(new FlowLayout());
JButton b = new JButton("Button");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
x++;
l.setText(x+"");
}
});
add(b);
add(l);
}
}
Sign in to weebly and click on the edit button next to your site name
On the "Elements" tab on the top, go to "Multimedia" and drag a file element onto your page.
Follow directions to upload your .class file. Name should be lowercase.
Hit the publish button and go to your published page.
Remember your .class file? Right-click on it and copy the link address or link location.
Go back to editing your weebly page.
On the "Elements" tab, go down to "More" and drag in the "Custom HTML" element.
Click to edit the custom HTML element- this is where we are going to put our applet code.
If my link location to my .class file was http://www.johndoe.com/uploads/3/3/2/6/3326331/countme.class, my applet code would read:
<applet codebase="http://www.johndoe.com/uploads/3/3/2/6/3326331" code="countme.class" width=something height=something></applet>
The idea is that the codebase tells the browser where to look for a .class file and the code itself tells it whick .class it is.
10. Publish again, and your applet should appear.
I haven't tried it personally, but I had a chat with a support support staff and they affirmed this method.
All the best!
I have the following Java Applet, which makes a simple sound:
import java.applet.*;
import java.awt.Graphics;
import java.net.MalformedURLException;
import java.net.URL;
public class Sound extends Applet {
AudioClip soundFile1;
public void init() {
soundFile1 = getAudioClip(getDocumentBase(),"collectgarments_alreadyassigned.wav");
soundFile1.play();
}
}
I want to use this applet in an HTML page, which is inside a .net project. I want it to be deployed eg make its sound onClick, so am trying to create a JavaScript method to play the sound.
So far I have the following:
function Sound() {
var attributes = { id:'SoundApplet', code:'Sound.class', archive:'Java/Sound.jar', width:0, height:0} ;
var parameters = { permissions:'sandbox'} ;
deployJava.runApplet(attributes, parameters, '1.6');
}
This method makes the sound, but it also makes all the HTML disappear on the screen.
Possible reasons for this I can think of are that the Applet is trying to rewrite all the HTML on the page but is not being given any HTML to write?
If so a possible solution could be to include it in a div in a similar way to a div set to `display="none"', but I would not know how to do that as this is a sound not a visual aspect.
Maybe my thoughts are completely wrong and it is something else altogether.
I cannot find anything relevant on the internet and the internet explorer debugger is no help either.
Anyone else come across this problem??
I have found the answer myself. I do not know the reasons that this works, but it does:
function Sound()
{
var app = document.createElement('applet');
app.id= 'SoundApplet';
app.archive= 'Java/Sound.jar';
app.code= 'Sound.class';
app.width = '0';
app.height = '0';
document.getElementsByTagName('body')[0].appendChild(app);
}
I have encountered a small problem that I need some help on. The issue is that I wish to call a browser window which calls a html page. The html file opens in 3 different browsers so the code for that should be correct. The actual problem is that it brings up a page can't be displayed error message
Here is the code that gets the location
package org.error;
public class BrowserLocation {
private String test1 = "org\\error\\PatientNumberError.html";
public BrowserLocation() {
}
public String patientNumberAddress() {
return test1;
}
}
and here is the code that creates the browser component and calls the location of the html file.
Browser browser = new Browser(container, SWT.NONE);
browser.setForeground(SWTResourceManager.getColor(SWT.COLOR_DARK_BLUE));
browser.setBackground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
browser.setUrl(browserLocation.patientNumberAddress());
browser.setBounds(25, 25, 315, 180);
Would it be possible to find the error of my ways?
setUrl require a URL so you need something like:
browser.setUrl(new File(path).toURI().toURL().toString());
Sorry for not getting back to you earlier.
Someone that I know who is a senior Java programmer told me the problem that I was having was a case of absolute address versus relative address.
The reason for this is that if I was reading and writing to a file, then I would be able to use a relative address. However If I'm interacting with a server which is the case here as eventually It could go on-line (If I had the money) it would need to be an absolute address.
As I am still learning Java programming this was a very specific and important lesson to learn. I hope this would help anybody else who has had this issue.
I have designed an Applet to take a screenshot and save it on the users computer using the java.awt.Robot class. I need to embedd this applet into an html page (using the object tag) so that when the user clicks a button on the webpage the screenshot is taken.
The applet itself works fine, i've tested it by adding a temporary main method to it and running it on my local machine as a regular java app.
Where I'm having difficulty is setting up permissions to allow it to run from its embedded location. Obviously the robot class is somewhat hazardous so an AWTPermission needs to be established and the applet itself needs to be signed.
I followed through the tutorial at http://download.oracle.com/javase/tutorial/security/toolsign/index.html and succeeded in creating a signed .jar file and then a policy file that allowed the demo application in that tutorial to run. Where I am now running into issues is how to reconcile what I've learned with the situation my applet will be used in.
My target audience comprises around 100 machines and I need it to be executable on all of them. I have packed my java .class file into a .jar and signed it using keytool and jarsigner. I then uploaded the .jar and .cer files to the server directory where the pages in question are hosted.
However: When I then used policytool to create a new policy file on one of the machines to test the setup I am still unable to execute the applet from the HTML. I get Java.Security.AccessControlException Acess Denied java.awt.AWTPermission createRobot errors.
I rather suspect its the policy step that is going awry, so I'll outline the steps I took:
I download the certificate to the local machine and generate a keystore from it, I launch 'policytool' from this directory through the commandline
I add the directory on the local machine where the keystore generated from and my certificate is located.
I then hit the add policy button and enter the SignedBy alias
Then Add Permissions and select AWTPermission
Targets name I select createRobot
The function field I have been leaving blank as I cant think what would apply here
Signed By in this window is also left blank
I then hit 'OK' and 'Done' and get a warning that there is no public key for the alias I've entered in the first step. I do a 'save as' and save my policyfile to the same directory as I put the certificate and the keystore generated from it.
This is not allowing me to run the applet from the webpage however and my limited understanding of this aspect of programming offers no clues as to what has gone wrong.
Ideas, thoughts, observations? If I havent explicitly mentioned something then I havent done it. My biggest suspect is the warning I recieve but I cant seem to find why its appearing
EDIT: Forgot to mention a step. I manually added to my jre\lib\security\java.security file the line 'policy.url.3=file:/C:/Testing/debugpolicy' since thats the path and policy filename I created during the above steps. I also just now managed to remove the warning I mentioned earlier, I'd been mixing up my alias' and gave the alias for the private keystore rather than the public one during policyfile creation, however I still encounter the same problems
If an applet is correctly signed, no policy file is required, nor is it required to separately upload any certificate. A correctly signed applet will prompt the user for permission when the applet is visited, before it loads. Does the prompt appear?
Here is a small demo. I wrote that demonstrates Defensive loading of trusted applets. That is the security prompt I am referring to.
If the applet is both digitally signed by the developer and trusted by the end user, it should be able to take a screen-shot.
There is one other thing you might try if the applet is trusted, just as an experiment (1). Early in the applet init(), call System.setSecurityManager(null). That will both test if the applet has trust, and wipe away the last remnants of the 'trusted' security manager given to applets.
And in the case that works, and it makes the screen capture successful, it suggests either a bug or Oracle changed their mind about the defaults of what a trusted applet could do.
1) Don't do this in a real world or production environment. To quote Tom Hawtin:
This question appears to have given some the impression that calling System.setSecurityManager(null); is okay. ... In case anyone has any doubts, changing global state in an applet will affect all applets in the same process. Clearing the security manager will allow any unsigned applet to do what it likes. Please don't sign code that plays with global state with a certificate you expect anyone to trust.
Edit 1:
Here is the source of the simple applet used in that demo. For some reason when I originally uploaded it, I decided the source was not relevant. OTOH 3 people have now asked to see the source, for one reason or another. When I get a round tuit I'll upload the source to my site. In the mean time, I'll put it here.
package org.pscode.eg.docload;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.io.*;
import java.security.*;
/** An applet to display documents that are JEditorPane compatible. */
public class DocumentLoader extends JApplet {
JEditorPane document;
#Override
public void init() {
System.out.println("init()");
JPanel main = new JPanel();
main.setLayout( new BorderLayout() );
getContentPane().add(main);
try {
// It might seem odd that a sandboxed applet can /instantiate/
// a File object, but until it goes to do anything with it, the
// JVM considers it 'OK'. Until we go to do anything with a
// 'File' object, it is really just a filename.
File f = new File(".");
// set up the green 'sandboxed page', as a precaution..
URL sandboxed = new URL(getDocumentBase(), "sandbox.html");
document = new JEditorPane(sandboxed);
main.add( new JScrollPane(document), BorderLayout.CENTER );
// Everything above here is possible for a sandboxed applet
// *test* if this applet is sandboxed
final JFileChooser jfc =
new JFileChooser(f); // invokes security check
jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
jfc.setMultiSelectionEnabled(false);
JButton button = new JButton("Load Document");
button.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent ae) {
int result = jfc.showOpenDialog(
DocumentLoader.this);
if ( result==JFileChooser.APPROVE_OPTION ) {
File temp = jfc.getSelectedFile();
try {
URL page = temp.toURI().toURL();
document.setPage( page );
} catch(Exception e) {
e.printStackTrace();
}
}
}
} );
main.add( button, BorderLayout.SOUTH );
// the applet is trusted, change to the red 'welcome page'
URL trusted = new URL(getDocumentBase(), "trusted.html");
document.setPage(trusted);
} catch (MalformedURLException murle) {
murle.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (AccessControlException ace) {
ace.printStackTrace();
}
}
#Override
public void start() {
System.out.println("start()");
}
#Override
public void stop() {
System.out.println("stop()");
}
#Override
public void destroy() {
System.out.println("destroy()");
}
}
I have been working with a Java applet which is an applet that helps to write using only a mouse. For my case, I am trying to incorporate this into my webiste project as follows:
When the user clicks on any input element (textbox/textarea) on the page, this JAVA applet loads on the webpage itself. In the screenshot of the JAVA applet seen below, the user points to an alphabet to and the corresponding text gets written in the text box of the applet.
Now what I am trying to do is to get this text from the TextBox of the applet to the input element on the webpage. I know that this needs an interaction between the Java and JavaScript, but not being a pro, I really do not have the catch. Here's the Java applet and the code I have written.
Java applet and jQuery code (298kB): http://bit.ly/jItN9m
Please could somebdoy help for extending this code.
Thanks a lot!
Update
I searched somewhere and found this -> To get the text inside of Java text box, a getter method in the Applet to retrieve the text:
public class MyApplet extends JApplet {
// ...
public String getTextBoxText() { return myTextBox.getText(); }
}
In the JQuery code, the following lines are to be added I think:
var textBoxText = $("#applet-id")[0].getTextBoxText();
//Now do something with the text
For the code of the applet, I saw a GNOME git page here. The getText call already exists -- look at the bottom of this file: http://git.gnome.org/browse/dasher/tree/java/dasher/applet/JDasherApplet.java
I'd need to call 'getCurrentEditBoxText' but when should this method 'getCurrentEditBoxText' be called?
In my case, I would probably have to do it when the user clicks in a new input control etc.
You can have full communication between your Applet and any javascript method on the page. Kyle has a good post demonstrating how the Javascript can call the applet and request the text value. However, I presume you want the HTML Textfield to update with each mouse click, meaning the applet needs to communicate with the page. I would modify your javascript to something like this:
var activeTextArea = null;
$('textarea, input').click(function() {
$(this).dasher();
activeTextArea = this;
});
function updateText(text) {
// Careful: I think textarea and input have different
// methods for setting the value. Check the
// jQuery documentation
$(activeTextArea).val(text);
}
Assuming you have the source for the applet, you can have it communicate with the above javascript function. Add this import:
import netscape.javascript.JSObject;
And then, in whatever onClick handler you have for the mouse clicks, add:
// After the Applet Text has been updated
JSObject win = null;
try {
win = (JSObject) JSObject.getWindow(Applet.this);
win.call("updateText", new Object[] { textBox.getText() });
} catch (Exception ex) {
// oops
}
That will update the text each time that chunk of code is called. If you do NOT have access to the applet source, things get trickier. You'd need to set some manner of javascript timeout that constantly reads the value from the applet, but this assumes the applet has such a method that returns the value of the textbox.
See Also: http://java.sun.com/products/plugin/1.3/docs/jsobject.html
Update Modifying the applet is your best shot since that is where any event would be triggered. For example, if you want the HTML TextField to change on every click, the click happens in the applet which would need to be modified to trigger the update, as described above. Without modifying the applet, I see two options. Option #1 uses a timer:
var timer;
var activeTextArea;
$('textarea, input').click(function() {
$(this).dasher();
activeTextArea = this;
updateText();
}
function updateText() {
// Same warnings about textarea vs. input
$(activeTextArea).val($('#appletId')[0].getCurrentEditBoxText());
timer = setTimeout("updateText()", 50);
}
function stopUpdating() {
clearTimeout(timer);
}
This is similar to the code above except clicking on a text area triggers the looping function updateText() which will set the value of the HTML text field to the value of the Applet text field every 50ms. This will potentially introduce a minor delay between click and update, but it'll be small. You can increase the timer frequency, but that will add a performance drain. I don't see where you've 'hidden' the applet, but that same function should call stopUpdating so that we are no longer trying to contact a hidden applet.
Option #2 (not coded)
I would be to try and capture the click in the Applet as it bubbles through the HTML Dom. Then, you could skip the timer and put a click() behavior on the Applet container to do the same update. I'm not sure if such events bubble, though, so not sure if this would work. Even if it did, I'm not sure how compatible it would be across browsers.
Option #3
Third option is to not update the HTML text field on every click. This would simply be a combination of Kyle's and my posts above to set the value of the text field whenever you 'finish' with the applet.
Here's a possible solution. To get the text inside of your Java text box, write a getter method in the Applet to retrieve the text:
public class MyApplet extends JApplet {
// ...
public String getTextBoxText() { return myTextBox.getText(); }
}
In your JQuery code, add the following lines:
var textBoxText = $("#applet-id")[0].getTextBoxText();
//Now do something with the text
I found most of what I posted above here. Hope this helps.
This page explains how to manipulate DOM from a Java applet. To find the input element, simply call the document.getElementById(id) function with id of an id attribute of the text input box.