Java Applets - Browse - Web Server

Dear All,

I have a task... to create something like this

1. Create a Java Applets that consist of 3 items, that is :

- 1 item is address bar

- 1 item is the 'browse' button, you can browse a file from the local, the address is show in the address bar

- 1 item is a run button, what run button do is change the file in the address bar, and save it with other name (example from aa.txt become bb.txt)

[can someone give me a source code for it.... I'm so confused]

2. After that this applets must be placed in the .jsp file (we can use Tomcat for it)

[Can we still browse file even after it's become a web server ?, and change file, edit and save it with different name ?]

3. The last step is to upload this file to some server (maybe ftp server can do it)

Pleasee help me.. I'm afraid if I can't make it within 2-3 days, I'll Drop Out...

Really, pleaseee... senior

[942 byte] By [oracle_rxa] at [2007-11-27 9:28:41]
# 1

creating an applet:

public class myApplet extends java.applet.Applet{

init(){

// this is like main

}

}

creating an address bar use TextField or JTextField and for the buttons use Button or JButton...

Yannixa at 2007-7-12 22:34:33 > top of Java-index,Java Essentials,Java Programming...
# 2
sorry...because I'm a newbiecan you be more specific ?or write some mini code that's compilable...and, then, how about number 2 and 3....thank you so much for everyone willing to answer my question..Duke point will be awarded...
oracle_rxa at 2007-7-12 22:34:33 > top of Java-index,Java Essentials,Java Programming...
# 3

import javax.swing.*;

import java.awt.*;

public class sample extends java.applet.Applet {

public void init(){

createUI();

}

public void createUI(){

JTextField txt = new JTextField();

JButton browse = new JButton("Browse");

JPanel panel = new JPanel();

panel.setLayout(new GridLayout(1,2,0,5));

panel.add(txt);

panel.add(browse);

setSize(300,50);

setLayout(new BorderLayout());

add(panel,BorderLayout.PAGE_START);

}

}

I'm not gonna write the whole code... have some effort in reading the tutorials and write your own code and if you have problems with your code then post it. We are happy to help you.

Yannixa at 2007-7-12 22:34:33 > top of Java-index,Java Essentials,Java Programming...
# 4

I already follow your advice...

After the column and the browse button is ready...

how can we link it to the local directory browser

I read some manual and tutorial that we need JFileChooser

but, some resource said that JFileChooser can't compatible with Java applet

If we don't use it, what else can we use to browse local file

can you guide me ?

oracle_rxa at 2007-7-12 22:34:33 > top of Java-index,Java Essentials,Java Programming...
# 5
here's a thread using applet and jfilechooser http://forum.java.sun.com/thread.jspa?threadID=440016&messageID=1981556
Yannixa at 2007-7-12 22:34:33 > top of Java-index,Java Essentials,Java Programming...
# 6

I follow the step in that site....

after I compile it, it only show a summit button, without anything..

push the summit button don't get me anywhere...

can you continue your guide with the JTextField and JButton

I think I'm more understand your style that his style..

I find a full program about JFileChooser... but it doesn't have any relation with applets, that can browse and select file...

Can you help me to combine it... (I can post it in the next one) or you can help me develop a simple one... push browse to browse local files is ok...

Thank you so much

oracle_rxa at 2007-7-12 22:34:33 > top of Java-index,Java Essentials,Java Programming...
# 7

Applets, as a general rule, are not allowed access to the local file system. So a file browser really isn't a sensible applet function.

There are ways arround the restriction, but the whole point of applets, as opposed to straight Java Swing applications, is that you don't have to install stuff on the client machine. If you have to run the applet from local files, or in an applet viewer, or if you need to change the .policy file to allow special access, you've defeated the whole point.

Applets are, in fact, less useful that you might imagine from reading some of the introductory books. You should consider writing a straight GUI application instead.

malcolmmca at 2007-7-12 22:34:33 > top of Java-index,Java Essentials,Java Programming...
# 8
malcolmmc is right you should write a straight GUI application, but your task is to create an applet.
Yannixa at 2007-7-12 22:34:33 > top of Java-index,Java Essentials,Java Programming...
# 9
> can you continue your guide with the JTextField and> JButton> I think I'm more understand your style that his> style..what should I do next?note: JFileChooser is better use in an application than an applet.
Yannixa at 2007-7-12 22:34:33 > top of Java-index,Java Essentials,Java Programming...
# 10

Thank you for your concern...

Based on my teacher told me... He said that this project is made to check which policy / security must be opened to make this project happened.

And, the main point of using Java Applets is there is no need to install anything in the client PC. I'm afraid Java Swing need at least JRE in the client PC.

Pleasee.. continue the progress...

Really2 thank you so much in advanced....

oracle_rxa at 2007-7-12 22:34:33 > top of Java-index,Java Essentials,Java Programming...
# 11
To Yannix...I already on the step with JTextField and JButton...How can connect These 2 with browse to local PC... on this Java Applets..And, after broswing a file, How can I edit /change this file ?
oracle_rxa at 2007-7-12 22:34:33 > top of Java-index,Java Essentials,Java Programming...
# 12

> Thank you for your concern...

>

> Based on my teacher told me... He said that this

> project is made to check which policy / security must

> be opened to make this project happened.

> And, the main point of using Java Applets is there is

> no need to install anything in the client PC. I'm

> afraid Java Swing need at least JRE in the client

> PC.

a) There has to be a JRE anyway, in order to run Sun-style applets. The browser invokes the JRE to run them.

b) Changing the policy file is installing stuff on the client machine, and more complicated than installing an application would be.

