⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ftpconnection.java

📁 JAVA FTP客户端经典
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
/* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA. */package net.sf.jftp.net;import net.sf.jftp.config.Settings;import net.sf.jftp.util.Log;import net.sf.jftp.util.StringUtils;import java.io.*;import java.net.*;import java.util.*;/** * Base class. All control transactions are made here. */public class FtpConnection implements BasicConnection, FtpConstants{    // everything starting with this will be treated    // as a negative response    private final static String NEGATIVE = "5";    private final static String NEGATIVE2 = "4";    // everything starting with this will be treated    // as a positive response    private final static String POSITIVE= "2";    // for resuming    private final static String PROCEED = "3"; //"350";    // if the 4th character is this, we do not break    // but wait for more lines    private final static char MORE_LINES_APPENDED = '-';    // login failed    public final static String WRONG_LOGIN_DATA = "Wrong login data!";    // temporarily not available    public final static String OFFLINE = "Offline";    // connection failed    public final static String GENERIC_FAILED = "Connection failed!";    // login ok    public final static String LOGIN_OK = "ok";    public final static String DOWNLOAD  = "DOWNLOAD";    public final static String UPLOAD  = "UPLOAD";    public final static String ABOR  = "ABOR";    // to check file permissions    public static final int R = 23;    public static final int W = 42;    public static final int DENIED = 666;    private boolean msg = true;    private boolean ok = true;    private String pwd = "";    private String initCWD = Settings.defaultDir;    private String[] loginAck = new String[] { FTP331_USER_OK_NEED_PASSWORD, FTP230_LOGGED_IN };    private String osType;    private String dataType;    public boolean work = true;    private boolean modeStreamSet = false;    private DataConnection dcon = null;    private Vector listeners = new Vector();    private ConnectionHandler handler = new ConnectionHandler();    // directory downloaded to    private String localPath = null;    // active ftp ports    private int porta = 5; // 5 * 256 + 1 = 1281    private int portb = 1;    /** the host */    private String host = "";    /** the user */    private String username;    /** the password */    private String password;    /** the port */    private int port = 21;    /** the InputStream of the control connection */    private BufferedReader in;    /** the OutputStream of the control connection */    private JConnection jcon;    /** we are disconnected */    private boolean connected = false;    public boolean hasUploaded = false;    private boolean shortProgress = false;    private boolean isDirUpload = false;    private String baseFile;    private int fileCount;    public FtpConnection(String host)    {        this.host = host;        File f = new File(".");        setLocalPath(f.getAbsolutePath());    }    public FtpConnection(String host, int port, String initCWD)    {        this.host = host;        this.port = port;        this.initCWD = initCWD;        File f = new File(".");        setLocalPath(f.getAbsolutePath());    }    /** connects to the server. */    public String login(String username, String password)    {        this.username = username;        this.password = password;	String status = LOGIN_OK;        if(msg)        {            Log.debug("Connecting to "+host);        }        jcon = new JConnection(host,port);        if(jcon.isThere())        {            in = jcon.getReader();            if(getLine(FTP220_SERVICE_READY) == null)            {                ok = false;                Log.debug("Server closed Connection, maybe too many users...");                status = OFFLINE;            }            if(msg)            {                Log.debug("Connection established...");            }            jcon.send(USER + " " + username);            if(!getLine(loginAck).startsWith(FTP230_LOGGED_IN))            {                jcon.send(PASS + " " + password);                if(success(FTP230_LOGGED_IN))                {                    if(msg)                        Log.debug("Logged in...");                }                else                {                    Log.debug("Wrong password!");                    ok = false;		    status = WRONG_LOGIN_DATA;                }            }            // end if(jcon)...        }        else        {            if(msg)            {                Log.debug("FTP not available!");                ok = false;		status = GENERIC_FAILED;            }        }        if(ok)        {	    connected = true;	    system();	    binary();	    if(initCWD.trim().equals(Settings.defaultDir) ||               !chdirNoRefresh(initCWD))	    {	        //System.out.println("default dir...");	    	//if(!chdirNoRefresh(getPWD()))		//{			//System.out.println("FtpConnection should not do this...");                //	if(!chdirNoRefresh("~"))                //	{                  //  		chdirNoRefresh("/");                //	}		//}		updatePWD();	    }	    fireDirectoryUpdate(this);	    fireConnectionInitialized(this);        }	else	{	    fireConnectionFailed(this, status);	}	return status;    }    /** sorts the filesizes */    public String[] sortSize(String file)    {        BufferedReader in = null;        PrintStream out = null;        int length = 0;	        try        {            in = new BufferedReader(new FileReader(file));            out = new PrintStream(new FileOutputStream(Settings.sortsize_out));            while(true)            {                String tmp = in.readLine();                if(tmp == null)                    break;                length++;		// ------------- VMS override -------------------		if(getOsType().startsWith("VMS"))		{			if(tmp.indexOf(";")<0)			{			 length--;			 continue;			}			out.println("-1");			continue;		}		// ------------------------------------------------                else if(osType.startsWith("WINDOW"))                {                    StringTokenizer to = new StringTokenizer(tmp, " ", false);		    if (to.countTokens() > 5) {			to.nextToken();			to.nextToken();			to.nextToken();			to.nextToken();			String size = to.nextToken();			out.println(size);                    } else if(to.countTokens() >= 3)                    {                        to.nextToken();                        to.nextToken();                        String size = to.nextToken();                        if(size.equals("<DIR>"))                        {                            out.println("0");                        }                        else                        {                            out.println(size);                        }                    }                }		else		{                    StringTokenizer to = new StringTokenizer(tmp," ",true);                    if(to.countTokens() > 8)                    {                        tmp = giveSize(to,4);                        //    System.out.println(s);                        out.println(tmp);                    }		    else		    {		    	length--;		    }                }            }        }        catch(Exception ex)        {            Log.debug(ex.toString()+" @FtpConnection::sortSize#1");        }        try        {            in = new BufferedReader(new FileReader(Settings.sortsize_out));            String[] files = new String[length];            for(int i=0; i<length; i++)            {                files[i] = in.readLine();                //System.out.println(files[i]);		//Log.debug(files[i]);            }            return files;        }        catch(Exception ex)        {            Log.debug(ex.toString()+" @FtpConnection::sortSize#2");        }        return new String[0];    }    /** sorts the filesizes */    public int[] getPermissions(String file)    {        BufferedReader in = null;        PrintStream out = null;        int length = 0;        try        {            in = new BufferedReader(new FileReader(file));            out = new PrintStream(new FileOutputStream(Settings.permissions_out));            while(true)            {                String tmp = in.readLine();                if(tmp == null) break;		// ------------- VMS override -------------------		if(getOsType().startsWith("VMS"))		{			if(tmp.indexOf(";")<0) continue;			out.println("r");			length++;			continue;		}		// ------------------------------------------------		                length++;                    StringTokenizer to = new StringTokenizer(tmp.trim()," ",false);		    if(!(to.countTokens() > 3) || (tmp.startsWith("/") && tmp.indexOf("denied") > 0))		    {		     length--;			     continue;		    }		                        tmp = to.nextToken();		    		    if(tmp.length() != 10)		    {		    	//System.out.println(tmp + " - e");		    	return null; // exotic bug, hardlinks are not found or something ("/bin/ls: dir: no such file or directy" in ls output) - we have no permissions then		    }		    		    char ur = tmp.charAt(1);		    char uw = tmp.charAt(2);		    char ar = tmp.charAt(7);		    char aw = tmp.charAt(8);		    to.nextToken();		    String user = to.nextToken();		    //System.out.println(""+ur+":"+ar+":"+tmp);		    if(aw == 'w')		    {		    	out.println("w");		    }		    else if(user.equals(username) && uw == 'w')		    {		    	out.println("w");		    }		    else if(ar == 'r')		    {		    	out.println("r");		    }		    else if(user.equals(username) && ur == 'r')		    {		    	out.println("r");		    }		    else		    {		    	//System.out.println(ur+":"+ar+":"+user+":"+username+":");		    	out.println("n");		    }            }	    out.flush();	    out.close();        }        catch(Exception ex)        {            Log.debug(ex.toString()+" @FtpConnection::getPermissions#1");        }        try        {            in = new BufferedReader(new FileReader(Settings.permissions_out));            //String[] files = new String[length];	    int ret[] = new int[length];	    String fx;            for(int i=0; i<length; i++)            {                fx = in.readLine();	    	if(fx.equals("w"))		{			ret[i] = W;		}	    	else if(fx.equals("n"))		{			ret[i] = DENIED;		}		else ret[i] = R;                //System.out.println(ret[i]);            }	    return ret;        }        catch(Exception ex)        {            Log.debug(ex.toString()+" @FtpConnection::getPermissions#2");        }        return new int[0];    }    /** parses the ls-output */    public String[] sortLs(String file)    {        try        {            BufferedReader in = new BufferedReader(new FileReader(file));            PrintStream out = new PrintStream(new FileOutputStream(Settings.sortls_out));            int length = 0;            while(true)            {                String tmp = in.readLine();                if(tmp == null) break;		// ------------------- VMS override --------------------	    	if(getOsType().startsWith("VMS"))		{			int x = tmp.indexOf(";");			if(x<0) continue;			tmp = tmp.substring(0,x);			;			if(tmp.endsWith("DIR"))			{				out.println(tmp.substring(0,tmp.lastIndexOf("."))+"/");			}			else			{				out.println(tmp);			}			length++;			continue;		}		// -------------------------------------------------------		// ------------------- Unix, Windows and others -----		boolean isDir = false;		boolean isLink = false;                if(tmp.startsWith("d") || tmp.indexOf("<DIR>") >= 0) isDir = true;                if(tmp.startsWith("l")) isLink = true;		if(tmp.startsWith("/") && tmp.indexOf("denied") > 0)	continue;                StringTokenizer to = new StringTokenizer(tmp," ",true);                int tokens = to.countTokens();                if (tokens > 8) // unix		{                       tmp = giveFile(to,8);                }		else if (tokens > 3) // old windows		{                       tmp = giveFile(to,4); // was: 3                } else		{		       continue;		}                if(isDir)                {                            tmp = tmp + "/";                } else if (isLink)		{		    	tmp = tmp + "###";		}		out.println(tmp);                length++;		// -------------------------------------------------------------            }            in = new BufferedReader(new FileReader(Settings.sortls_out));            String[] files = new String[length];            for(int i=0; i<length; i++)            {                files[i] = parseSymlink(in.readLine());            }            return files;        }        catch(Exception ex)        {            Log.debug(ex.toString()+" @FtpConnection::sortLs");        }        return new String[0];    }    /** get a filename */    private String giveFile(StringTokenizer to, int lev)    {        for(int i=0; i<lev; i++)        {            if(to.hasMoreTokens())            {                String t = to.nextToken();                if(t.equals(" ") || t.equals("\t"))                {                    i--;                }            }        }        String tmp = "<error>";        while(tmp.equals(" ") || tmp.equals("\t") || tmp.equals("<error>"))        {            if(to.hasMoreTokens())

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -