How do I add a java program to a weebly site? - java

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!

Related

Moxieapps file uploader for GWT adding multiple upload buttons

The GWT web app I'm building has a page where users can upload CSV files. The upload code uses the Moxieapps GWT Uploader, which mostly works great.
However, I've discovered a strange scenario, where navigating away from the page and back to it adds the upload button again. So the third time I visit the page, the upload section will look like this:
And the relevant part of the generated HTML viewed in an inspector shows that both the input and the div containing the "button" get added over and over (though there is only ever one dropzone):
I've gone over my code many times to see whether I was doing something that could be causing this, but haven't found anything. You don't actually manually add the button or the input; this is done automatically by the framework. The fileUploader gets initialised only once (this being GWT client code, I've debugged using the inspector as well as logging statements to the console to confirm this):
fileUploader.setButtonDisabled(true).setFileTypes("*.csv")
.setUploadURL(getBaseUrl() + "/fileUpload.upload")
.setButtonText("<span class=\"buttonText\">Select CSV file to upload</span>")
.setFileSizeLimit(FILE_SIZE_LIMIT)
.setButtonCursor(CustomUploader.Cursor.HAND)
.setButtonAction(CustomUploader.ButtonAction.SELECT_FILE)
.setUploadProgressHandler(new UploadProgressHandler() {...})
.setUploadSuccessHandler(...)
// etc. with other handlers
The method setButtonText() is called from a couple of other places, and the text changes as it should, but only on the last button (if there are several). Otherwise, there's nothing in my code that could possibly be adding the button as far as I can tell.
Has anyone else encountered this issue? Is there some property I need to set to prevent this? Could it be a bug in the moxieapps code?
After writing out my question, and adding "Could it be a bug in the moxieapps code?" at the end, I followed up on that suspicion, and it turns out that it is indeed a bug in the org.moxieapps.gwt.uploader.client.Uploader class.
The input and the "select file" button are added in the onLoad() method of that class without a check whether they may have been added already.
It looks like there hasn't been any active development on this framework for some time, so I thought it was time for a custom override version. I've tested this and it works:
package yourpackagename.client.override;
import java.util.Iterator;
import org.moxieapps.gwt.uploader.client.Uploader;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.WidgetCollection;
/**
* The sole reason this class exists is to fix a bug in the moxieapps uploader
* (org.moxieapps.gwt.uploader-1.1.0.jar) where it adds a new upload input and
* button each time its <code>onLoad()</code> method is called, i.e. every time
* you navigate away from the page and then back to it.
*/
public class CustomUploader extends Uploader {
#Override
protected void onLoad() {
boolean hasFileUploadAlready = false;
WidgetCollection children = getChildren();
for (Iterator<Widget> iterator = children.iterator(); iterator.hasNext();) {
Widget eachWidget = iterator.next();
if (eachWidget instanceof FileUpload) {
hasFileUploadAlready = true;
}
}
// Only call the super method if there isn't already a file upload input and button
if (!hasFileUploadAlready) {
super.onLoad();
}
}
}
Instead of referencing the org.moxieapps.gwt.uploader.client.Uploader, I've changed the references to point to my custom uploader class, which will now check for an existing FileUpload child widget, and simply skip the original onLoad() code if it finds such a widget.
Might be a bit of a crowbar approach, but it works (and in my case, changing the maven-managed JAR file is not very practical). Hopefully, this will be useful to anyone else coming across this problem.

Get page's html source using a Java applet

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.

Signed Java applet permission [duplicate]

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

JApplet fails to run in HTML page

I have created a JApplet using the JUNG library in Netbeans that compiles and runs normally. However, when I try to create an html file that runs the applet, only a grey pane appears but the components are missing.
My class is :
public class View extends JApplet {
//Here I declare the buttons etc..
public View()
{
initializeComponent();
fetchGraphs();
}
public static void main(String[] args) throws IOException{
f = new JFrame();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
x = screenSize.width;
y = screenSize.height;
f.getContentPane().add(new View());
f.setTitle("Social Network Privacy Settings and Access Control");
f.setLocation(new Point(15, 20));
f.setSize(new Dimension(x-20,y-50));
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.setResizable(false);
f.setVisible(true);
}
}
The method initializeComponent() adds all the components to the main window. I used JFrameBuilder to build some basic components. JFrameBuilder uses a method addComponent(container, component, x, y, width, height) to add components
I use the code below for that:
contentPane = (JPanel)this.getContentPane();
//to create the japplet contentpane
addComponent(contentPane, genGraphButton, (int)(0.35*x),(int)(0.63*y),
(int)(0.2*x),28);
// to add components
Then I create an html file:
<applet code = 'MyPackage.View'
archive = 'MyProject.jar',
width = 1600,
height = 800/>
in the /dist folder but then only a grey pane appears when I try to open it with Mozilla Firefox. The strange thing is that I have created another simple applet, this time with netbeans JBuilder and it runs normally in a web page.
I really need some help!
You mention the JUNG library, it relies on the two third party libraries, Collections-Generic & Cern Colt Scientific Library 1.2.0. As mentioned by #othman they need to be added to the run-time class-path of the applet (added to the archive attribute of the applet element).
But just so we are clear, make sure the HTML contains more than just the applet element. Something like this:
<html>
<body>
<applet
code='MyPackage.View'
archive='MyProject.jar,jung.jar,collections.jar,colt-scientific.jar'
alt='Java is DISABLED in this browser!'
width='1600'
height='800'>
This browser does not recognize the applet element!
</applet>
</body>
</html>
Of course, you'll need to change the names of the last 3 Jars to their real names.
I'm no Applet expert, since I don't use them, but IIRC you need the init() method to initialize your view. main(...) is not called for an applet.
First, I am not sure that new lines you added into the html are legal. I mean write <applet and /> without any new lines and spaces.
Second, test that your jar is really available. To do this go to the same URL that you go to retrieve your HTML without HTML but with jar, i.e.
if your HTML URL is: http://somehost/my.html type in browser http://somehost/MyProject.jar and see that you can download the jar.
if this works check the code attribute. Is your package name really MyPackage? Capitalized? Do you know it is not according the naming convention?
Also check java console. Find it somewhere in menus of your browser: it depends in browser. I believe that you will see the reason there in form of exception stack trace.
you need to reference also the JUG jars in your applet tag :
<
applet code = 'MyPackage.View'
archive = 'MyProject.jar , jung_xx.jar',
width = 1600,
height = 800 /
>
in the archive attribute add all jung jars that you have currently in your netbeans project classpath.

Bridge between the Java applet and the text input controls on the web page

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.

Categories