malcolmmca at 2007-7-12 22:34:33 > top of Java-index,Java Essentials,Java Programming...
# 13

> a) There has to be a JRE anyway, in order to run Sun-style applets. The

> browser invokes the JRE to run them.

> b) Changing the policy file is installing stuff on the client machine, and

> more complicated than installing an application would be.

a> I understand it, but my teacher request is used Java Applets, and the reason is because it need not install anything in the client. But my teacher told me, if you can prove that it is impossible, give him the official site, of some legal paper, do you have something like that ? (I think it's possible, with many change, most of them in security policy)

b> The teacher said that change policy (of course this policy is in the server) is OK. I don;t understand 100% by the meaning of "Changing the policy file is installing stuff on the client machine" but I think , if we set the setting right, this process will be automatically done by program, not manually by us.

Pleasee help me too... With the senior like you, I think do this thing won't be so difficult...

Thank you so much in advanced

oracle_rxa at 2007-7-12 22:34:33 > top of Java-index,Java Essentials,Java Programming...
# 14

> b> The teacher said that change policy (of course

> this policy is in the server) is OK. I don;t

> understand 100% by the meaning of "Changing the

> policy file is installing stuff on the client

> machine" but I think , if we set the setting right,

> this process will be automatically done by program,

> not manually by us.

>

The policy file you'd have to change is the one on the client (I suggest using "policytool" which is in the JDK's binary directory). The alternative is to digitally sign the applet's jar file. To do that properly requires that you purchase a digital certificate (at great expense) from a firm like Verasign or Twaite. You can generate a self-signed test certificate, and ignore serveral warning messages from the browser.

This is all about protecting the client from rogue applets on malicious web sites. So something like changing the policy files on the server side obviously can't let you in. What is possible is to construct a more restricted policy for a signed applet - the default is that a signed applet can do anything.

(A policy file essentially contains listsof permissions for various "codesources", for example specific jar files.)

malcolmmca at 2007-7-12 22:34:33 > top of Java-index,Java Essentials,Java Programming...
# 15

thank you so much, My understanding about client policy is increasing....

But, the old problem is exist....

Now, how can I change the Button 'browse" that I create using JButton become really can browse files in the my local. And the link (c:\test\aa.txt for example) is written in the JTextField beside it.

