KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sf > jftp > net > SftpConnection


1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software
14  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
15  */

16 package net.sf.jftp.net;
17
18 import java.io.BufferedInputStream JavaDoc;
19 import java.io.BufferedOutputStream JavaDoc;
20 import java.io.File JavaDoc;
21 import java.io.FileInputStream JavaDoc;
22 import java.io.FileOutputStream JavaDoc;
23 import java.io.IOException JavaDoc;
24 import java.io.InputStream JavaDoc;
25 import java.io.StreamTokenizer JavaDoc;
26 import java.util.Date JavaDoc;
27 import java.util.Enumeration JavaDoc;
28 import java.util.Vector JavaDoc;
29
30 import javax.swing.JLabel JavaDoc;
31
32 import net.sf.jftp.config.Settings;
33 import net.sf.jftp.system.StringUtils;
34 import net.sf.jftp.system.logging.Log;
35
36 import com.sshtools.common.hosts.DialogHostKeyVerification;
37 import com.sshtools.j2ssh.SshClient;
38 import com.sshtools.j2ssh.authentication.AuthenticationProtocolState;
39 import com.sshtools.j2ssh.authentication.PasswordAuthenticationClient;
40 import com.sshtools.j2ssh.authentication.PublicKeyAuthenticationClient;
41 import com.sshtools.j2ssh.configuration.SshConnectionProperties;
42 import com.sshtools.j2ssh.sftp.SftpFile;
43 import com.sshtools.j2ssh.sftp.SftpFileInputStream;
44 import com.sshtools.j2ssh.sftp.SftpFileOutputStream;
45 import com.sshtools.j2ssh.sftp.SftpSubsystemClient;
46 import com.sshtools.j2ssh.transport.publickey.SshPrivateKey;
47 import com.sshtools.j2ssh.transport.publickey.SshPrivateKeyFile;
48
49
50 public class SftpConnection implements BasicConnection
51 {
52     public static int smbBuffer = 32000;
53     private String JavaDoc path = "";
54     private String JavaDoc pwd = "/";
55     private Vector JavaDoc listeners = new Vector JavaDoc();
56     private String JavaDoc[] files;
57     private String JavaDoc[] size = new String JavaDoc[0];
58     private int[] perms = null;
59     private String JavaDoc user;
60     private String JavaDoc pass;
61     private String JavaDoc host;
62     private String JavaDoc baseFile;
63     private int fileCount;
64     private boolean isDirUpload = false;
65     private boolean shortProgress = false;
66     private int RW = SftpSubsystemClient.OPEN_CREATE |
67                      SftpSubsystemClient.OPEN_WRITE;
68     private int W = SftpSubsystemClient.OPEN_CREATE;
69     private int R = SftpSubsystemClient.OPEN_READ;
70     private SftpSubsystemClient sftp = null;
71     private int port = 22;
72     private boolean connected = false;
73     private SshClient ssh = null;
74     private String JavaDoc keyfile = null;
75     
76     //private int timeout = 30000;
77

78     //private SessionChannelClient session = null;
79
private SshConnectionProperties properties = new SshConnectionProperties();
80
81     public SftpConnection(SshConnectionProperties properties)
82     {
83         this.properties = properties;
84         this.host = properties.getHost();
85         this.port = properties.getPort();
86     }
87
88     public SftpConnection(SshConnectionProperties properties, String JavaDoc keyfile)
89     {
90         this.properties = properties;
91         this.keyfile = keyfile;
92         this.host = properties.getHost();
93         this.port = properties.getPort();
94     }
95    
96 // seem to be broken, use the newer constructors
97
/*
98     public SftpConnection(String host)
99     {
100         this.host = host;
101         properties.setHost(host);
102     }
103
104     public SftpConnection(String host, int port)
105     {
106         this.host = host;
107         this.port = port;
108         properties.setHost(host);
109         properties.setPort(port);
110     }
111     */

112
113     private boolean login()
114     {
115         try
116         {
117             ssh = new SshClient();
118             //ssh.setSocketTimeout(timeout);
119
//ssh.setKexTimeout(timeout);
120

121             Log.debug("Host: "+properties.getHost()+":"+properties.getPort());
122
123             if(!Settings.getEnableSshKeys())
124             {
125                 ssh.connect(properties,//new IgnoreHostKeyVerification());
126
new SftpVerification(Settings.sshHostKeyVerificationFile));
127             }
128             else
129             {
130                 ssh.connect(properties,
131                             new DialogHostKeyVerification(new JLabel JavaDoc()));
132             }
133
134             int result = -1;
135
136             if(keyfile == null)
137             {
138                 //ssh.connect(host);
139
PasswordAuthenticationClient pwd = new PasswordAuthenticationClient();
140                 pwd.setUsername(user);
141                 pwd.setPassword(pass);
142
143                 result = ssh.authenticate(pwd);
144             }
145             else
146             {
147                 Log.out("keyfile-auth: " + keyfile);
148
149                 PublicKeyAuthenticationClient pk = new PublicKeyAuthenticationClient();
150                 pk.setUsername(user);
151
152                 SshPrivateKeyFile file = SshPrivateKeyFile.parse(new File JavaDoc(keyfile));
153                 SshPrivateKey key = file.toPrivateKey(pass);
154
155                 pk.setKey(key);
156                 result = ssh.authenticate(pk);
157             }
158
159             if(result == AuthenticationProtocolState.COMPLETE)
160             {
161                 //session = ssh.openSessionChannel();
162
//boolean ok = session.startSubsystem("sftp");
163
sftp = new SftpSubsystemClient();
164
165                 boolean ok = ssh.openChannel(sftp);
166
167                 boolean ok2 = sftp.startSubsystem();
168
169                 //Log.out("sftp sub ok: "+ok+" and "+ok2);
170
// newer api
171
//SftpClient sftp = ssh.openSftpClient();
172
connected = true;
173
174                 return true;
175             }
176             else
177             {
178                 return false;
179             }
180         }
181         catch(Exception JavaDoc ex)
182         {
183             ex.printStackTrace();
184             Log.debug("Error: " + ex);
185
186             return false;
187         }
188     }
189
190     public int removeFileOrDir(String JavaDoc file)
191     {
192         file = toSFTP(file);
193
194         try
195         {
196             SftpFile f;
197
198             if(!file.endsWith("/"))
199             {
200                 Log.out(">>>>>>>> remove file: " + file);
201                 f = sftp.openFile(file, RW);
202                 sftp.removeFile(file);
203                 //f.delete();
204
}
205             else
206             {
207                 Log.out(">>>>>>>> remove dir: " + file);
208                 f = sftp.openDirectory(file);
209                 cleanSftpDir(file, f);
210                 sftp.closeFile(f);
211                 sftp.removeDirectory(file);
212             }
213         }
214         catch(Exception JavaDoc ex)
215         {
216             ex.printStackTrace();
217             Log.debug("Removal failed (" + ex + ").");
218             ex.printStackTrace();
219
220             return -1;
221         }
222
223         return 1;
224     }
225
226     private void cleanSftpDir(String JavaDoc dir, SftpFile f2)
227                        throws Exception JavaDoc
228     {
229         Log.out(">>>>>>>> cleanSftpDir: " + dir);
230
231         Vector JavaDoc v = new Vector JavaDoc();
232
233         while(sftp.listChildren(f2, v) > 0)
234         {
235             ;
236         }
237
238         String JavaDoc[] tmp = new String JavaDoc[v.size()];
239         SftpFile[] f = new SftpFile[v.size()];
240         Enumeration JavaDoc e = v.elements();
241         int x = 0;
242
243         while(e.hasMoreElements())
244         {
245             f[x] = ((SftpFile) e.nextElement());
246             tmp[x] = f[x].getFilename();
247
248             //Log.out("sftp delete: " + tmp[x]);
249
//Log.out(">>>>>>>> remove file/dir: " + tmp[x]);
250
if(f[x].isDirectory() && !tmp[x].endsWith("/"))
251             {
252                 tmp[x] = tmp[x] + "/";
253             }
254
255             //sftp.closeFile(f[x]);
256
x++;
257         }
258
259         if(tmp == null)
260         {
261             return;
262         }
263
264         for(int i = 0; i < tmp.length; i++)
265         {
266             if(tmp[i].equals("./") || tmp[i].equals("../"))
267             {
268                 continue;
269             }
270
271             SftpFile f3;
272
273             //System.out.println(dir+tmp[i]);
274
if(tmp[i].endsWith("/"))
275             {
276                 f3 = sftp.openDirectory(dir + tmp[i]);
277             }
278             else
279             {
280                 f3 = sftp.openFile(dir + tmp[i], RW);
281             }
282
283             Log.out(">>>>>>>> remove file/dir: " + dir + tmp[i]);
284
285             if(f3.isDirectory())
286             {
287                 cleanSftpDir(dir + tmp[i], f3);
288
289                 //sftp.closeFile(f3);
290
sftp.removeDirectory(dir + tmp[i]);
291             }
292             else
293             {
294                 //f3.delete();
295
sftp.removeFile(dir + tmp[i]);
296             }
297         }
298     }
299
300     public void sendRawCommand(String JavaDoc cmd)
301     {
302     }
303
304     public void disconnect()
305     {
306         try
307         {
308             //sftp.stop();
309
//session.close();
310
ssh.disconnect();
311         }
312         catch(Exception JavaDoc e)
313         {
314             e.printStackTrace();
315             Log.debug("SftpSshClient.disconnect()" + e);
316         }
317
318         connected = false;
319     }
320
321     public boolean isConnected()
322     {
323         return connected;
324     }
325
326     public String JavaDoc getPWD()
327     {
328         //Log.debug("PWD: " + pwd);
329
return toSFTPDir(pwd);
330     }
331
332     public boolean mkdir(String JavaDoc dirName)
333     {
334         try
335         {
336             if(!dirName.endsWith("/"))
337             {
338                 dirName = dirName + "/";
339             }
340
341             dirName = toSFTP(dirName);
342
343             sftp.makeDirectory(dirName);
344
345             fireDirectoryUpdate();
346
347             return true;
348         }
349         catch(Exception JavaDoc ex)
350         {
351             Log.debug("Failed to create directory (" + ex + ").");
352
353             return false;
354         }
355     }
356
357     public void list() throws IOException JavaDoc
358     {
359     }
360
361     public boolean chdir(String JavaDoc p)
362     {
363         return chdir(p, true);
364     }
365
366     public boolean chdir(String JavaDoc p, boolean refresh)
367     {
368         String JavaDoc tmp = toSFTP(p);
369
370         try
371         {
372             if(!tmp.endsWith("/"))
373             {
374                 tmp = tmp + "/";
375             }
376
377             if(tmp.endsWith("../"))
378             {
379                 return cdup();
380             }
381
382             // Log.out("sftp path: "+tmp);
383
SftpFile f = sftp.openDirectory(tmp);
384
385             //Log.out("sftp after path...");
386
//if(!f.isDirectory()) return false;
387
sftp.closeFile(f);
388
389             pwd = toSFTP(f.getAbsolutePath());
390
391             //Log.debug("chdir: " + getPWD());
392
if(refresh)
393             {
394                 fireDirectoryUpdate();
395             }
396
397             //System.out.println("chdir2: " + getPWD());
398
//Log.debug("Changed path to: " + tmp);
399
return true;
400         }
401         catch(Exception JavaDoc ex)
402         {
403             ex.printStackTrace();
404
405             //System.out.println(tmp);
406
Log.debug("Could not change directory (" + ex + ").");
407
408             return false;
409         }
410     }
411
412     public boolean cdup()
413     {
414         String JavaDoc tmp = pwd;
415
416         if(pwd.endsWith("/"))
417         {
418             tmp = pwd.substring(0, pwd.lastIndexOf("/"));
419         }
420
421         return chdir(tmp.substring(0, tmp.lastIndexOf("/") + 1));
422     }
423
424     public boolean chdirNoRefresh(String JavaDoc p)
425     {
426         return chdir(p, false);
427     }
428
429     public String JavaDoc getLocalPath()
430     {
431         return path;
432     }
433
434     public boolean setLocalPath(String JavaDoc p)
435     {
436         if(StringUtils.isRelative(p))
437         {
438             p = path + p;
439         }
440
441         p = p.replace('\\', '/');
442
443         //System.out.println(", local 2:" + p);
444
File JavaDoc f = new File JavaDoc(p);
445
446         if(f.exists())
447         {
448             try
449             {
450                 path = f.getCanonicalPath();
451                 path = path.replace('\\', '/');
452
453                 if(!path.endsWith("/"))
454                 {
455                     path = path + "/";
456                 }
457
458                 //System.out.println("localPath: "+path);
459
}
460             catch(IOException JavaDoc ex)
461             {
462                 Log.debug("Error: can not get pathname (local)!");
463
464                 return false;
465             }
466         }
467         else
468         {
469             Log.debug("(local) No such path: \"" + p + "\"");
470
471             return false;
472         }
473
474         return true;
475     }
476
477     public String JavaDoc[] sortLs()
478     {
479         try
480         {
481             String JavaDoc t = getPWD();
482
483             SftpFile fx = sftp.openDirectory(t);
484
485             //if(fx == null) System.out.println("Sftp: fx null");
486
Vector JavaDoc v = new Vector JavaDoc();
487
488             while(sftp.listChildren(fx, v) > 0)
489             {
490                 ;
491             }
492
493             String JavaDoc[] tmp = new String JavaDoc[v.size()];
494             SftpFile[] f = new SftpFile[v.size()];
495             files = new String JavaDoc[tmp.length];
496             size = new String JavaDoc[tmp.length];
497             perms = new int[tmp.length];
498
499             Enumeration JavaDoc e = v.elements();
500             int x = 0;
501
502             while(e.hasMoreElements())
503             {
504                 f[x] = ((SftpFile) e.nextElement());
505                 tmp[x] = f[x].getFilename();
506
507                 size[x] = f[x].getAttributes().getSize().toString();
508
509                 //if(f[x].canWrite()) Log.debug(tmp[x]);
510
//if(f[x].canWrite()) perms[x] = FtpConnection.W;
511
//else
512
if(!f[x].canRead())
513                 {
514                     perms[x] = FtpConnection.DENIED;
515                 }
516                 else
517                 {
518                     perms[x] = FtpConnection.R;
519                 }
520
521                 //Log.debugRaw(".");
522
if(f[x].isDirectory() && !tmp[x].endsWith("/"))
523                 {
524                     tmp[x] = tmp[x] + "/";
525                 }
526
527                 x++;
528             }
529
530             sftp.closeFile(fx);
531
532             for(int i = 0; i < tmp.length; i++)
533             {
534                 files[i] = tmp[i];
535             }
536
537             //Log.debug(" done.");
538
return files;
539         }
540         catch(Exception JavaDoc ex)
541         {
542             //ex.printStackTrace();
543
//Log.debug(" Error while listing directory: " + ex);
544
return new String JavaDoc[0];
545         }
546     }
547
548     public String JavaDoc[] sortSize()
549     {
550         return size;
551     }
552
553     public int[] getPermissions()
554     {
555         return perms;
556     }
557
558     public int handleUpload(String JavaDoc f)
559     {
560         if(Settings.getEnableSftpMultiThreading())
561         {
562             SftpTransfer t = new SftpTransfer(properties, getLocalPath(), getPWD(),
563                                               f, user, pass, listeners,
564                                               Transfer.UPLOAD, keyfile);
565         }
566         else
567         {
568             upload(f);
569         }
570
571         return 0;
572     }
573
574     public int handleDownload(String JavaDoc f)
575     {
576         if(Settings.getEnableSftpMultiThreading())
577         {
578             SftpTransfer t = new SftpTransfer(properties, getLocalPath(), getPWD(),
579                                               f, user, pass, listeners,
580                                               Transfer.DOWNLOAD, keyfile);
581         }
582         else
583         {
584             download(f);
585         }
586
587         return 0;
588     }
589
590     public int upload(String JavaDoc f)
591     {
592         String JavaDoc file = toSFTP(f);
593
594         if(file.endsWith("/"))
595         {
596             String JavaDoc out = StringUtils.getDir(file);
597             uploadDir(file, getLocalPath() + out);
598             fireActionFinished(this);
599         }
600         else
601         {
602             String JavaDoc outfile = StringUtils.getFile(file);
603
604             //System.out.println("transfer: " + file + ", " + getLocalPath() + outfile);
605
work(getLocalPath() + outfile, file, true);
606             fireActionFinished(this);
607         }
608
609         return 0;
610     }
611
612     public int download(String JavaDoc f)
613     {
614         String JavaDoc file = toSFTP(f);
615
616         if(file.endsWith("/"))
617         {
618             String JavaDoc out = StringUtils.getDir(file);
619             downloadDir(file, getLocalPath() + out);
620             fireActionFinished(this);
621         }
622         else
623         {
624             String JavaDoc outfile = StringUtils.getFile(file);
625
626             //System.out.println("transfer: " + file + ", " + getLocalPath() + outfile);
627
work(file, getLocalPath() + outfile, false);
628             fireActionFinished(this);
629         }
630
631         return 0;
632     }
633
634     private void downloadDir(String JavaDoc dir, String JavaDoc out)
635     {
636         try
637         {
638             //System.out.println("downloadDir: " + dir + "," + out);
639
fileCount = 0;
640             shortProgress = true;
641             baseFile = StringUtils.getDir(dir);
642
643             SftpFile f2 = sftp.openDirectory(dir);
644
645             Vector JavaDoc v = new Vector JavaDoc();
646
647             while(sftp.listChildren(f2, v) > 0)
648             {
649                 ;
650             }
651
652             String JavaDoc[] tmp = new String JavaDoc[v.size()];
653             SftpFile[] f = new SftpFile[v.size()];
654             Enumeration JavaDoc e = v.elements();
655             int x = 0;
656
657             while(e.hasMoreElements())
658             {
659                 f[x] = ((SftpFile) e.nextElement());
660                 tmp[x] = f[x].getFilename();
661                 Log.debugRaw(".");
662
663                 if(f[x].isDirectory() && !tmp[x].endsWith("/"))
664                 {
665                     tmp[x] = tmp[x] + "/";
666                 }
667
668                 //sftp.closeFile(f[x]);
669
x++;
670             }
671
672             //sftp.closeFile(f2);
673
File JavaDoc fx = new File JavaDoc(out);
674             fx.mkdir();
675
676             for(int i = 0; i < tmp.length; i++)
677             {
678                 if(tmp[i].equals("./") || tmp[i].equals("../"))
679                 {
680                     continue;
681                 }
682
683                 tmp[i] = tmp[i].replace('\\', '/');
684
685                 //System.out.println("1: " + dir+tmp[i] + ", " + out +tmp[i]);
686
SftpFile f3 = sftp.openFile(dir + tmp[i], R);
687
688                 if(f3.isDirectory())
689                 {
690                     if(!tmp[i].endsWith("/"))
691                     {
692                         tmp[i] = tmp[i] + "/";
693                     }
694
695                     downloadDir(dir + tmp[i], out + tmp[i]);
696                 }
697                 else
698                 {
699                     fileCount++;
700                     fireProgressUpdate(baseFile,
701                                        DataConnection.GETDIR + ":" + fileCount,
702                                        -1);
703                     work(dir + tmp[i], out + tmp[i], false);
704                 }
705
706                 //sftp.closeFile(f3);
707
}
708
709             fireProgressUpdate(baseFile,
710                                DataConnection.DFINISHED + ":" + fileCount, -1);
711         }
712         catch(Exception JavaDoc ex)
713         {
714             ex.printStackTrace();
715             System.out.println(dir + ", " + out);
716             Log.debug("Transfer error: " + ex);
717             fireProgressUpdate(baseFile,
718                                DataConnection.FAILED + ":" + fileCount, -1);
719         }
720
721         shortProgress = false;
722     }
723
724     private void uploadDir(String JavaDoc dir, String JavaDoc out)
725     {
726         try
727         {
728             //System.out.println("uploadDir: " + dir + "," + out);
729
isDirUpload = true;
730             fileCount = 0;
731             shortProgress = true;
732             baseFile = StringUtils.getDir(dir);
733
734             File JavaDoc f2 = new File JavaDoc(out);
735             String JavaDoc[] tmp = f2.list();
736
737             if(tmp == null)
738             {
739                 return;
740             }
741
742             sftp.makeDirectory(dir);
743             sftp.changePermissions(dir, "rwxr--r--");
744
745             for(int i = 0; i < tmp.length; i++)
746             {
747                 if(tmp[i].equals("./") || tmp[i].equals("../"))
748                 {
749                     continue;
750                 }
751
752                 tmp[i] = tmp[i].replace('\\', '/');
753
754                 //System.out.println("1: " + dir+tmp[i] + ", " + out +tmp[i]);
755
File JavaDoc f3 = new File JavaDoc(out + tmp[i]);
756
757                 if(f3.isDirectory())
758                 {
759                     if(!tmp[i].endsWith("/"))
760                     {
761                         tmp[i] = tmp[i] + "/";
762                     }
763
764                     uploadDir(dir + tmp[i], out + tmp[i]);
765                 }
766                 else
767                 {
768                     fileCount++;
769                     fireProgressUpdate(baseFile,
770                                        DataConnection.PUTDIR + ":" + fileCount,
771                                        -1);
772                     work(out + tmp[i], dir + tmp[i], true);
773                 }
774             }
775
776             fireProgressUpdate(baseFile,
777                                DataConnection.DFINISHED + ":" + fileCount, -1);
778         }
779         catch(Exception JavaDoc ex)
780         {
781             ex.printStackTrace();
782             System.out.println(dir + ", " + out);
783             Log.debug("Transfer error: " + ex);
784             fireProgressUpdate(baseFile,
785                                DataConnection.FAILED + ":" + fileCount, -1);
786         }
787
788         isDirUpload = false;
789         shortProgress = true;
790     }
791
792     private String JavaDoc toSFTP(String JavaDoc f)
793     {
794         String JavaDoc file;
795
796         if(f.startsWith("/"))
797         {
798             file = f;
799         }
800         else
801         {
802             file = getPWD() + f;
803         }
804
805         file = file.replace('\\', '/');
806
807         //System.out.println("file: "+file);
808
return file;
809     }
810
811     private String JavaDoc toSFTPDir(String JavaDoc f)
812     {
813         String JavaDoc file;
814
815         if(f.startsWith("/"))
816         {
817             file = f;
818         }
819         else
820         {
821             file = pwd + f;
822         }
823
824         file = file.replace('\\', '/');
825
826         if(!file.endsWith("/"))
827         {
828             file = file + "/";
829         }
830
831         //System.out.println("file: "+file);
832
return file;
833     }
834
835     private void work(String JavaDoc file, String JavaDoc outfile, boolean up)
836     {
837         BufferedInputStream JavaDoc in = null;
838         BufferedOutputStream JavaDoc out = null;
839
840         try
841         {
842             SftpFile inf = null;
843             SftpFile of = null;
844             boolean outflag = false;
845
846             if(up)
847             {
848                 in = new BufferedInputStream JavaDoc(new FileInputStream JavaDoc(file));
849             }
850             else
851             {
852                 inf = sftp.openFile(file, R);
853                 in = new BufferedInputStream JavaDoc(new SftpFileInputStream(inf));
854             }
855
856             if(up)
857             {
858                 outflag = true;
859
860                 //FileAttributes fa = new FileAttributes();
861
//fa.setPermissions("rwxr--r--");
862
//fa.setSize(new UnsignedInteger64(
863
// new java.math.BigInteger(""+new File(file).length())));
864

865                 //of = sftp.openFile(outfile, W);
866
//of.delete();
867
try {
868                     sftp.removeFile(outfile);
869                 }
870                 catch(Exception JavaDoc ex) {
871                     
872                 }
873
874                 of = sftp.openFile(outfile, RW); // , fa);
875
sftp.changePermissions(of, "rwxr--r--");
876                 out = new BufferedOutputStream JavaDoc(new SftpFileOutputStream(of));
877             }
878             else
879             {
880                 out = new BufferedOutputStream JavaDoc(new FileOutputStream JavaDoc(outfile));
881             }
882
883             //System.out.println("out: " + outfile + ", in: " + file);
884
byte[] buf = new byte[smbBuffer];
885             int len = 0;
886             int reallen = 0;
887
888             //System.out.println(file+":"+getLocalPath()+outfile);
889
while(true)
890             {
891                 len = in.read(buf);
892
893                 //System.out.print(".");
894
if(len == StreamTokenizer.TT_EOF)
895                 {
896                     break;
897                 }
898
899                 out.write(buf, 0, len);
900                 reallen += len;
901
902                 //System.out.println(file + ":" + StringUtils.getFile(file));
903
if(outflag)
904                 {
905                     fireProgressUpdate(StringUtils.getFile(outfile),
906                                        DataConnection.PUT, reallen);
907                 }
908                 else
909                 {
910                     fireProgressUpdate(StringUtils.getFile(file),
911                                        DataConnection.GET, reallen);
912                 }
913             }
914
915             fireProgressUpdate(file, DataConnection.FINISHED, -1);
916         }
917         catch(IOException JavaDoc ex)
918         {
919             ex.printStackTrace();
920             Log.debug("Error with file IO (" + ex + ")!");
921             fireProgressUpdate(file, DataConnection.FAILED, -1);
922         }
923         finally
924         {
925             try
926             {
927                 out.flush();
928                 out.close();
929                 in.close();
930             }
931             catch(Exception JavaDoc ex)
932             {
933                 ex.printStackTrace();
934             }
935         }
936     }
937
938     public boolean rename(String JavaDoc oldName, String JavaDoc newName)
939     {
940         try
941         {
942             oldName = toSFTP(oldName);
943             newName = toSFTP(newName);
944
945             SftpFile f = sftp.openFile(oldName, RW);
946             f.rename(newName);
947
948             return true;
949         }
950         catch(Exception JavaDoc ex)
951         {
952             ex.printStackTrace();
953
954             Log.debug("Could rename file (" + ex + ").");
955
956             return false;
957         }
958     }
959
960     private void update(String JavaDoc file, String JavaDoc type, int bytes)
961     {
962         if(listeners == null)
963         {
964             return;
965         }
966         else
967         {
968             for(int i = 0; i < listeners.size(); i++)
969             {
970                 ConnectionListener listener = (ConnectionListener) listeners.elementAt(i);
971                 listener.updateProgress(file, type, bytes);
972             }
973         }
974     }
975
976     public void addConnectionListener(ConnectionListener l)
977     {
978         listeners.add(l);
979     }
980
981     public void setConnectionListeners(Vector JavaDoc l)
982     {
983         listeners = l;
984     }
985
986     /** remote directory has changed */
987     public void fireDirectoryUpdate()
988     {
989         if(listeners == null)
990         {
991             return;
992         }
993         else
994         {
995             for(int i = 0; i < listeners.size(); i++)
996             {
997                 ((ConnectionListener) listeners.elementAt(i)).updateRemoteDirectory(this);
998             }
999         }
1000    }
1001
1002    public boolean login(String JavaDoc user, String JavaDoc pass)
1003    {
1004        this.user = user;
1005        this.pass = pass;
1006
1007        if(!login())
1008        {
1009            Log.debug("Login failed.");
1010
1011            return false;
1012        }
1013        else
1014        {
1015            Log.debug("Authed successfully.");
1016
1017            //if(!chdir(getPWD())) chdir("/");
1018
}
1019
1020        return true;
1021    }
1022
1023    /** progress update */
1024    public void fireProgressUpdate(String JavaDoc file, String JavaDoc type, int bytes)
1025    {
1026        if(listeners == null)
1027        {
1028            return;
1029        }
1030
1031        for(int i = 0; i < listeners.size(); i++)
1032        {
1033            ConnectionListener listener = (ConnectionListener) listeners.elementAt(i);
1034
1035            if(shortProgress && Settings.shortProgress)
1036            {
1037                if(type.startsWith(DataConnection.DFINISHED))
1038                {
1039                    listener.updateProgress(baseFile,
1040                                            DataConnection.DFINISHED + ":" +
1041                                            fileCount, bytes);
1042                }
1043                else if(isDirUpload)
1044                {
1045                    listener.updateProgress(baseFile,
1046                                            DataConnection.PUTDIR + ":" +
1047                                            fileCount, bytes);
1048                }
1049                else
1050                {
1051                    listener.updateProgress(baseFile,
1052                                            DataConnection.GETDIR + ":" +
1053                                            fileCount, bytes);
1054                }
1055            }
1056            else
1057            {
1058                listener.updateProgress(file, type, bytes);
1059            }
1060        }
1061    }
1062
1063    public void fireActionFinished(SftpConnection con)
1064    {
1065        if(listeners == null)
1066        {
1067            return;
1068        }
1069        else
1070        {
1071            for(int i = 0; i < listeners.size(); i++)
1072            {
1073                ((ConnectionListener) listeners.elementAt(i)).actionFinished(con);
1074            }
1075        }
1076    }
1077
1078    public int upload(String JavaDoc file, InputStream JavaDoc i)
1079    {
1080        BufferedOutputStream JavaDoc out = null;
1081        BufferedInputStream JavaDoc in = null;
1082
1083        try
1084        {
1085            file = toSFTP(file);
1086
1087            SftpFile of = sftp.openFile(file, RW);
1088
1089            //of.delete();
1090
//of = sftp.openFile(file, RW);
1091
sftp.changePermissions(of, "rwxr--r--");
1092
1093            out = new BufferedOutputStream JavaDoc(new SftpFileOutputStream(of));
1094            in = new BufferedInputStream JavaDoc(i);
1095
1096            //Log.debug(getLocalPath() + ":" + file+ ":"+getPWD());
1097
byte[] buf = new byte[smbBuffer];
1098            int len = 0;
1099            int reallen = 0;
1100
1101            while(true)
1102            {
1103                len = in.read(buf);
1104
1105                //System.out.print(".");
1106
if(len == StreamTokenizer.TT_EOF)
1107                {
1108                    break;
1109                }
1110
1111                out.write(buf, 0, len);
1112                reallen += len;
1113
1114                fireProgressUpdate(StringUtils.getFile(file),
1115                                   DataConnection.PUT, reallen);
1116            }
1117
1118            //byte[] fin = new byte[1];
1119
//fin[0] = -1;
1120
//out.write(fin, 0, 1);
1121

1122            /*
1123            try {
1124                out.flush();
1125                out.close();
1126            } catch(Exception ex) {
1127                Log.out("flush: "+ex);
1128            }
1129            */

1130            
1131            fireProgressUpdate(file, DataConnection.FINISHED, -1);
1132
1133            return 0;
1134        }
1135        catch(IOException JavaDoc ex)
1136        {
1137            ex.printStackTrace();
1138            Log.debug("Error with file IO (" + ex + ")!");
1139            fireProgressUpdate(file, DataConnection.FAILED, -1);
1140
1141            return -1;
1142        }
1143        finally
1144        {
1145            try
1146            {
1147                out.flush();
1148                out.close();
1149                in.close();
1150            }
1151            catch(Exception JavaDoc ex)
1152            {
1153                ex.printStackTrace();
1154            }
1155        }
1156    }
1157
1158    public InputStream JavaDoc getDownloadInputStream(String JavaDoc file)
1159    {
1160        try
1161        {
1162            file = toSFTP(file);
1163
1164            SftpFile inf = sftp.openFile(file, R);
1165
1166            return new SftpFileInputStream(inf);
1167        }
1168        catch(IOException JavaDoc ex)
1169        {
1170            ex.printStackTrace();
1171            Log.debug(ex.toString() +
1172                      " @SftpConnection::getDownloadInputStream");
1173
1174            return null;
1175        }
1176    }
1177
1178    public Date JavaDoc[] sortDates()
1179    {
1180        return null;
1181    }
1182}
1183
Popular Tags