I'm trying to write sample file from applet but is not working. Below is the code.
Applet
public class PasteImageApplet extends JApplet {
Clipboard clipboard;
Toolkit toolkit;
JLabel lbl;
public String getClipboardImageURL(String server) {
lbl.setText("pasting image");
String url = "";
try {
DataFlavor dataFlavor = DataFlavor.imageFlavor;
System.out.println(dataFlavor.getDefaultRepresentationClass());
Object object = null;
try {
object = clipboard.getContents(null)
.getTransferData(dataFlavor);
JOptionPane.showMessageDialog(null,"Image found.");
try
{
Writer output = null;
String text = "Test Write File";
File file = new File("write.txt");
output = new BufferedWriter(new FileWriter(file));
output.write(text);
output.close();
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null,"Error writing file"+ex);
return "" ;
}
//return "";
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "No image found.");
return "";
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error."+e);
return "";
}
return url;
}
public void init() {
lbl = new JLabel("");
lbl.setText("applet started");
add(lbl);
toolkit = Toolkit.getDefaultToolkit();
clipboard = toolkit.getSystemClipboard();
}
}
HTML
<html>
<head>
<title>Clipboard image demo</title>
<script type="text/javascript">
function loadApplet() {
// Deferred load to display text first
document.getElementById("applet").innerHTML = '<object id="paste-image" classid="java:PasteImageApplet.class" type="application/x-java-applet" archive="tst.jar" width="1" height="1"></object>';
}
function getImage() {
obj = document.getElementById('paste-image');
postTo = "http://localhost/PasteImageApplet/PasteImageApplet/Web/shoot.php"; // Change this to your URL
image = obj.getClipboardImageURL(postTo);
if (image) {
url = "shots/" + image;
document.getElementById("target").src = url;
document.getElementById("url").value = document.getElementById("target").src; // to get full path, hack, I know ;)
document.getElementById("container").style.display = "";
}
}
</script>
<body onload="loadApplet();">
<p>
Copy some image data to your clipboard, accept the applet (it only accesses the clipboard) and click the button :-)
See a blog post about this demo
</p>
<p>
<div id="applet"></div>
<input type="button" value="Paste it!" onclick="getImage();">
</p>
<div id="container" style="display: none;">
<input type="text" id="url" style="width: 700px;"><br />
<iframe id="target" width="700" height="400"></iframe>
</div>
</body>
</html>
I didn't get any error as well. Please advice.
That's because applets live there own sandbox, where they require special permission to perform certain operations, like read or write the disk of a client machine. Remember, applets execute within the context of the client machine, they are guests and need to follow the house rules
Check out What Applets can and cannot do for more details
An applet cannot establish a File on the server. That is not how servers work. If a server accepts uploads, it must provide specific functionality to enable that and the applet must use that functionality.
As long as the functionality to accept an upload is on the same server, the applet can remain sand-boxed.
you can see the console for applets via the (windows) taskbar, you right click the java icon(when applet is running it should appear on the lower right) and right click > open console, you can debug there, this is where the stack trace of an applet goes.
Related
Hello programmers around the world, I am currently working on my own browser game and I ran into a problem when trying to register an account and store the details into a database. I am currently using PHP in order to do it. When I enter the registration details username, email, password ...etc. and hit the register button nothing happens. The result should be that the values should be stored in a database and you should be redirected to another page.
Note I am using my own server which I made in Java the code is below:
package server.java;
import java.net.ServerSocket;
import java.net.Socket;
public class Main {
ServerSocket serversocket;
//entry point for our program
public static void main(String[] args) throws Exception {
new Main().runServer(); // to avoid any problems with static fields
}
public void runServer() throws Exception{
System.out.println("Server is started!");
serversocket = new ServerSocket(4567); //port number at which the server is running
//for accepting requests
acceptRequest();
}
private void acceptRequest() throws Exception{
while(true){ // we have to accept all the requests
//connection to the client is in the form of socket which contains the stream for input and output
Socket s = serversocket.accept();
ConnectionHandler ch = new ConnectionHandler(s);
//ch is the thread, so we have to strt the thread
ch.start();// this line of code will call the run() method automatically
}
}
}
package server.java;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
//this class basically handles all the connections which contain the requests
public class ConnectionHandler extends Thread{ //by extending to Thread, this class becoomes a Thread
Socket s;
//for sending the output to the client
PrintWriter pw;
//for getting the input from the client
BufferedReader br;
//constructor which accepts and uses a Socket
public ConnectionHandler(Socket s) throws Exception{
this.s = s;
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
pw = new PrintWriter(s.getOutputStream());
}
/*
*Thread class contains a method run() which is called automatically when we start the thread
*in this method we have to read the request and give the responce
*/
public void run(){
try{
//here we get the request string and give this string to the HttpRequest class
String requestString = "";
//from br we have to read our request
//read until request is not of length 0 or br is ready
while(br.ready() || requestString.length() == 0){
requestString += (char) br.read();
}
System.out.println(requestString);// for testing purposes
HttpRequest request = new HttpRequest(requestString);
//now we pass the HttpRequest object to HttpResponce in order to get the responce
HttpResponce responce = new HttpResponce(request);
//write the final output to pw
pw.write(responce.responce.toCharArray());
pw.close();
br.close();
s.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
package server.java;
public class HttpRequest {
//first line contains 3 parts, 1 - request type, 2 - file name, 3 - http version
//for us only the file name is important
String filename;
//we have to create a constructor which accepts a string as input
public HttpRequest(String request){
//now we have the request from which only the fisrt line matters to us
String lines[] = request.split("\n");// now we have all the lines of the request separated
//this line basically splits the first line, and then selcets the second item which is our filename
filename = lines[0].split(" ")[1];
}
}
package server.java;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class HttpResponce {
HttpRequest request;
//this is the final responce which is generated
String responce;
//root path of the server
String root = "E:/root";
//we have to create a constructor which accepts a request as input
public HttpResponce(HttpRequest request) throws Exception{
this.request = request;
//now we have to open the file mentioned in request
File f = new File(root + this.request.filename);
try{
responce = "HTTP/1.1 200 \r\n"; //version of http and 200 for status code
//200 means everything is okay
responce += "Server: Our Java Server/1.0 \r\n"; //identity of the server
responce += "Content-Type: text/html \r\n"; //responce is in html format
responce += "Connection: close \r\n";//this line tells the browser to close the connection because no transmitions
responce += "Content-Length: " + f.length() + " \r\n"; //lngth of the responce file
responce += "\r\n"; //after blank line we have to append file data
//to read this file
FileInputStream fis = new FileInputStream(f);
int s;
while((s = fis.read()) != -1){ //-1 means end of file
responce += (char) s;
}
fis.close();
}catch(FileNotFoundException e){
//if we dont get a file then error 404
responce = responce.replace("200", "404");
}
catch(Exception e){
//if other error then 500 internal server error
responce = responce.replace("200", "500");
}
}
}
This is the entire code for my Java server.
Note: I think the server is working fine because it load and transitions between HTML pages. When it comes to PHP pages though it doesn't do anything so maybe it is the problem. I've been trying to solve this problem for two weeks now with no success so far? If somebody would be so kind as to help it would be really appreciated. Sending the code for the PHP page now:
<?php
session_start();
//connect to the database
$db = mysqli_connect("localhost", "root", "Smd497_497", "users");
if(isset($_POST['register'])){
$username = mysql_real_escape_string($_POST['username']);
$email = mysql_real_escape_string($_POST['email']);
$password = mysql_real_escape_string($_POST['password']);
$password2 = mysql_real_escape_string($_POST['password2']);
if($password == $password2){
//create user
$password = md5($password); //hash password before storing it for security purposes
$sql = "INSERT INTO users(username, email, password) VALUES('$username', '$email', '$password')";
mysqli_query($db, $sql);
$_SESSION['message'] = "Registration successful!";
header('Location: choice.php'); //redirect to the next page
else{
//failed to create user
$_SESSION['message'] = "The passwords DO NOT match!";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Registration page</title>
<style type="text/css">
body{
background-position: top;
background-repeat: no-repeat;
background-size: cover;
}
.starwars{
margin-left: 525px;
}
.blyat{
position: relative;
text-align; center;
margin-left: 325px;
}
.registration{
position: absolute;
top: 80px;
left: 22%;
font-size: 30px;
border-bottom: 1px solid black;
padding-bottom: 5px;
}
.details{
position: absolute;
top: 130px;
left: 14%;
}
form {
margin-left: 100px;
}
</style>
</head>
<body background = "https://pre00.deviantart.net/c83b/th/pre/i/2013/067/0/1/star_wars_sith_or_jedi_by_misterrecord-d5xdgdq.png">
<div class = "starwars">
<img src = "https://novaopenstore.com/Image/EventContainerImage/30" height = "100" width = "300" />
</div>
<div class = "blyat">
<img src = "https://scontent-lht6-1.xx.fbcdn.net/v/t1.0-9/30629292_1627559157293346_4622477325102925006_n.jpg?_nc_cat=0&oh=82718a4b31b952272b36d8a374a0ae14&oe=5B712921" height = "425" width = "700"/>
<div class = "registration"><b>Registration Details</b></div>
<div class = "details">
<form class="form" action="register.php" method="post">
<div class="alert-error"><?= $_SESSION['message'] ?></div>
Choose you battlefield!<br>
Battlefield: <select>
<option value="Battlefield 1">Battlefield 1</option>
</select><br>
Choose your name!<br>
Username: <input type="text" name="username" required /><br>
Choose your email!<br>
Email: <input type="text" name = "email" required /><br>
Choose your password!<br>
Password: <input type="password" name="password" required/><br>
Confirm your password!<br>
Confirm Password: <input type="password" name="password2" required/><br>
<input type="submit" value="Register" name="register" class="btn btn-block btn-primary"/>
</form>
</div>
</div>
</body>
</html>
Note: I am currently not having any problems with HTML or CSS (at least not any I know of...) Another useful thing to say is that some of you might think that my server is not working or that it is not receiving the information. Last time I tried I got the following result:
**username=zexstoi&email=ss%40mail.bg&password=147852369&password2=147852369®ister=Register
**
This is evidence that the server is receiveing the right info just not processing it right for some reason could be the server or the PHP page.As said above if anybody has any idea for a fix please share it with me and the rest of the community. Have a nice day everybody!
The HTML file is opened via double click. The player screen is black, and if I click play button, it jumps straight to the end. However, if I drag video player's handle around, I can see some shots from the video on screen.
This is the HTML file:
<!DOCTYPE html>
<html>
<body>
<video width="400" controls="controls">
<source src="video.mp4" type="video/mp4">
Your browser does not support HTML5 video.
</video>
</body>
</html>
And this is video generation Java code :
private LinkedList<BufferedImage> buffer;
...
public void saveVideo (File f) throws IOException {
if (converting) return;
System.out.println("Attempting to save video");
synchronized (lock) {
System.out.println("Starting the conversation");
converting = true;
SequenceEncoder enc = new SequenceEncoder(f);
while(!buffer.isEmpty()) {
BufferedImage image = buffer.getFirst();
buffer.removeFirst();
enc.encodeImage(image);
}
enc.finish();
System.out.println("Finished the conversation");
converting = false;
}
}
I play NanoHTTPD and WebServer based on it. To update any object in my code (application) I can use GET/POST method. But how can I create dynamic pages? For example I have html page on disc and it should present current temperature:
<html>
<head>
<title>My page</title>
</head>
<body>
<p style="text-align: center">Temperature: [temperature variable] </p>
</body>
</html>
How can I pass "variable temperature" from my application based on NanoHTTPD to html file and present it in browser?
You have to read the template from your disk, and replace the [temperature variable] substring with the value you want to include.
To read the file, you can use the Files class:
byte[] data = Files.readAllBytes(Paths.get("mytemplpate.html"));
String templ = new String(data, StandardCharsets.UTF_8);
To insert your temperature:
double temperature = 22.3;
String html = templ.replace("[temperature variable]", Double.toString(temperature));
And finally to send this as the response with NanoHTTPD:
return new NanoHTTPD.Response(html);
The complete program:
Foreword: Exceptions are not handled, this is just for demonstration purposes.
public class TemperatureServer extends NanoHTTPD {
// Loaded and cached html template
private static String templ;
// Value of this variable will be included and sent in the response
private static double temperature;
public TemperatureServer () {
super(8080);
}
#Override
public Response serve(IHTTPSession session) {
String html = templ.replace("[temperature variable]",
Double.toString(temperature));
return new NanoHTTPD.Response(html);
}
public static void main(String[] args) throws Exception {
byte[] data = Files.readAllBytes(Paths.get("mytemplpate.html"));
templ = new String(data, StandardCharsets.UTF_8);
ServerRunner.run(TemperatureServer.class);
}
}
For more advanced examples check out the Samples package of the NanoHttpd Github site.
I am creating a web application in which recording is done through applet. When i run my program on applet viewer using eclipse , it records my voice and saves it into my computer but when i run the same using html file on browser it opens up the applet but doesn't record my voice.
Even i have signed my project jar file but this didn't make any difference. It always throw an exception like this java.security.AccessControlException: access denied (javax.sound.sampled.AudioPermission record).
Here is sample code :
public class AudioRecorder extends JApplet {
private static final long serialVersionUID = 1L;
AudioFormat audioFormat;
TargetDataLine targetDataLine;
final JButton captureBtn = new JButton("Capture");
final JButton stopBtn = new JButton("Stop");
final JPanel btnPanel = new JPanel();
AudioFileFormat.Type[] fileTypes;
#Override
public void init() {
// TODO Auto-generated method stub
super.init();
new AudioRecorder();
}
public AudioRecorder() {
captureBtn.setEnabled(true);
stopBtn.setEnabled(false);
captureBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
captureBtn.setEnabled(false);
stopBtn.setEnabled(true);
captureAudio();
}
}
);
stopBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
captureBtn.setEnabled(true);
stopBtn.setEnabled(false);
stopAudio();
}
}
);
getContentPane().add(captureBtn);
getContentPane().add(stopBtn);
getContentPane().setLayout(new FlowLayout());
setSize(300, 120);
setVisible(true);
}
private void captureAudio() {
try {
audioFormat = getAudioFormat();
DataLine.Info dataLineInfo = new DataLine.Info(
TargetDataLine.class, audioFormat);
targetDataLine = (TargetDataLine) AudioSystem.getLine(dataLineInfo);
new CaptureThread().start();
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
}
private void stopAudio() {
targetDataLine.stop();
targetDataLine.close();
}
private AudioFormat getAudioFormat() {
float sampleRate = 8000.0F;
// 8000,11025,16000,22050,44100
int sampleSizeInBits = 16;
// 8,16
int channels = 1;
// 1,2
boolean signed = true;
// true,false
boolean bigEndian = false;
// true,false
return new AudioFormat(sampleRate, sampleSizeInBits, channels, signed,
bigEndian);
}
class CaptureThread extends Thread {
public void run() {
AudioFileFormat.Type fileType = AudioFileFormat.Type.WAVE;
File audioFile = new File("audio." + fileType.getExtension());
try {
targetDataLine.open(audioFormat);
targetDataLine.start();
AudioSystem.write(new AudioInputStream(targetDataLine),
fileType, audioFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Here is HTML Page source code :
<HTML>
<HEAD>
</HEAD>
<BODY>
<div>
<APPLET CODE="AudioRecorder.class" WIDTH="800" HEIGHT="500">
<param name="permissions" value="sandbox">
</APPLET>
</div>
</BODY>
</HTML>
Please help me out where the actual problem is. Thanks in advance.
Thanks guys, i got some ideas from here and have resolved the issue today evening and now it's working perfectly.
I : I mentioned recorded sound path to save it to D drive of My Computer [ Note : This is hard-coded location just for testing purpose].
II : I have gone through the procedure to sign my project and granted required permissions using java docs http://docs.oracle.com/javase/tutorial/security/toolsign/ [This procedure is most important to fix this AudioPermission issue].
III : To create a separate policy file specially for my project using Policy Tool and keystore alias, i added FilePermission for all files and for all operations i.e. read,write,execute,delete . Once again, i added javax.sound.sampled.AudioPermission record, both have been added with signedBy my project's keystore alias name. [For more details go through last few steps provided in the link given above]
IV : I created a new HTML file, removed sandbox permission parameter tag from html file and included ARCHIVE="signedjar.jar" as an attribute in APPLET tag. So, the new HTML file code is -
<HTML>
<HEAD>
</HEAD>
<BODY>
<div>
<APPLET CODE="AudioRecorder.class" ARCHIVE="signedjar.jar" WIDTH="800" HEIGHT="500">
</APPLET>
</div>
</BODY>
</HTML>
[This one was used to load html directly on browser after everything was done successfully, so i kept it safe for future use and moved on to next step. Again an important thing, i kept html file, signed jar and newly created policy file into same folder. You can change directory or place these files on different location if you wish but in my case i was fixing the issue that's why i did so.]
V : I deleted cache files from temporary internet files option present in Java Control Panel [Go to Control Panel > Java > From Temporary internet files, click on settings > Delete files]
VI : I run html file again on browser and then clicked record button and finally it worked as expected.
I hope it will help others who are still facing this problem.
I am having a very wierd issue and I'm hoping you can help me out
At work, we use a web application made with the framework GWT, and all the sales reports have an option to export the data to excel. It usually works fine, but the days that the report has more than about 15-20 thousand rows, the excel file only opens with the word "null" on the first cell.
Within the code, we use a JSP to send the data as html and a StringBuffer object to append all the text of the html. Here es the method that sends the html:
public void export(final String psFormat) {
manageStartOfCall();
String lsFileName = "resources/system/excel_file.jsp";
final DynamicForm loForm = new DynamicForm();
loForm.setAction(lsFileName);
loForm.setMethod(FormMethod.POST);
loForm.setCanSubmit(true);
final TextAreaItem loDataToExport = new TextAreaItem("psExcelData");
final Window loExcelWindow = new Window();
loExcelWindow.setWidth(5);
loExcelWindow.setHeight(5);
loExcelWindow.addItem(loForm);
addChild(loExcelWindow);
new Timer() {
public void run() {
cancel();
loDataToExport.setValue(moHeader.getHeaderAsExcel() + "<br><br>" + moReportGrid.getDataAsHTML());
loForm.setFields(loDataToExport);
new Timer() {
public void run() {
cancel();
manageEndOfCall();
loForm.submit();
loExcelWindow.destroy();
}
}.schedule(200);
}
}.schedule(200);
}
I've already debugged the getDataAsHTML method and the string that it returns is fine, it contains the correct HTML, however when I call the method getParameter in the JSP y returns a null value. Here the code of the JSP:
<%
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=eYumReport.xls");
String msDataToExcel = request.getParameter("psExcelData");
%>
<html>
<head>
<title>Data to excel</title>
</head>
<body>
<%=msDataToExcel %>
</body>
</html>
I may have to mention I am using this on Firefox 26, GWT 2.1, smartGWT 2.4, Windows 7 Professional and the Web application is on Windows Server 2008, mounted on Apache 6.
Any ideas why this is happening??