oracle_rxa at 2007-7-21 23:01:59 > top of Java-index,Java Essentials,Java Programming...
# 16
So.. now return to the main problem...How can we combine JFileChooser with Java Applets..So, Java Applets can browse file from local PC...thank you so much in advanced for the answerNB : above tips can't browse file..., above link is down
oracle_rxa at 2007-7-21 23:01:59 > top of Java-index,Java Essentials,Java Programming...
# 17

To do something when a button is clicked you need to add an object whose class extends ActionListener to the button. When the button is clicked the method actionPerformed() is called.

The neatest way to do this is to use an "anonymous class". This adds what amounts to a class definition to the new operator that defines the object.

This looks like:

myButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent evt) {

... do your action stuff here

}

});

Because this counts as an inner class the actionPerformed method can access the fields and methods of the outer object, and even local variables if they are declared as final

malcolmmca at 2007-7-21 23:01:59 > top of Java-index,Java Essentials,Java Programming...
# 18
my action is only browse local file...how can I combine it with listener ?help needed.....and thank's before
oracle_rxa at 2007-7-21 23:01:59 > top of Java-index,Java Essentials,Java Programming...
# 19

Can someone change this JPanel become Java Applets ?

Help is really needed....

package components;

import java.io.*;

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.filechooser.*;

public class Main extends JPanel implements ActionListener {

static private final String newline = "\n";

JButton openButton, saveButton;

JTextArea log;

JFileChooser fc;

public Main() {

super(new BorderLayout());

log = new JTextArea(5,20);

log.setMargin(new Insets(5,5,5,5));

log.setEditable(false);

JScrollPane logScrollPane = new JScrollPane(log);

fc = new JFileChooser();

openButton = new JButton("Open a File...",

createImageIcon("images/Open16.gif"));

openButton.addActionListener(this);

saveButton = new JButton("Save a File...",

createImageIcon("images/Save16.gif"));

saveButton.addActionListener(this);

JPanel buttonPanel = new JPanel(); //use FlowLayout

buttonPanel.add(openButton);

buttonPanel.add(saveButton);

add(buttonPanel, BorderLayout.PAGE_START);

add(logScrollPane, BorderLayout.CENTER);

}

public void actionPerformed(ActionEvent e) {

if (e.getSource() == openButton) {

int returnVal = fc.showOpenDialog(Main.this);

if (returnVal == JFileChooser.APPROVE_OPTION) {

File file = fc.getSelectedFile();

log.append("Opening: " + file.getName() + "." + newline);

} else {

log.append("Open command cancelled by user." + newline);

}

log.setCaretPosition(log.getDocument().getLength());

} else if (e.getSource() == saveButton) {

int returnVal = fc.showSaveDialog(Main.this);

if (returnVal == JFileChooser.APPROVE_OPTION) {

File file = fc.getSelectedFile();

log.append("Saving: " + file.getName() + "." + newline);

} else {

log.append("Save command cancelled by user." + newline);

}

log.setCaretPosition(log.getDocument().getLength());

}

}

protected static ImageIcon createImageIcon(String path) {

java.net.URL imgURL = Main.class.getResource(path);

if (imgURL != null) {

return new ImageIcon(imgURL);

} else {

System.err.println("Couldn't find file: " + path);

return null;

}

}

private static void createAndShowGUI() {

JFrame frame = new JFrame("FileChooserDemo");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JComponent newContentPane = new Main();

newContentPane.setOpaque(true); //content panes must be opaque

frame.setContentPane(newContentPane);

frame.pack();

frame.setVisible(true);

}

public static void main(String[] args) {

javax.swing.SwingUtilities.invokeLater(new Runnable() {

public void run() {

createAndShowGUI();

}

});

}

}

oracle_rxa at 2007-7-21 23:01:59 > top of Java-index,Java Essentials,Java Programming...
# 20

create a class like this:

public class myPRJ extends java.applet.Applet {

public void init(){

add(new Main());

}

}

Your modified code:

import java.io.*;

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.filechooser.*;

