Java Applet removing all content from HTML page - java

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

Related

Creating an "allowed-users" list in Next.Js while implementing Google Auth

I am fairly new to Next and React, and I really don't know a whole lot about backend anything except very basic knowledge for how models and using the data works.
Ok, so far the method I have used is working. However, I went to the client side and the login.js file obviously showed the JSON file items in the allowed-users.json because I imported it and checked the array for the allowed users. The logic works and only the emails on the list can login with Google Auth.
This is not a major issue because the app idea I am coming up with is not supposed to be a site pushed to production with a lot of publicity, but I still would like to know something I could do to make this secure to learn.
I am open to any suggestions, or any correction on anything I am doing that is not good practice. I am here to learn. What I did in this code is just a test to get it to work, and the whole project is just to test out using the NextAuth with Google to give users permissions on the site to implement an Admin, Employee, Client system for the accounts.
My Code:
import React from "react";
import { useSession, signIn, signOut } from "next-auth/react";
import GoogleButton from "react-google-button";
import { useRouter } from "next/router";
import allowedUsers from "./api/allowed-users.json";
const Login = () => {
const { data: session } = useSession();
const router = useRouter();
console.log(session);
if (!session) {
return (
<div className="flex justify-center items-center content-center h-full">
<div>
<GoogleButton onClick={() => signIn()} />
</div>
</div>
);
}
if (session && allowedUsers.includes(session.user.email) ) {
router.push("/account");
} else {
const exitLogin = () => signOut();
exitLogin();
}
};
export default Login;
I have tried reading Next documentation on handling JSON and also API calls, but like I said, I am fairly new to this. I come from old school HTML / CSS / with simple JavaScript for simple sites. I am trying to broaden my knowledge to learn how to develop apps and sites that are viable nowadays.
If anyone has good documentation I should read please link it, or if you know a tutorial somewhere I can read through or watch that covers a topic similar to this.
Thanks!
Knight

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.

How am I supposed to draw an image from my Java Applet?

I am not sure how to fully express this but, I have probably gone through 10 pages of Google links on this topic and not one of them has helped me solve my issue.
I thought it would be simple enough, I was just trying to add an image to the paint function of my java applet, like any other shape, but this has turned out to be a nightmare for me.
The problem is that every time I try to run the drawImage function it keeps saying Access Denied ("java.io.FilePermission" "Image.jpg" "read"). Yet, none of the tutorials mention this at all, all they ever say is that I should do the following:
import java.applet.*;
import java.awt.*;
Image img;
//These would go in the paint function
img=getImage(getDocumentBase(),"/Image.jpg"); //I have tried without the slash too
g.drawImage(img,20,20,this);
This is all they do and it works for them, but it just won't work for me. Other methods are far too complex for the sake of just adding an image, and even when I go through the toil of doing those it keeps giving me the "Access Denied" message. There's also the method of "signing" it, but I really don't think that's going to help given all that I have tried, so I am afraid it might just be another wasted endeavor. None of the tutorials even tell you to have your applet signed.
I have the image in the "build" (also called bin) folder together with the classes.
The program seemed to run when I included the entire file path, but even then the image did not display. That is not to mention I can't really include the complete path from my own computer because then it wouldn't work when I actually send it to another person.
Please, I just want to know why it doesn't work for me yet seems to work perfectly for others. That, and if there's a way around this.
This is an example of what I am doing:
import java.applet.*;
import java.awt.*;
public class JavaProject extends JApplet
{
Image img;
public void init()
{
img=getImage(getDocumentBase(),"/Image.jpg");
}
public void paint(Graphics g)
{
super.paint(g);
g.drawImage(img,20,20,this);
}
}
This is my HTML file:
<html>
<head>
<title> My First Web Page </title>
</head>
<body>
<applet code="JavaProject.class" width="400" height="500">
</applet>
</body>
</html>
According JApplet java docs method getImage(URL url, String name) should have two parameter: URL-link to picture and String name.
Is method getDocumentBase() returnig an URL-link?
You must start by understanding that an Applet, unless signed, may not read from the file system. It must use either classpath resources or things fetched from the same place it was fetched from. You have to decide which of these applies to you. If the image is a fixed image, you can put it in your classpath as a resource, and use Class.getResourceAsStream. If it's a different image every time, you'll have to use HTTP.
Try this one if the image in the "build" (also called bin) folder together with the classes.
import java.awt.Graphics;
import java.awt.Image;
import java.net.URL;
import javax.swing.JApplet;
public class JavaProject extends JApplet {
Image img;
public void init() {
img = getImage(getDocumentBase(), "images/222.png");
// Please ensure that 222.png is placed under bin/images folder directly
}
#Override
public void paint(Graphics g) {
update(g);
}
#Override
public void update(Graphics g) {
g.drawImage(img, 20, 20, this);
}
}
Try with HTTP URL first
URL myURL = new URL("https://www.gravatar.com/avatar/a94613cea642e6e9e2105867bc2e103e?s=32&d=identicon&r=PG&f=1");
img = getImage(myURL);
If you are using Eclipse under Windows then have a look at below screenshot:
Please have a look at below post to get some understanding about it.
java.io.FilePermission exception - Read from jar file?

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.

jQuery and Java applets

I'm working on a project where we're using a Java applet for part of the UI (a map, specifically), but building the rest of the UI around the applet in HTML/JavaScript, communicating with the applet through LiveConnect/NPAPI. A little bizarre, I know, but let's presume that setup is not under discussion. I started out planning on using jQuery as my JavaScript framework, but I've run into two issues.
Issue the first:
Selecting the applet doesn't provide access to the applet's methods.
Java:
public class MyApplet extends JApplet {
// ...
public String foo() { return "foo!"; }
}
JavaScript:
var applet = $("#applet-id");
alert(applet.foo());
Running the above JavaScript results in
$("#applet-id").foo is not a function
This is in contrast to Prototype, where the analogous code does work:
var applet = $("applet-id");
alert(applet.foo());
So...where'd the applet methods go?
Issue the second:
There's a known problem with jQuery and applets in Firefox 2: http://www.pengoworks.com/workshop/jquery/bug_applet/jquery_applet_bug.htm
It's a long shot, but does anybody know of a workaround? I suspect this problem isn't fixable, which will mean switching to Prototype.
Thanks for the help!
For the first issue, how about trying
alert( $("#applet-id")[0].foo() );
For the second issue here is a thread with a possible workaround.
Quoting the workaround
// Prevent memory leaks in IE
// And prevent errors on refresh with events like mouseover in other browsers
// Window isn't included so as not to unbind existing unload events
jQuery(window).bind("unload",
function() {
jQuery("*").add(document).unbind();
});
change that code to:
// Window isn't included so as not to unbind existing unload events
jQuery(window).bind("unload",
function() {
jQuery("*:not('applet, object')").add(document).unbind();
});

Categories