KickJava   Java API By Example, From Geeks To Geeks.

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


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.FileOutputStream JavaDoc;
22 import java.io.IOException JavaDoc;
23 import java.io.InputStream JavaDoc;
24 import java.io.StreamTokenizer JavaDoc;
25 import java.util.Date JavaDoc;
26 import java.util.Vector JavaDoc;
27
28 import net.sf.jftp.config.Settings;
29 import net.sf.jftp.system.StringUtils;
30 import net.sf.jftp.system.logging.Log;
31
32 import org.apache.commons.httpclient.HttpException;
33 import org.apache.commons.httpclient.HttpURL;
34 import org.apache.webdav.lib.WebdavFile;
35 import org.apache.webdav.lib.WebdavResource;
36
37
38 public class WebdavConnection implements BasicConnection
39 {
40     public static int webdavBuffer = 32000;
41     private String JavaDoc path = "";
42     private String JavaDoc pwd = "";
43     private Vector JavaDoc listeners = new Vector JavaDoc();
44     private String JavaDoc[] files;
45     private String JavaDoc[] size = new String JavaDoc[0];
46     private int[] perms = null;
47     private String JavaDoc baseFile;
48     private int fileCount;
49     private boolean shortProgress = false;
50     private String JavaDoc user;
51     private String JavaDoc pass;
52
53     public WebdavConnection(String JavaDoc path, String JavaDoc user, String JavaDoc pass,
54                             ConnectionListener l)
55     {
56         this.user = user;
57         this.pass = pass;
58
59         listeners.add(l);
60         chdir(path);
61     }
62
63     public int removeFileOrDir(String JavaDoc file)
64     {
65         Log.debug("Feature is not implemented yet");
66
67         if(true)
68         {
69             return -1;
70         }
71
72         try
73         {
74             if((file == null) || file.equals(""))
75             {
76                 return -1;
77             }
78
79             String JavaDoc tmp = file;
80
81             if(StringUtils.isRelative(file))
82             {
83                 tmp = getPWD() + file;
84             }
85
86             WebdavFile f = new WebdavFile(getURL(tmp));
87
88             if(!f.getAbsolutePath().equals(f.getCanonicalPath()))
89             {
90                 //Log.debug("WARNING: Symlink removed");//Skipping symlink, remove failed.");
91
//Log.debug("This is necessary to prevent possible data loss when removing those symlinks.");
92
//return -1;
93
if(!f.delete())
94                 {
95                     return -1;
96                 }
97             }
98
99             if(f.exists() && f.isDirectory())
100             {
101                 cleanLocalDir(tmp);
102             }
103
104             //System.out.println(tmp);
105
if(!f.delete())
106             {
107                 Log.debug("Removal failed.");
108
109                 return -1;
110             }
111         }
112         catch(Exception JavaDoc ex)
113         {
114             Log.debug("Error: " + ex.toString());
115             ex.printStackTrace();
116         }
117
118         return -1;
119     }
120
121     private void cleanLocalDir(String JavaDoc dir)
122     {
123         try
124         {
125             dir = dir.replace('\\', '/');
126
127             if(!dir.endsWith("/"))
128             {
129                 dir = dir + "/";
130             }
131
132             //String remoteDir = StringUtils.removeStart(dir,path);
133
//System.out.println(">>> " + dir);
134
WebdavFile f2 = new WebdavFile(getURL(dir));
135             String JavaDoc[] tmp = f2.list();
136
137             if(tmp == null)
138             {
139                 return;
140             }
141
142             for(int i = 0; i < tmp.length; i++)
143             {
144                 WebdavFile f3 = new WebdavFile(getURL(dir + tmp[i]));
145
146                 if(!f3.getAbsolutePath().equals(f3.getCanonicalPath()))
147                 {
148                     //Log.debug("WARNING: Symlink remove");//Skipping symlink, remove may fail.");
149
f3.delete();
150
151                     //Log.debug("This is necessary to prevent possible data loss when removing those symlinks.");
152
//continue;
153
}
154
155                 if(f3.isDirectory())
156                 {
157                     //System.out.println(dir);
158
cleanLocalDir(dir + tmp[i]);
159                     f3.delete();
160                 }
161                 else
162                 {
163                     //System.out.println(dir+tmp[i]);
164
f3.delete();
165                 }
166             }
167         }
168         catch(Exception JavaDoc ex)
169         {
170             Log.debug("Error: " + ex.toString());
171             ex.printStackTrace();
172         }
173     }
174
175     public void sendRawCommand(String JavaDoc cmd)
176     {
177     }
178
179     public void disconnect()
180     {
181     }
182
183     public boolean isConnected()
184     {
185         return true;
186     }
187
188     public String JavaDoc getPWD()
189     {
190         return pwd;
191     }
192
193     public boolean cdup()
194     {
195         return chdir(pwd.substring(0, pwd.lastIndexOf("/") + 1));
196     }
197
198     public boolean mkdir(String JavaDoc dirName)
199     {
200         Log.debug("Feature is not implemented yet");
201
202         if(true)
203         {
204             return false;
205         }
206
207         try
208         {
209             if(StringUtils.isRelative(dirName))
210             {
211                 dirName = getPWD() + dirName;
212             }
213
214             WebdavFile f = new WebdavFile(getURL(dirName));
215
216             boolean x = f.mkdir();
217             fireDirectoryUpdate();
218
219             return x;
220         }
221         catch(Exception JavaDoc ex)
222         {
223             Log.debug("Error: " + ex.toString());
224             ex.printStackTrace();
225
226             return false;
227         }
228     }
229
230     public void list() throws IOException JavaDoc
231     {
232     }
233
234     public boolean chdir(String JavaDoc p)
235     {
236         try
237         {
238             String JavaDoc p2 = processPath(p);
239
240             if(p2 == null)
241             {
242                 return false;
243             }
244
245             //WebdavFile f = new WebdavFile(getURL(p2));
246
WebdavResource f = getResource(p2);
247
248             if(!f.exists() || !f.isCollection()) //!f.isDirectory() || !f.canRead())
249
{
250                 Log.debug("Access denied.");
251
252                 return false;
253             }
254
255             pwd = p2;
256
257             Log.out("PWD: " + pwd);
258
259             fireDirectoryUpdate();
260
261             return true;
262         }
263         catch(Exception JavaDoc ex)
264         {
265             Log.debug("Error: " + ex.toString());
266             ex.printStackTrace();
267
268             return false;
269         }
270     }
271
272     public boolean chdirNoRefresh(String JavaDoc p)
273     {
274         String JavaDoc p2 = processPath(p);
275
276         if(p2 == null)
277         {
278             return false;
279         }
280
281         //System.out.println(p2);
282
pwd = p2;
283
284         return true;
285     }
286
287     public String JavaDoc getLocalPath()
288     {
289         //System.out.println("local: " + path);
290
return path;
291     }
292
293     public String JavaDoc processPath(String JavaDoc p)
294     {
295         try
296         {
297             if(!p.startsWith("http://"))
298             {
299                 p = pwd + p;
300             }
301
302             if(!p.endsWith("/"))
303             {
304                 p = p + "/";
305             }
306
307             while(p.endsWith("/../"))
308             {
309                 p = p.substring(0, p.lastIndexOf("/../") - 1);
310                 p = p.substring(0, p.lastIndexOf("/"));
311             }
312
313             while(p.endsWith("/./"))
314             {
315                 p = p.substring(0, p.lastIndexOf("/./") - 1);
316                 p = p.substring(0, p.lastIndexOf("/"));
317             }
318
319             //System.out.println(", processPath 2: "+p);
320
//WebdavFile f = new WebdavFile(getURL(p));
321
Log.out("\n\n\nprocessPath URL: " + p);
322
323             WebdavResource f = getResource(p);
324             String JavaDoc p2 = p;
325
326             if(f.exists() && f.isCollection())
327             {
328                 try
329                 {
330                     //p2 = f.toURL(); //CanonicalPath();
331
if(!p2.endsWith("/"))
332                     {
333                         p2 = p2 + "/";
334                     }
335
336                     //Log.out("processPath parsed URL: " + p);
337
//Log.out("processPath URL2: " + f.getPath());
338
return p2;
339                 }
340                 catch(Exception JavaDoc ex)
341                 {
342                     Log.debug("Error: can not get pathname (processPath)!");
343
344                     return null;
345                 }
346             }
347             else
348             {
349                 Log.debug("(processpPath) No such path: \"" + p + "\"");
350
351                 return null;
352             }
353         }
354         catch(Exception JavaDoc ex)
355         {
356             Log.debug("Error: " + ex.toString());
357             ex.printStackTrace();
358
359             return null;
360         }
361     }
362
363     public boolean setLocalPath(String JavaDoc p)
364     {
365         try
366         {
367             p = p.replace('\\', '/');
368
369             //System.out.print("local 1:" + p);
370
if(StringUtils.isRelative(p))
371             {
372                 p = path + p;
373             }
374
375             p = p.replace('\\', '/');
376
377             //System.out.println(", local 2:" + p);
378
File JavaDoc f = new File JavaDoc(p);
379
380             if(f.exists())
381             {
382                 try
383                 {
384                     path = f.getCanonicalPath();
385                     path = path.replace('\\', '/');
386
387                     if(!path.endsWith("/"))
388                     {
389                         path = path + "/";
390                     }
391
392                     //System.out.println("localPath: "+path);
393
}
394                 catch(Exception JavaDoc ex)
395                 {
396                     Log.debug("Error: can not get pathname (local)!");
397
398                     return false;
399                 }
400             }
401             else
402             {
403                 Log.debug("(local) No such path: \"" + p + "\"");
404
405                 return false;
406             }
407
408             return true;
409         }
410         catch(Exception JavaDoc ex)
411         {
412             Log.debug("Error: " + ex.toString());
413             ex.printStackTrace();
414
415             return false;
416         }
417     }
418
419     public String JavaDoc[] sortLs()
420     {
421         try
422         {
423             Log.out("sortLs PWD: " + pwd);
424
425             //WebdavFile fl = new WebdavFile(new URL(pwd), user, pass);
426
WebdavResource fp = getResource(pwd);
427
428             //new WebdavResource(getURL(pwd));
429
//files = f.list();
430
//File[] f = fl.listFiles();
431
WebdavResource[] f = fp.listWebdavResources();
432
433             //if(files == null) return new String[0];
434
files = new String JavaDoc[f.length];
435             size = new String JavaDoc[f.length];
436             perms = new int[f.length];
437
438             int accessible = 0;
439
440             for(int i = 0; i < f.length; i++)
441             {
442                 files[i] = f[i].getName();
443
444                 /*
445                 while(files[i].indexOf("%20") >= 0)
446                 {
447                         int x = files[i].indexOf("%20");
448                         String tmp = files[i].substring(0,x)+" "+
449                                         files[i].substring(files[i].indexOf("%20")+3);
450                         files[i] = tmp;
451                 }
452                 */

453                 /*
454                 try
455                 {
456                         f[i].exists();
457                 }
458                 catch(Exception ex)
459                 {
460                         Log.debug("ERROR: parsing problem with:" + files[i]);
461                         size[i] = "-1";
462                         perms[i] = FtpConnection.DENIED;
463                         continue;
464                 }
465                 */

466                 Log.out("sortLs files[" + i + "]: " + files[i]);
467
468                 //size[i] = "" + (int) f[i].length();
469
size[i] = "" + (int) f[i].getGetContentLength();
470                 perms[i] = FtpConnection.R;
471
472                 if(f[i].isCollection() && !files[i].endsWith("/"))
473                 {
474                     files[i] = files[i] + "/";
475                 }
476
477                 /*
478                 if(f[i].canWrite()) accessible = FtpConnection.W;
479                 else if(f[i].canRead()) accessible = FtpConnection.R;
480                 else accessible = FtpConnection.DENIED;
481                 perms[i] = accessible;
482
483                 Log.out("sortLs files["+i+"]: " + files[i]);
484                 WebdavFile f2 = new WebdavFile(new URL(files[i]), user, pass);
485
486                 if(!f2.exists()) continue;
487                 if(f2.isDirectory() && !files[i].endsWith("/")) files[i] = files[i] + "/";
488
489                 size[i] = "" + new WebdavFile(new URL(files[i]), user, pass).length();
490                 */

491             }
492
493             return files;
494         }
495         catch(Exception JavaDoc ex)
496         {
497             Log.debug("Error: " + ex.toString());
498             ex.printStackTrace();
499
500             return new String JavaDoc[0];
501         }
502     }
503
504     public String JavaDoc[] sortSize()
505     {
506         return size;
507     }
508
509     public int[] getPermissions()
510     {
511         return perms;
512     }
513
514     public int handleDownload(String JavaDoc file)
515     {
516         transfer(file);
517
518         return 0;
519     }
520
521     public int handleUpload(String JavaDoc file)
522     {
523         transfer(file, true);
524
525         return 0;
526     }
527
528     public int download(String JavaDoc file)
529     {
530         transfer(file);
531
532         return 0;
533     }
534
535     public int upload(String JavaDoc file)
536     {
537         transfer(file, true);
538
539         return 0;
540     }
541
542     private void transferDir(String JavaDoc dir, String JavaDoc out)
543     {
544         try
545         {
546             fileCount = 0;
547             shortProgress = true;
548             baseFile = StringUtils.getDir(dir);
549
550             WebdavFile f2 = new WebdavFile(getURL(dir));
551             String JavaDoc[] tmp = f2.list();
552
553             if(tmp == null)
554             {
555                 return;
556             }
557
558             WebdavFile fx = new WebdavFile(getURL(out));
559
560             if(!fx.mkdir())
561             {
562                 Log.debug("Can not create directory: " + out +
563                           " - already exist or permission denied?");
564             }
565
566             for(int i = 0; i < tmp.length; i++)
567             {
568                 tmp[i] = tmp[i].replace('\\', '/');
569
570                 //System.out.println("1: " + dir+tmp[i] + ", " + out +tmp[i]);
571
WebdavFile f3 = new WebdavFile(getURL(dir + tmp[i]));
572
573                 if(f3.isDirectory())
574                 {
575                     if(!tmp[i].endsWith("/"))
576                     {
577                         tmp[i] = tmp[i] + "/";
578                     }
579
580                     transferDir(dir + tmp[i], out + tmp[i]);
581                 }
582                 else
583                 {
584                     fireProgressUpdate(baseFile,
585                                        DataConnection.GETDIR + ":" + fileCount,
586                                        -1);
587                     work(dir + tmp[i], out + tmp[i]);
588                 }
589             }
590
591             fireProgressUpdate(baseFile,
592                                DataConnection.DFINISHED + ":" + fileCount, -1);
593             shortProgress = false;
594         }
595         catch(Exception JavaDoc ex)
596         {
597             Log.debug("Error: " + ex.toString());
598             ex.printStackTrace();
599         }
600     }
601
602     private HttpURL getURL(String JavaDoc u)
603     {
604         try
605         {
606             HttpURL url = new HttpURL(u);
607
608             //System.out.println(user + ":"+ pass);
609
url.setUserinfo(user, pass);
610
611             return url;
612         }
613         catch(Exception JavaDoc ex)
614         {
615             ex.printStackTrace();
616             Log.debug("ERROR: " + ex);
617
618             return null;
619         }
620     }
621
622     private WebdavResource getResource(String JavaDoc res)
623                                 throws HttpException, IOException JavaDoc
624     {
625         return new WebdavResource(getURL(res));
626     }
627
628     private void transfer(String JavaDoc file)
629     {
630         transfer(file, false);
631     }
632
633     private void transfer(String JavaDoc file, boolean up)
634     {
635         String JavaDoc out = StringUtils.getDir(file);
636
637         if(StringUtils.isRelative(file))
638         {
639             file = getPWD() + file;
640         }
641
642         file = file.replace('\\', '/');
643         out = out.replace('\\', '/');
644
645         String JavaDoc outfile = StringUtils.getFile(file);
646
647         if(file.endsWith("/"))
648         {
649             if(up)
650             {
651                 Log.debug("Directory upload not implemented yet.");
652
653                 return;
654             }
655
656             transferDir(file, getLocalPath() + out);
657
658             return;
659         }
660         else
661         {
662             if(up)
663             {
664                 work(getLocalPath() + outfile, file);
665             }
666             else
667             {
668                 work(file, getLocalPath() + outfile);
669             }
670         }
671     }
672
673     private void work(String JavaDoc file, String JavaDoc outfile)
674     {
675         Log.out("transfer started\nfile: " + file + "\noutfile: " + outfile);
676
677         BufferedInputStream JavaDoc in = null;
678         BufferedOutputStream JavaDoc out = null;
679
680         try
681         {
682             if(outfile.startsWith("http://"))
683             {
684                 //out = new BufferedOutputStream(new FileOutputStream(new WebdavResource(new HttpURL(file)).getMethodData());
685
//new WebdavFile(new URL(outfile), user, pass)));
686
//in = new BufferedInputStream(new FileInputStream(file));
687
String JavaDoc resPath = outfile.substring(0,
688                                                    outfile.lastIndexOf("/") +
689                                                    1);
690                 String JavaDoc name = outfile.substring(outfile.lastIndexOf("/") + 1);
691
692                 Log.debug("Uploading " + file + " to " + resPath + " as " +
693                           name);
694
695                 //HttpURL url = getURL(resPath);
696
WebdavResource res = getResource(resPath);
697
698                 //new WebdavResource(url);
699

700                 /*
701                 if(res.checkinMethod()) Log.debug("Checkin OK");
702                 else Log.debug("Checkin FAILED");
703
704                 Enumeration e = res.getAllowedMethods();
705                 while(e != null && e.hasMoreElements())
706                 {
707                         Log.debug("Method: " + e.nextElement().toString());
708                 }
709                 */

710                 if(res.putMethod(new File JavaDoc(file)))
711                 {
712                     fireProgressUpdate(file, DataConnection.FINISHED, -1);
713                 }
714                 else
715                 {
716                     Log.debug("Upload failed.");
717                     fireProgressUpdate(file, DataConnection.FAILED, -1);
718                 }
719
720                 return;
721             }
722
723             Log.debug("Downloading " + file + " to " + outfile);
724
725             out = new BufferedOutputStream JavaDoc(new FileOutputStream JavaDoc(outfile));
726             in = new BufferedInputStream JavaDoc(getResource(file).getMethodData());
727
728             //new WebdavResource(getURL(file)).getMethodData());
729
byte[] buf = new byte[webdavBuffer];
730             int len = 0;
731             int reallen = 0;
732
733             //System.out.println(file+":"+getLocalPath()+outfile);
734
while(true)
735             {
736                 len = in.read(buf);
737
738                 //System.out.print(".");
739
if(len == StreamTokenizer.TT_EOF)
740                 {
741                     break;
742                 }
743
744                 out.write(buf, 0, len);
745
746                 reallen += len;
747                 fireProgressUpdate(StringUtils.getFile(file),
748                                    DataConnection.GET, reallen);
749             }
750
751             fireProgressUpdate(file, DataConnection.FINISHED, -1);
752         }
753         catch(IOException JavaDoc ex)
754         {
755             Log.debug("Error with file IO (" + ex + ")!");
756             ex.printStackTrace();
757             fireProgressUpdate(file, DataConnection.FAILED, -1);
758         }
759         finally
760         {
761             try
762             {
763                 out.flush();
764                 out.close();
765                 in.close();
766             }
767             catch(Exception JavaDoc ex)
768             {
769                 ex.printStackTrace();
770             }
771         }
772     }
773
774     public int upload(String JavaDoc file, InputStream JavaDoc in)
775     {
776         /*
777            if(StringUtils.isRelative(file)) file = getPWD() + file;
778            file = file.replace('\\','/');
779
780            try
781            {
782                    work(new BufferedInputStream(in), file, file);
783                    return 0;
784            }
785            catch(Exception ex)
786            {
787                    Log.debug("Error: " + ex.toString());
788                    ex.printStackTrace();
789                    return -1;
790            }
791            */

792         Log.debug("Upload using InputStream is not implemented yet!");
793
794         return -1;
795     }
796
797     /*
798     private void work(BufferedInputStream in, String outfile, String file)
799     {
800      Log.out("transfer started, input from stream\noutfile: " + outfile);
801
802      try
803      {
804              BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outfile));
805         byte buf[] = new byte[webdavBuffer];
806         int len = 0;
807         int reallen = 0;
808
809         while(true)
810         {
811                 len = in.read(buf);
812                 System.out.print(".");
813                 if(len == StreamTokenizer.TT_EOF) break;
814                 out.write(buf,0,len);
815
816                 reallen += len;
817                 fireProgressUpdate(StringUtils.getFile(file),DataConnection.GET, reallen);
818         }
819
820         out.flush();
821         out.close();
822         in.close();
823         fireProgressUpdate(file,DataConnection.FINISHED, -1);
824      }
825      catch(IOException ex)
826      {
827              Log.debug("Error with file IO ("+ex+")!");
828         ex.printStackTrace();
829         fireProgressUpdate(file,DataConnection.FAILED, -1);
830      }
831     }
832     */

833     public InputStream JavaDoc getDownloadInputStream(String JavaDoc file)
834     {
835         if(StringUtils.isRelative(file))
836         {
837             file = getPWD() + file;
838         }
839
840         file = file.replace('\\', '/');
841
842         try
843         {
844             return getResource(file).getMethodData();
845         }
846         catch(Exception JavaDoc ex)
847         {
848             ex.printStackTrace();
849             Log.debug(ex.toString() +
850                       " @WebdavConnection::getDownloadInputStream");
851
852             return null;
853         }
854     }
855
856     public void addConnectionListener(ConnectionListener l)
857     {
858         listeners.add(l);
859     }
860
861     public void setConnectionListeners(Vector JavaDoc l)
862     {
863         listeners = l;
864     }
865
866     /** remote directory has changed */
867     public void fireDirectoryUpdate()
868     {
869         if(listeners == null)
870         {
871             return;
872         }
873         else
874         {
875             for(int i = 0; i < listeners.size(); i++)
876             {
877                 ((ConnectionListener) listeners.elementAt(i)).updateRemoteDirectory(this);
878             }
879         }
880     }
881
882     public boolean login(String JavaDoc user, String JavaDoc pass)
883     {
884         return true;
885     }
886
887     public void fireProgressUpdate(String JavaDoc file, String JavaDoc type, int bytes)
888     {
889         if(listeners == null)
890         {
891             return;
892         }
893         else
894         {
895             for(int i = 0; i < listeners.size(); i++)
896             {
897                 ConnectionListener listener = (ConnectionListener) listeners.elementAt(i);
898
899                 if(shortProgress && Settings.shortProgress)
900                 {
901                     if(type.startsWith(DataConnection.DFINISHED))
902                     {
903                         listener.updateProgress(baseFile,
904                                                 DataConnection.DFINISHED + ":" +
905                                                 fileCount, bytes);
906                     }
907
908                     listener.updateProgress(baseFile,
909                                             DataConnection.GETDIR + ":" +
910                                             fileCount, bytes);
911                 }
912                 else
913                 {
914                     listener.updateProgress(file, type, bytes);
915                 }
916             }
917         }
918     }
919
920     public Date JavaDoc[] sortDates()
921     {
922         return null;
923     }
924
925     public boolean rename(String JavaDoc from, String JavaDoc to)
926     {
927         Log.debug("Not implemented!");
928
929         return false;
930     }
931 }
932
Popular Tags