public class Main extends JPanel implements ActionListener {

static private final String newline = "\n";

JButton openButton, saveButton;

JTextArea log;

JFileChooser fc;

public Main() {

super(new BorderLayout());

log = new JTextArea(5,20);

log.setMargin(new Insets(5,5,5,5));

log.setEditable(false);

JScrollPane logScrollPane = new JScrollPane(log);

fc = new JFileChooser();

openButton = new JButton("Open a File...",

createImageIcon("images/Open16.gif"));

openButton.addActionListener(this);

saveButton = new JButton("Save a File...",

createImageIcon("images/Save16.gif"));

saveButton.addActionListener(this);

JPanel buttonPanel = new JPanel(); //use FlowLayout

buttonPanel.add(openButton);

buttonPanel.add(saveButton);

add(buttonPanel, BorderLayout.PAGE_START);

add(logScrollPane, BorderLayout.CENTER);

}

public void actionPerformed(ActionEvent e) {

if (e.getSource() == openButton) {

int returnVal = fc.showOpenDialog(Main.this);

if (returnVal == JFileChooser.APPROVE_OPTION) {

File file = fc.getSelectedFile();

log.append("Opening: " + file.getName() + "." + newline);

} else {

log.append("Open command cancelled by user." + newline);

}

log.setCaretPosition(log.getDocument().getLength());

} else if (e.getSource() == saveButton) {

int returnVal = fc.showSaveDialog(Main.this);

if (returnVal == JFileChooser.APPROVE_OPTION) {

File file = fc.getSelectedFile();

log.append("Saving: " + file.getName() + "." + newline);

} else {

log.append("Save command cancelled by user." + newline);

}

log.setCaretPosition(log.getDocument().getLength());

}

}

protected static ImageIcon createImageIcon(String path) {

java.net.URL imgURL = Main.class.getResource(path);

if (imgURL != null) {

return new ImageIcon(imgURL);

} else {

System.err.println("Couldn't find file: " + path);

return null;

}

}

}

Yannixa at 2007-7-21 23:01:59 > top of Java-index,Java Essentials,Java Programming...
# 21
Where should I place :public class myPRJ extends java.applet.Applet {public void init(){add(new Main());} }other files ? or....and how can it connect each other ?sorry for the newbie question
oracle_rxa at 2007-7-21 23:01:59 > top of Java-index,Java Essentials,Java Programming...
# 22

> Where should I place :

>

> public class myPRJ extends java.applet.Applet {

>public void init(){

>add(new Main());

> }

> }

>

> other files ? or....

> and how can it connect each other ?

>

> sorry for the newbie question

separate file each... Main.java and myPRJ.java

run myPRJ.java not Main.java

Yannixa at 2007-7-21 23:01:59 > top of Java-index,Java Essentials,Java Programming...
# 23
javac Main.javaok.. no problemjavac myPRJ.javamyPRJ.java:9: cannot resolve symbolsymbol : class Mainlocation: class myPRJadd(new Main());^1 errorBecause myPRJ don't recognize Main... what should I do ?
oracle_rxa at 2007-7-21 23:01:59 > top of Java-index,Java Essentials,Java Programming...
# 24
save and complie both java files in the same directory.....
Yannixa at 2007-7-21 23:01:59 > top of Java-index,Java Essentials,Java Programming...
# 25
I already place it in the same directory...on one time, we can only compile 1 file, is it right ?I used Command Prompt to compile it....type 'javac'and, there is error like that
oracle_rxa at 2007-7-21 23:01:59 > top of Java-index,Java Essentials,Java Programming...
# 26
> I already place it in the same directory...> > on one time, we can only compile 1 file, is it right> ?> No, you can give javac it a list of files or even *.java
malcolmmca at 2007-7-21 23:01:59 > top of Java-index,Java Essentials,Java Programming...
# 27

Thank you so much for the reply.. I can compile it... and success....

But, even the myPRJ is and applets, both of them can't appear in the HTML when I embedded it...

The conclusion is we can't make the raw JPanel (with JFileChooser) inside Java Applets... So... how can I combine JFileChooser that can be read by Java Applets and my HTML...

