posts - 167,  comments - 30,  trackbacks - 0
最近通过做的项目中修改个bug,在jsp页面中潜入applet,通过applet来上传5-10G之间的文件。
修改过程记录如下:
JSP页面中
                <div id="appletTemp">   
                       <applet code = "org/apache/commons/yp/MyApplet.class"  name="test" archive="applet.jar"
                             height="32" width="260" mayscript>
                        <s:text name="image.add.installJdk"></s:text>
                         </applet>
                  </div>   

以下为Java Applet结合commons-net-2.0.jar包实现上传文件的功能代码:
package org.apache.commons.yp;

import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JTextField;
import javax.swing.filechooser.FileFilter;
import netscape.javascript.JSObject;

public class MyApplet extends Applet implements ActionListener {
    
public void destroy() {
    }

    
public String getAppletInfo() {
        
return "This is my default applet created by Eclipse";
    }

    
public void init() {
    }

    
public void start() {
    }

    
public void stop() {
    }

    
private static final long serialVersionUID = 1L;

    
private MyApplet jFrame = null;

    
private JButton jFileButton = null;
    
private JButton onClickButton = null;
    JTextField jtf 
= new JTextField(10);
    File fileIn 
= null;
    FileFtpApplet myFtp 
= new FileFtpApplet();
    
public int totalSize = 0;
    
public int nowSize = 0;
    
public String hostName;
    
public Integer port;
    
public String user;
    
public String password; 
    
    
public String getHostName() {
        
return hostName;
    }

    
public void setHostName(String hostName) {
        
this.hostName = hostName;
    }

    
public Integer getPort() {
        
return port;
    }

    
public void setPort(Integer port) {
        
this.port = port;
    }

    
public String getUser() {
        
return user;
    }

    
public void setUser(String user) {
        
this.user = user;
    }

    
public String getPassword() {
        
return password;
    }

    
public void setPassword(String password) {
        
this.password = password;
    }

    
public MyApplet() {
        System.out.println(
" MyApplet start ");
        jFrame 
= this;
        jFrame.setSize(
5010);
        jFileButton 
= new JButton("浏览");
        jFileButton.setFont(
new Font("system", Font.PLAIN, 12));
        jFileButton.setSize(
22);
        onClickButton 
= new JButton("上传");
        onClickButton.setFont(
new Font("system", Font.PLAIN, 12));
        jFrame.add(jtf, BorderLayout.NORTH);
        jFrame.add(jFileButton);
        jFrame.add(onClickButton);
        jtf.setEditable(
true);
        onClickButton.addActionListener((ActionListener) 
this);
        jFileButton.addActionListener((ActionListener) 
this);
        onClickButton.setSize(
220);
        System.out.println(
" MyApplet end ");
        
this.start();
    }

    
public void actionPerformed(ActionEvent e) {
        System.out.println(
" actionPerformed(ActionEvent e)  ");
        String comm 
= e.getActionCommand();
        
try {
            
if ("浏览".equals(comm)) {
                JFileChooser jfChooser 
= new JFileChooser("");
                jfChooser.setDialogTitle(
"打开并上传文件");
                jfChooser.setFileFilter(
new FileFilter() {
                    @Override
                    
public boolean accept(File f) {
                        
if (f.getName().endsWith("img"|| f.isDirectory())
                            
return true;
                        
return false;
                    }

                    @Override
                    
public String getDescription() {
                        
return "镜像文件(*.img)";
                    }
                });
                
int result = jfChooser.showOpenDialog(jFrame);
                
if (result == JFileChooser.APPROVE_OPTION) {
                    fileIn 
= jfChooser.getSelectedFile();
                    jtf.setText(fileIn.getPath());
                    
try {
                        JSObject.getWindow(
this).eval(
                                
"getinfo(" + "\"" + fileIn.getName() + "\""
                                        
+ ")");
                    } 
catch (Exception ea) {
                        ea.printStackTrace();
                    }
                    
if (fileIn != null && fileIn.exists()) {
                        
try {
                            
long l1 = System.currentTimeMillis();
                            System.out.println(hostName
+"----hostName");
                            System.out.println(port
+"----port");
                            System.out.println(user
+"-----user");
                            System.out.println(password
+"---------password");
                            
if (myFtp.connect(hostName, port, user, password)) {
                                myFtp.setLocal(fileIn.getPath());
                                myFtp.setFileName(fileIn.getName());
                                myFtp.setRemote(
"../../opt/nebula/images");
                                
long l2 = System.currentTimeMillis();
                                System.out.println(
"end:" + l2);
                                System.out.println(
"remaining:" + (l2 - l1));
                            }
                        } 
catch (Exception e1) {
                            System.out.println(
"连接出错 " + e1.getMessage());
                        }
                    }
                }
            } 
else if ("上传".equals(comm)) {
                
try {
                    JSObject.getWindow(
this).eval(
                            
"javascript:showLoading(" + "\"" + fileIn.getName()
                                    + "\"" + ")");
                } catch (Exception ea) {
                    ea.printStackTrace();
                }
                myFtp.upload(hostName, port, user, password);
                
try {
                    JSObject.getWindow(
this).eval(
                            
"javascript:uploadEnd(" + "\"" + fileIn.getName()
                                    + "\"" + ")");
                } catch (Exception ea) {
                    ea.printStackTrace();
                }
            }
        } 
catch (HeadlessException e1) {
            e1.printStackTrace();
        } 
finally {
            
try {
                myFtp.disconnect();
            } 
catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
}

package org.apache.commons.yp;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

/**
 * 
 * Function Description:FTP 鍔熻兘绫伙紝鍚玴ut鍜実et鏂规硶
 
*/

public class FileFtpApplet {
    
public static FTPClient ftp = new FTPClient();
    
public String remote;
    
public String fileName;
    
public String local;

    
public String getRemote() {
        
return remote;
    }

    
public void setRemote(String remote) {
        
this.remote = remote;
    }

    
public String getFileName() {
        
return fileName;
    }

    
public void setFileName(String fileName) {
        
this.fileName = fileName;
    }

    
public String getLocal() {
        
return local;
    }

    
public void setLocal(String local) {
        
this.local = local;
    }

    
public boolean upload(String hostname, Integer port, String username,
            String password) {
        
try {
            
this.connect(hostname, port, username, password);
        } 
catch (IOException e1) {
            e1.printStackTrace();
        }
        ftp.enterLocalPassiveMode();
        
try {
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
        } 
catch (IOException e) {
            e.printStackTrace();
        }
        
try {
            ftp.changeWorkingDirectory(
"");
        } 
catch (IOException e) {
            e.printStackTrace();
        }
        
boolean result;
        
try {
            createDir(remote);
        } 
catch (IOException e) {
            e.printStackTrace();
        }
        
boolean isExists = false;
        
long fileSize = 0;
        FTPFile[] files 
= new FTPFile[10];
        
try {
            files 
= ftp.listFiles();
        } 
catch (IOException e) {
            e.printStackTrace();
        }
        
for (int i = 0; i < files.length; i++) {
            FTPFile file 
= files[i];
            
if (fileName.equals(file.getName())) {
                isExists 
= true;
                fileSize 
= file.getSize();
                
break;
            }
        }
        
if (isExists) {
            System.out.println(
"fileSize:" + fileSize);
            File fLocal 
= new File(local);
            OutputStream os;
            
try {
                os 
= ftp.appendFileStream(fileName);
                RandomAccessFile randomAccessFileLocal;
                randomAccessFileLocal 
= new RandomAccessFile(fLocal, "r");
                randomAccessFileLocal.seek(fileSize);
                
int len = 0;
                
byte[] bt = new byte[1024];
                
while ((len = randomAccessFileLocal.read(bt)) > 0) {
                    os.write(bt, 
0, len);
                }
                randomAccessFileLocal.close();
                os.close();
                result 
= true;
            } 
catch (IOException e) {
                e.printStackTrace();
            }

        } 
else {
            
try {
                File f 
= new File(local);
                FileInputStream in 
= new FileInputStream(f);
                result 
= ftp.storeFile(fileName, in);
                in.close();
                
return result;
            } 
catch (Exception e) {
                e.printStackTrace();
            }
        }
        
return false;
    }

    
/**
     * 寤虹珛FTP杩炴帴
     
*/
    
public boolean connect(String hostname, int port, String username,
            String password) 
throws IOException {
        ftp.connect(hostname, port);
        ftp.login(username, password);
        
if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
            disconnect();
            
return false;
        }
        
return true;
    }

    
/**
     * 鍏抽棴FTP杩炴帴
     
*/
    
public void disconnect() throws IOException {
        
if (ftp.isConnected()) {
            ftp.disconnect();
        }
    }

    
public void createDir(String dir) throws IOException {
        
if (dir != null && dir.trim().length() > 0) {
            String[] dirs 
= dir.split("/");
            String workingDir 
= "";
            
for (int i = 0; i < dirs.length; i++) {
                
if (!existDirectory(workingDir, dirs[i])) {
                    ftp.makeDirectory(dirs[i]);
                    workingDir 
= dirs[i];
                    ftp.changeWorkingDirectory(dirs[i]);
                } 
else {
                    workingDir 
= dirs[i];
                    ftp.changeWorkingDirectory(dirs[i]);
                }
            }
        }
    }

    
public boolean existDirectory(String path, String dirName)
            
throws IOException {
        
boolean flag = false;
        FTPFile[] ftpFileArr 
= ftp.listFiles(path);
        
for (FTPFile ftpFile : ftpFileArr) {
            
if (ftpFile.isDirectory()
                    
&& ftpFile.getName().equalsIgnoreCase(dirName)) {
                flag 
= true;
                
break;
            }
        }
        
return flag;
    }
}
访问该jsp页面,第一次会提示“请安装jdk” ,那么就按照他所说的,去
http://www.java.com/下载jre进行安装。(但是我自己服务器上已经有jdk,为什么默认找到里面的jre呢,在研究中。。。)
控制台中打印的信息:
Java Plug-in 1.6.0_26
使用 JRE 版本 1.6.0_26-b03 Java HotSpot(TM) Client VM
用户主目录 = C:\Documents and Settings\server

----------------------------------------------------
c:   清除控制台窗口
f:   终结在结束队列上的对象
g:   垃圾收集
h:   显示此帮助消息
l:   转储类载入程序列表
m:   打印内存使用
o:   触发日志记录
q:   隐藏控制台
r:   重新载入策略配置
s:   转储系统和部署属性
t:   转储线程列表
v:   转储线程堆栈
x:   清除类载入程序高速缓存
0-5: 设置跟踪级别为<n>
----------------------------------------------------
。。。。。。。。。。。。。。。。。。。。。。。。。。
安装完成jre后,报错 ClassNotFoundException找不到应用中的org/apache/commons/yp/MyApplet.class文件.
因为archive="applet.jar",默认找的是工程WebRoot下面的See the line -:
applet.jar,所以需要将MyApplet.java打包为applet.jar中并放到WebRoot下。
访问还是报错说找不到org/apache/commons/net/ftp/FTPClient.class类,我工程中的lib下已经存在commons-net-2.0.jar,找的应该是默认在applet.jar中类,
所以我又将
commons-net-2.0.jar
中所有的class文件放到了applet.jar中。在访问不存在找不到类的问题了。

但是又出现了新的问题,说
Caused by: java.security.AccessControlException: access denied (java.io.FilePermission <<ALL FILES>> read)等相关的异常。
解决方案如下:
Edit and append the snippet below, to the end of the policy file (The typical location of your policy file is C:\Program Files\Java\jre1.5.0_16\lib\security\java.policy). If you are running a different JRE (i.e. 1.6), then the folder name 'jre1.5.0_16' will obviously reflect your version of the java runtime environment.

在你自己的jre\lib\security\java.policy文件中增加如下配置。对于文件的访问许可。
grant codeBase "http://*/-" {
    permission java.security.AllPermission;
    permission java.io.FilePermission "<<ALL FILES>>", "read";
    permission java.io.FilePermission "<<ALL FILES>>", "write";
};
经过测试,以上配置可用。
java applet界面如下:

以上问题解决之后,点击浏览,弹出框选择文件,之后点击上传。
查看jre控制台说连接不上ftp 21端口,Connected refused Exception,
那就说明linux的ftp 21端口没有开启。看如下解决方案:

1-ssh以root用户身份登录 登录Linux系统后,

vi /etc/xinetd.d/gssftp

# default: off
# description: The kerberized FTP server accepts FTP connections \
#              that can be authenticated with Kerberos 5.
service ftp
{
        flags           = REUSE
        socket_type     = stream
        wait            = no
        user            = root
        server          = /usr/kerberos/sbin/ftpd
        server_args     = -l  -a
        log_on_failure  += USERID
        disable         = yes
}
server_args     = -l  -a 修改为 server_args     = -l
disable         = yes 修改 disable         = no
然后执行
[root@vm-container-16-5 sbin]# service xinetd restart
Stopping xinetd:                                           [  OK  ]
Starting xinetd:                                           [  OK  ]
OK!!!!

2- 执行service xinetd restart如果出现
xinetd: unrecognized service
则可能说明安装操作系统时默认未安装xinetd
通过yum -y install xinetd
[root@vm-container-16-5 sbin]# service xinetd restart
xinetd: unrecognized service
[root@vm-container-16-5 sbin]# yum -y install xinetd
Rocks-5.3                                                                                                                                                                          | 1.1 kB     00:00     
Setting up Install Process
Resolving Dependencies
There are unfinished transactions remaining. You might consider running yum-complete-transaction first to finish them.
The program yum-complete-transaction is found in the yum-utils package.
--> Running transaction check
---> Package xinetd.x86_64 2:2.3.14-10.el5 set to be updated
--> Finished Dependency Resolution

Dependencies Resolved

==========================================================================================================================================================================================================
 Package                                      Arch                                         Version                                                  Repository                                       Size
==========================================================================================================================================================================================================
Installing:
 xinetd                                       x86_64                                       2:2.3.14-10.el5                                          Rocks-5.3                                       125 k

Transaction Summary
==========================================================================================================================================================================================================
Install      1 Package(s)         
Update       0 Package(s)         
Remove       0 Package(s)         

Total download size: 125 k
Downloading Packages:
xinetd-2.3.14-10.el5.x86_64.rpm                                                                                                                                                    | 125 kB     00:00     
Running rpm_check_debug
Running Transaction Test
Finished Transaction Test
Transaction Test Succeeded
Running Transaction
  Installing     : xinetd                                                                                                                                                                             1/1

Installed:
  xinetd.x86_64 2:2.3.14-10.el5                                                                                                                                                                           

Complete!
[root@vm-container-16-5 sbin]# service xinetd restart      
Stopping xinetd:                                           [FAILED]
Starting xinetd:                                           [  OK  ]
[root@vm-container-16-5 sbin]# service xinetd restart
Stopping xinetd:                                           [  OK  ]
Starting xinetd:                                           [  OK  ]

Linux下如果FTP访问不了可以进行如下设置修改:

在终端中执行 vi /etc/selinux/config,将其中的selinux=enforcing的enforcing改为disable。然后保存退出vi,执行setenforce 0 或者重启。就可以上传了。

如果,你不是上述的解决方法的话,有可能是你没有到ftp服务器下的incoming文件夹中,或者你没有把incoming文件夹的权限改为777。

ELinux是「Security-Enhanced Linux」的简称,是美国国家安全局「NSA=The National Security Agency」 和SCC(Secure Computing Corporation)开发的 Linux的一个扩张强制访问控制安全模块。原先是在Fluke上开发的,2000年以 GNU GPL 发布。

posted on 2011-06-21 15:07 David1228 阅读(2227) 评论(0)  编辑  收藏 所属分类: Linux

只有注册用户登录后才能发表评论。


网站导航:
 

<2011年6月>
2930311234
567891011
12131415161718
19202122232425
262728293012
3456789

常用链接

留言簿(4)

随笔分类

随笔档案

文章档案

新闻分类

新闻档案

相册

收藏夹

Java

Linux知识相关

Spring相关

云计算/Linux/虚拟化技术/

友情博客

多线程并发编程

开源技术

持久层技术相关

搜索

  •  

积分与排名

  • 积分 - 353972
  • 排名 - 155

最新评论

阅读排行榜

评论排行榜