Or do you have other solution ? The main point is I can't to browse local files in my Java Applets....

Please help, and thank you againn

oracle_rxa at 2007-7-21 23:01:59 > top of Java-index,Java Essentials,Java Programming...
# 28
Actually you can open windows from applets, though they appear with a security health warning, and some browsers may block them.
malcolmmca at 2007-7-21 23:01:59 > top of Java-index,Java Essentials,Java Programming...
# 29
can you tell me how can I post java program with the right model ?I find and edit some Java Applets program and now it can browse my local file.I want to show it to all of you.. To ask for the next step...
oracle_rxa at 2007-7-21 23:01:59 > top of Java-index,Java Essentials,Java Programming...
# 30

At this point, I can make my Java applets browse local file...

now there are 2 problem....

1. How can I create a link between the file that I chose, to show it in the JTextArea on the left of it.... (I mean after I browse a file, it's nothing happened)

2. How can I edit file that I chose....

import java.applet.*;

import java.awt.*;

import java.util.*;

import java.lang.*;

import java.text.*;

import java.awt.event.*;

import java.io.*;

public class localfile extends Applet {

public localfile() {

Panel p = new Panel();

Font f;

String osname = System.getProperty("os.name","");

if (!osname.startsWith("Windows")) {

f = new Font("Arial",Font.BOLD,10);

} else {

f = new Font("Verdana",Font.BOLD,12);

}

p.setFont(f);

p.add(new Button("Open"));

p.setBackground(new Color(255, 255, 255));

add("North",p);

}

public boolean action(Event evt, Object arg) {

if (arg.equals("Open")) {

System.out.println("OPEN CLICKED");

int arrlen = 10000;

byte[] infile = new byte[arrlen];

Frame parent = new Frame();

FileDialog fd = new FileDialog(parent, "Please choose a file:",

FileDialog.LOAD);

fd.show();

String selectedItem = fd.getFile();

if (selectedItem == null) {

// no file selected

} else {

File ffile = new File( fd.getDirectory() + File.separator +

fd.getFile());

// read the file

System.out.println("reading file " + fd.getDirectory() +

File.separator + fd.getFile() );

try {

FileInputStream fis = new FileInputStream(ffile);

BufferedInputStream bis = new BufferedInputStream(fis);

DataInputStream dis = new DataInputStream(bis);

try {

int filelength = dis.read(infile);

String filestring = new String(infile, 0,

filelength);

System.out.println("FILE CONTENT=" + filestring);

} catch(IOException iox) {

System.out.println("File read error...");

iox.printStackTrace();

}

} catch (FileNotFoundException fnf) {

System.out.println("File not found...");

fnf.printStackTrace();

}

}

} else return false;

return true;

}

}

oracle_rxa at 2007-7-21 23:02:04 > top of Java-index,Java Essentials,Java Programming...
# 31

On the forum, surround your code in code tags; the button above the message window will create a pair for you, and you can paste your code between them. That's much more readable.

I'd suggest using JFileChooser instead of FileDialog - that's the swing version and it's more versatile.

To read text, use a Reader not an InputStream. Then you use a char[] buffer rather than a byte buffer, or you use a BufferedReader and read each line as a String.

Once you have a text String just use the setText() method of a TextArea or the like to display the text.

malcolmmca at 2007-7-21 23:02:04 > top of Java-index,Java Essentials,Java Programming...
# 32

thank you so much...

Now my read - and write file is almost done....

Now, I got my new problem... It's about upload...

If I have a file, can read and write it, how can I upload this file to the other place... (use FTP is OK, let's make other server open a FTP server with the user and password...)

How can I make the program...

oracle_rxa at 2007-7-21 23:02:04 > top of Java-index,Java Essentials,Java Programming...
# 33

The simplest way to access an FTP site is to use a URL string. You may be able to do something like this:

URL url = new URL("ftp://username:password@ftp.whatever.com/file.zip;type=i");

URLConnection con = url.openConnection();

BufferedInputStream in =

new BufferedInputStream(con.getInputStream());

FileOutputStream out =

new FileOutputStream("C:\\file.zip");

int i = 0;

byte[] bytesIn = new byte[1024];

while ((i = in.read(bytesIn)) >= 0) {

out.write(bytesIn, 0, i);

}

out.close();

in.close();

This method can work if:

* the site supports it

* you know exactly what file you need and where it is

* you don't have to do anything other than just download a file

Yannixa at 2007-7-21 23:02:04 > top of Java-index,Java Essentials,Java Programming...
# 34

Thank you so much for all the answer...

This is my last program...

In the local path, I can perfectly read and write (with open the policy file of course), but After I put it in the Tomcat Web Server, the read and write ability is get the security access denied.....

import java.io.*;

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

import javax.swing.*;

import javax.swing.border.*;

public class rwf2 extends JApplet implements ActionListener {

private JPanel pane = null;

private JScrollPane scrolling = null;

private JTextPane fileBox = null;

private JTextField tfFilename = null;

private JButton butLoad = null;

private final String LOAD = "load";

public void init() {

try {

jbInit();

} catch(Exception e) {

e.printStackTrace();

}

}

// method which will read data from file, and return it in

// String

public String readFile(String fn) {

String thisLine, ret = "";

try {

FileInputStream fin = new FileInputStream(fn);

BufferedReader myInput = new BufferedReader

(new InputStreamReader(fin));

while ((thisLine = myInput.readLine()) != null) {

ret += thisLine + "\n";

}

} catch (Exception e) {

ret = ("Cannot load, exception! "+ e);

}

return (ret);

}

private void jbInit() throws Exception {

pane = new JPanel();

pane.setBounds(new Rectangle(0, 0, 500, 325));

pane.setLayout(null);

pane.setBorder(BorderFactory.createEtchedBorder(

EtchedBorder.LOWERED));

pane.setBackground(new Color(221, 194, 219));

fileBox = new JTextPane();

fileBox.setText("");

fileBox.setEditable(false);

scrolling = new JScrollPane(fileBox);

scrolling.setBounds(new Rectangle(16, 65, 295, 225));

tfFilename = new JTextField();

tfFilename.setText("");

tfFilename.setBounds(new Rectangle(16, 23, 206, 29));

butLoad = new JButton();

butLoad.setBounds(new Rectangle(231, 23, 80, 30));

butLoad.setText("Load");

butLoad.setActionCommand(LOAD);

butLoad.addActionListener(this);

pane.add(scrolling);

pane.add(tfFilename);

pane.add(butLoad);

setContentPane(pane);

}

public void actionPerformed(ActionEvent e) {

if (e.getActionCommand().equals(LOAD)) {

fileBox.setText(readFile(tfFilename.getText()));

//public void paint(Graphics g) {

String fileName = "a.txt";

String address = "C:\\coba\\exper7\\";

String source;

source = readFile(tfFilename.getText());

try {

FileOutputStream fos = new FileOutputStream(address + fileName);

PrintStream outputFile = new PrintStream(fos);

outputFile.println( source + "\n" + "Keren !!");

outputFile.close();

fos.close();

//g.drawString("The applet created the file " + fileName, 10, 20);

}

catch (SecurityException eq) {

//g.drawString(e + "", 10, 20);

}

catch (IOException ioe) {

//g.drawString("NoBox: i/o exception", 10, 20);

}

//}

}

}

}

can anyone help me to solve this problem ?

oracle_rxa at 2007-7-21 23:02:04 > top of Java-index,Java Essentials,Java Programming...
# 35
because no reply...I officialy closed this thread...thank you so much for any answer....I already give the Duke star for everyone that help me solve it...
oracle_rxa at 2007-7-21 23:02:04 > top of Java-index,Java Essentials,Java Programming...
# 36
> because no reply...> > I officialy closed this thread...> > thank you so much for any answer....> I already give the Duke star for everyone that help> me solve it...tried to help but never tried using tomcat web
Yannixa at 2007-7-21 23:02:04 > top of Java-index,Java Essentials,Java Programming...