KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > knowgate > dfs > FileSystem


1 /*
2   Copyright (C) 2003 Know Gate S.L. All rights reserved.
3                       C/Oña, 107 1º2 28050 Madrid (Spain)O
4
5   Redistribution and use in source and binary forms, with or without
6   modification, are permitted provided that the following conditions
7   are met:
8
9   1. Redistributions of source code must retain the above copyright
10      notice, this list of conditions and the following disclaimer.
11
12   2. The end-user documentation included with the redistribution,
13      if any, must include the following acknowledgment:
14      "This product includes software parts from hipergate
15      (http://www.hipergate.org/)."
16      Alternately, this acknowledgment may appear in the software itself,
17      if and wherever such third-party acknowledgments normally appear.
18
19   3. The name hipergate must not be used to endorse or promote products
20      derived from this software without prior written permission.
21      Products derived from this software may not be called hipergate,
22      nor may hipergate appear in their name, without prior written
23      permission.
24
25   This library is distributed in the hope that it will be useful,
26   but WITHOUT ANY WARRANTY; without even the implied warranty of
27   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
28
29   You should have received a copy of hipergate License with this code;
30   if not, visit http://www.hipergate.org or mail to info@hipergate.org
31 */

32
33 package com.knowgate.dfs;
34
35 import java.lang.System JavaDoc;
36 import java.io.*;
37
38 import java.net.URL JavaDoc;
39 import java.net.MalformedURLException JavaDoc;
40 import java.net.ProtocolException JavaDoc;
41
42 import javax.activation.DataHandler JavaDoc;
43 import javax.activation.DataSource JavaDoc;
44 import javax.activation.FileDataSource JavaDoc;
45 import javax.activation.URLDataSource JavaDoc;
46
47 import com.enterprisedt.net.ftp.FTPClient;
48 import com.enterprisedt.net.ftp.FTPException;
49 import com.enterprisedt.net.ftp.FTPTransferType;
50
51 import com.knowgate.debug.DebugFile;
52 import com.knowgate.misc.Gadgets;
53 import com.knowgate.misc.Environment;
54
55 import java.util.Properties JavaDoc;
56
57 // ==========================================================
58

59 /**
60  * <p>Abstract FileSystem object for encasulating NFS and FTP file transfer.</p>
61  * FileSystem can work in 100% Pure Java mode or using native operating system
62  * atomic calls.
63  * <p>This is an alpha state testing module.</p>
64  * @author Sergio Montoro Ten
65  * @version 0.7
66  */

67
68 public class FileSystem {
69
70   /**
71    * <p>Create new File System</p>
72    * <p>Operation mode will be Pure Java by default</p>
73    * <p>User and Password fro FTP access wil be readed from hipergate.cnf file</p>
74    * @throws NumberFormatException If javamode property is not a positive integer number.
75    * @throws IllegalArgumentException If javamode property is not 0, 1 or 2.
76    */

77
78   public FileSystem() throws NumberFormatException JavaDoc, IllegalArgumentException JavaDoc {
79
80     try {
81       OS = Integer.parseInt(Environment.getProfileVar("hipergate", "javamode", String.valueOf(OS_PUREJAVA)));
82     }
83     catch (NumberFormatException JavaDoc nfe) { OS=OS_PUREJAVA; }
84
85     if (OS<0 || OS>2)
86       throw new IllegalArgumentException JavaDoc("javamode property can only be set to 0, 1 or 2");
87
88     SLASH = System.getProperty("file.separator");
89
90     oRunner = null;
91
92     sUsr = Environment.getProfileVar("hipergate", "fileuser", "anonymous");
93     sPwd = Environment.getProfileVar("hipergate", "filepassword", "");
94   }
95
96   // ==========================================================
97

98   /**
99    * <p>Create new File System</p>
100    * <p>Operation mode may be set for faster file access throught direct usage
101    * of operating system atomic calls.</p>
102    * <p>User and Password fro FTP access wil be readed from hipergate.cnf file</p>
103    * @param iMode Operation Mode { OS_PUREJAVA | OS_UNIX | OS_WINDOWS }
104    */

105
106   public FileSystem(int iMode) {
107     /* OS PAtch
108     OS = iMode;
109     */

110
111     SLASH = System.getProperty("file.separator");
112     oRunner = Runtime.getRuntime();
113     sUsr = Environment.getProfileVar("hipergate", "fileuser", "anonymous");
114     sPwd = Environment.getProfileVar("hipergate", "filepassword", "");
115   }
116
117   // ----------------------------------------------------------
118

119   /**
120    * <p>Create new File System</p>
121    * <p>Operation mode will be Pure Java by default</p>
122    * @param sUser User for FTP access
123    * @param sPassword Password for FTP access
124    */

125
126   public FileSystem(String JavaDoc sUser, String JavaDoc sPassword) {
127     OS = OS_PUREJAVA;
128     SLASH = System.getProperty("file.separator");
129     oRunner = Runtime.getRuntime();
130     sUsr = sUser;
131     sPwd = sPassword;
132   }
133
134   // ----------------------------------------------------------
135

136   /**
137    * <p>Create new File System</p>
138    * @param iMode Operation Mode: OS_PUREJAVA or OS_UNIX or OS_WINDOWS
139    * @param sUser User for FTP access
140    * @param sPassword Password for FTP access
141    */

142
143   public FileSystem(int iMode, String JavaDoc sUser, String JavaDoc sPassword) {
144     OS = iMode;
145
146     SLASH = System.getProperty("file.separator");
147     oRunner = Runtime.getRuntime();
148     sUsr = sUser;
149     sPwd = sPassword;
150   }
151
152   // ----------------------------------------------------------
153

154   /**
155    * Crea un FileSystem tomando los parámetros de creación necesarios
156    * de un conjunto de propiedades.
157    * @param oProps Conjunto de propiedades. Actualmente se usan dos:
158    * fileuser = Nombre de Usuario a Autentificar
159    * filepassword = Clave de Acceso del Usuario
160    */

161
162   /**
163    *
164    * @param oProps Properties collection.<br>
165    * <u>Property names</u>:<br>
166    * <b>javamode</b> : "0" (default) for Pure Java, "1" for UNIX, "2" for Windows.<br>
167    * <b>fileuser</b> : User for FTP access (default is "anonymous").
168    * <b>filepassword</b> : Password for FTP access (default is "").
169    * @throws NumberFormatException If javamode property is not a positive integer number.
170    * @throws IllegalArgumentException If javamode property is not 0, 1 or 2.
171    */

172   public FileSystem(Properties JavaDoc oProps) throws NumberFormatException JavaDoc,IllegalArgumentException JavaDoc {
173
174     OS = Integer.parseInt(oProps.getProperty("javamode", "0"));
175
176     if (OS<0 || OS>2)
177       throw new IllegalArgumentException JavaDoc("javamode property can only be set to 0, 1 or 2");
178
179     SLASH = System.getProperty("file.separator");
180
181     oRunner = Runtime.getRuntime();
182
183     sUsr = oProps.getProperty("fileuser", "anonymous");
184     sPwd = oProps.getProperty("filepassword", "");
185   }
186
187   // ----------------------------------------------------------
188

189   /**
190    * @param iOperatingSystem = { FileSystem.OS_PUREJAVA, FileSystem.OS_UNIX, FileSystem.OS_WINDOWS }
191    */

192
193   public void os(int iOperatingSystem) {
194     OS = iOperatingSystem;
195
196     if (OS!=OS_PUREJAVA && null==oRunner)
197       oRunner = Runtime.getRuntime();
198   }
199
200   // ----------------------------------------------------------
201

202   /**
203    * @param sUser user for FTP access
204    */

205
206   public void user(String JavaDoc sUser) {
207     sUsr = sUser;
208   }
209
210   // ----------------------------------------------------------
211

212   /**
213    * @return user for FTP access.
214    */

215   public String JavaDoc user() {
216     return sUsr;
217   }
218
219   // ----------------------------------------------------------
220

221   /**
222    * @param sPassword Password for FTP access
223    */

224   public void password(String JavaDoc sPassword) {
225     sPwd = sPassword;
226   }
227
228   // ----------------------------------------------------------
229

230   /**
231    * @return sPassword Password for FTP access
232    */

233
234   public String JavaDoc password() {
235     return sPwd;
236   }
237
238   // ----------------------------------------------------------
239

240   protected String JavaDoc host() {
241     return sHost;
242   }
243
244   // ----------------------------------------------------------
245

246   protected String JavaDoc path() {
247     return sPath;
248   }
249
250   // ----------------------------------------------------------
251

252   protected String JavaDoc file() {
253     return sFile;
254   }
255
256   // ----------------------------------------------------------
257

258   protected void splitURI(String JavaDoc sURI) {
259     String JavaDoc sURINoProtocol;
260     int iHost, iPort, iPath;
261
262     if (sURI.startsWith("file://")) {
263       sURINoProtocol = sURI.substring(7);
264       sProtocol = "file://";
265     }
266     else if (sURI.startsWith("ftp://")) {
267       sURINoProtocol = sURI.substring(6);
268       sProtocol = "ftp://";
269     }
270     else {
271       sURINoProtocol = sURI;
272       sProtocol = "";
273     }
274
275     if (sProtocol.equals("ftp://")) {
276       iHost = sURINoProtocol.indexOf('/', 7);
277       sHost = sURINoProtocol.substring(0, iHost);
278       iPort = sHost.indexOf(':');
279       if (iPort > 0) {
280         sPort = sHost.substring(iPort + 1);
281         sHost = sHost.substring(0, iPort);
282       }
283       else
284         sPort = "";
285
286       iPath = sURINoProtocol.lastIndexOf('/');
287       sPath = sURINoProtocol.substring(iHost, iPath+1);
288       sFile = sURINoProtocol.substring(iPath+1);
289     }
290     else if (sProtocol.equals("file://")) {
291       sHost = "";
292       sPort = "";
293       iPath = sURINoProtocol.lastIndexOf('/', 8);
294       sPath = sURINoProtocol.substring(7, iPath+1);
295       sFile = sURINoProtocol.substring(iPath+1);
296     }
297   } // splitURI()
298

299   // ---------------------------------------------------------------------------
300

301   private static void copyFileNFS(String JavaDoc sSource, String JavaDoc sTarget) throws Exception JavaDoc {
302     FileInputStream fis = new FileInputStream(sSource);
303     FileOutputStream fos = new FileOutputStream(sTarget);
304
305     BufferedInputStream bis = new BufferedInputStream(fis);
306     BufferedOutputStream bos = new BufferedOutputStream(fos);
307
308     byte[] buf = new byte[2048];
309     int i = 0;
310
311     while((i=bis.read(buf))!=-1) bos.write(buf, 0, i);
312
313     bis.close();
314     bos.close();
315     fis.close();
316     fos.close();
317   } // copyFileNFS()
318

319   // ---------------------------------------------------------------------------
320

321   private void copyFTPToFTP(String JavaDoc sSource, String JavaDoc sTarget)
322     throws FTPException,IOException {
323
324     String JavaDoc sSourceHost, sTargetHost, sSourcePath, sTargetPath, sSourceFile, sTargetFile, sTempName;
325     FTPWorkerThread oReader,oWriter;
326     FTPClient oFTPC;
327
328     if (DebugFile.trace) {
329       DebugFile.writeln("Begin FileSystem.copyFTPToFTP(" + sSource + "," + sTarget + ")");
330       DebugFile.incIdent();
331     }
332
333     splitURI(sSource);
334     sSourceHost = sHost;
335     sSourcePath = sPath;
336     if (!sSourcePath.endsWith("/")) sSourcePath+="/";
337     sSourceFile = sFile;
338
339     splitURI(sTarget);
340     sTargetHost = sHost;
341     sTargetPath = sPath;
342     if (!sTargetPath.endsWith("/")) sTargetPath+="/";
343     sTargetFile = sFile;
344
345     if (sSourceHost.equals(sTargetHost) && (OS!=OS_PUREJAVA)) {
346       sTempName = Gadgets.generateUUID();
347
348       oFTPC = new FTPClient(sTargetHost);
349       oFTPC.login(user(), password());
350
351       if (DebugFile.trace)DebugFile.writeln("FTPClient.site(exec cp " + sSourcePath + sSourceFile + " " + sTargetPath + sTargetFile);
352       oFTPC.rename(sSourcePath + sSourceFile, sSourcePath + sTempName );
353       oFTPC.site("exec cp " + sSourcePath + sTempName + " " + sTargetPath + sTargetFile);
354       oFTPC.rename(sSourcePath + sTempName, sSourcePath + sSourceFile);
355       oFTPC.quit();
356     }
357     else {
358       oReader = new FTPWorkerThread(sSourceHost, sUsr, sPwd);
359       oWriter = new FTPWorkerThread(sTargetHost, sUsr, sPwd);
360
361       oReader.get(sSourcePath+sSourceFile);
362       oWriter.put(sTargetPath+sTargetFile);
363
364       oReader.connect(oWriter.getInputPipe());
365
366       if (DebugFile.trace) DebugFile.writeln("starting read pipe...");
367
368       oReader.start();
369
370       if (DebugFile.trace) DebugFile.writeln("starting write pipe...");
371
372       oWriter.start();
373     } // fi (sSourceHost==sTargetHost AND OS!=PUREJAVA)
374

375     if (DebugFile.trace) {
376       DebugFile.decIdent();
377       DebugFile.writeln("End FileSystem.copyFTPToFTP()");
378     }
379   } // copyFTPToFTP()
380

381   // ---------------------------------------------------------------------------
382

383   private void copyFileToFTP(String JavaDoc sSource, String JavaDoc sTarget) throws Exception JavaDoc,IOException {
384     boolean bFTPSession = false;
385
386     FTPClient oFTPC = null;
387
388     splitURI(sTarget);
389
390     try {
391       if (DebugFile.trace) DebugFile.writeln("new FTPClient(" + sHost + ")");
392       oFTPC = new FTPClient(sHost);
393       if (DebugFile.trace) DebugFile.writeln("FTPClient.login(" + sUsr + "," + sPwd + ")");
394       oFTPC.login(sUsr, sPwd);
395       bFTPSession = true;
396       if (DebugFile.trace) DebugFile.writeln("FTPClient.chdir(" + sPath + ")");
397       oFTPC.chdir(sPath);
398       if (DebugFile.trace) DebugFile.writeln("FTPClient.put(" + sSource + "," + sFile + ",false)");
399       oFTPC.setType(FTPTransferType.BINARY);
400       oFTPC.put(sSource, sFile, false);
401
402     } catch (FTPException ftpe) {
403       throw new Exception JavaDoc(ftpe.getMessage(), ftpe.getCause());
404     }
405     finally {
406       if (DebugFile.trace) DebugFile.writeln("FTPClient.quit()");
407       if (bFTPSession) oFTPC.quit();
408     }
409
410   } // copyFileToFTP()
411

412   // ---------------------------------------------------------------------------
413

414   private void copyFTPToFile(String JavaDoc sSource, String JavaDoc sTarget)
415     throws Exception JavaDoc,IOException {
416
417     boolean bFTPSession = false;
418
419     FTPClient oFTPC = null;
420
421     splitURI(sSource);
422
423     try {
424       if (DebugFile.trace) DebugFile.writeln("new FTPClient(" + sHost + ")");
425       oFTPC = new FTPClient(sHost);
426       if (DebugFile.trace) DebugFile.writeln("FTPClient.login(" + sUsr + "," + sPwd + ")");
427       oFTPC.login(sUsr, sPwd);
428       bFTPSession = true;
429       if (DebugFile.trace) DebugFile.writeln("FTPClient.chdir(" + sPath + ")");
430       oFTPC.chdir(sPath);
431       if (DebugFile.trace) DebugFile.writeln("FTPClient.get(" + sTarget + "," + sFile + ",false)");
432       oFTPC.setType(FTPTransferType.BINARY);
433       oFTPC.get(sTarget, sFile);
434
435     } catch (FTPException ftpe) {
436       throw new Exception JavaDoc(ftpe.getMessage(), ftpe.getCause());
437     }
438     finally {
439       if (DebugFile.trace) DebugFile.writeln("FTPClient.quit()");
440       if (bFTPSession) oFTPC.quit();
441     }
442
443   } // copyFileToFTP()
444

445   // ---------------------------------------------------------------------------
446

447   private static void copyHTTPToFile (String JavaDoc sSource, String JavaDoc sTarget)
448     throws MalformedURLException JavaDoc,IOException {
449
450     URL JavaDoc oUrl = new URL JavaDoc(sSource);
451
452     FileOutputStream oTrgt = new FileOutputStream(sTarget.substring(7));
453
454     DataHandler JavaDoc oHndlr = new DataHandler JavaDoc(oUrl);
455
456     oHndlr.writeTo(oTrgt);
457
458     oTrgt.close();
459   } // copyHTTPToFile
460

461   // ---------------------------------------------------------------------------
462

463   /**
464    * <p>Copy a file</p>
465    * <p>This method is able to copy a file from local or network disk location
466    * to and FTP location or viceversa.</p>
467    * @param sSourceURI Source URI, it must have the following syntax:
468    * protocol://[server:[port]]/path/filename
469    * Even whe working with local files protocol must be specified, ej.
470    * copy ("file:///tmp/upload/image.jpg", "file:///opt/storage/approved/image.jpg")
471    * @param sTargetURI Target URI
472    * @throws Exception
473    * @throws IOException
474    * @throws MalformedURLException
475    */

476
477   public boolean copy (String JavaDoc sSourceURI, String JavaDoc sTargetURI) throws MalformedURLException JavaDoc, IOException, Exception JavaDoc {
478     // Copy a file by delegating the operation into an operating system atomic call
479

480     if (DebugFile.trace) {
481       DebugFile.writeln("Begin FileSystem.copy(" + sSourceURI + "," + sTargetURI + ")");
482       DebugFile.incIdent();
483     }
484
485     byte verbose[] = new byte[256];
486     boolean bRetVal;
487     int iReaded;
488     String JavaDoc sCmd;
489     InputStream oStdOut;
490     String JavaDoc sSourcePath;
491     String JavaDoc sTargetPath;
492     File oSourceFile;
493
494     if (sSourceURI.startsWith("file://") && sTargetURI.startsWith("file://")) {
495       sSourcePath = sSourceURI.substring(7);
496       sTargetPath = sTargetURI.substring(7);
497       oSourceFile = new File(sSourcePath);
498
499       switch (OS) {
500         case OS_UNIX:
501           if (oSourceFile.isDirectory())
502             sCmd = "/usr/bin/cp -r " + sSourcePath + " " + sTargetPath;
503           else
504             sCmd = "/usr/bin/cp \"" + sSourcePath + "\" \"" + sTargetPath + "\"";
505           break;
506         case OS_WINDOWS:
507           if (oSourceFile.isDirectory())
508             sCmd = "xcopy " + sSourcePath + " " + sTargetPath + " /E /C /Q /Y";
509           else
510             sCmd = "copy \"" + sSourcePath + "\" \"" + sTargetPath + "\"";
511           break;
512         default:
513           sCmd = "";
514       } // end switch(OS)
515

516       if (sCmd.length()>0) {
517         if (DebugFile.trace) {
518           DebugFile.writeln("Runtime.exec(" + sCmd + ")");
519           oStdOut = oRunner.exec(sCmd).getInputStream();
520           iReaded = oStdOut.read(verbose, 0, 255);
521           oStdOut.close();
522           if (iReaded>0) DebugFile.writeln(new String JavaDoc(verbose, iReaded));
523         }
524         else {
525           oRunner.exec(sCmd);
526           bRetVal = true;
527         }
528       }
529       else {
530         if (DebugFile.trace) DebugFile.writeln("copyFileNFS(" + sSourcePath + "," + sTargetPath + ")");
531
532         copyFileNFS(sSourcePath, sTargetPath);
533         bRetVal = true;
534       }
535       bRetVal = true;
536     } // fi(Source==file AND Target==file)
537
else if (sSourceURI.startsWith("file://") && sTargetURI.startsWith("ftp://")) {
538       sSourcePath = sSourceURI.substring(7);
539       sTargetPath = sTargetURI.substring(6);
540       if (DebugFile.trace) DebugFile.writeln("copyFileToFTP(" + sSourcePath + "," + sTargetURI + ")");
541
542       copyFileToFTP(sSourcePath, sTargetURI);
543       bRetVal = true;
544     }
545     else if (sSourceURI.startsWith("ftp://") && sTargetURI.startsWith("ftp://")) {
546       if (DebugFile.trace) DebugFile.writeln("copyFTPToFTP(" + sSourceURI + "," + sTargetURI + ")");
547
548       copyFTPToFTP(sSourceURI, sTargetURI);
549       bRetVal = true;
550     }
551     else if (sSourceURI.startsWith("ftp://") && sTargetURI.startsWith("file://")) {
552       if (DebugFile.trace) DebugFile.writeln("copyFTPToFTP(" + sSourceURI + "," + sTargetURI + ")");
553
554       copyFTPToFile(sSourceURI, sTargetURI);
555       bRetVal = true;
556     }
557     else if (sSourceURI.startsWith("http://") && sTargetURI.startsWith("file://")) {
558       if (DebugFile.trace) DebugFile.writeln("copyHTTPToFile(" + sSourceURI + "," + sTargetURI + ")");
559
560       copyHTTPToFile(sSourceURI, sTargetURI);
561       bRetVal = true;
562     }
563     else {
564       if (DebugFile.trace) DebugFile.writeln("ERROR: FileSystem.copy(), Source or Target protocol not recognized");
565       bRetVal = false;
566       throw new IOException("FileSystem.copy(), protocol not recognized");
567     }
568
569     if (DebugFile.trace) {
570       DebugFile.decIdent();
571       DebugFile.writeln("End FileSystem.copy() : " + String.valueOf(bRetVal));
572     }
573
574     return bRetVal;
575   } // copy()
576

577
578   // ---------------------------------------------------------------------------
579

580   /**
581    * <p>Get file length</p>
582    * Currently only local and network files length can be queried</p>
583    * @param sFullURI File URI (protocol+path)
584    * @return File length in bytes
585    * @throws IOException
586    */

587   public int filelen (String JavaDoc sFullURI) throws IOException {
588     File oFile;
589     Long JavaDoc oFLng;
590     int iFLen;
591
592     if (DebugFile.trace) {
593       DebugFile.writeln("Begin FileSystem.filelen(" + sFullURI + ")");
594       DebugFile.incIdent();
595     }
596
597     oFile = new File(sFullURI);
598     if (oFile.exists()) {
599       oFLng = new Long JavaDoc(oFile.length());
600       iFLen = oFLng.intValue();
601     }
602     else
603       throw new IOException("File " + sFullURI + " does not exists");
604
605     if (DebugFile.trace) {
606       DebugFile.decIdent();
607       DebugFile.writeln("End FileSystem.filelen() : " + String.valueOf(iFLen));
608     }
609
610     return iFLen;
611   } // filelen()
612

613   // ----------------------------------------------------------
614

615   private static String JavaDoc[] listFTP (FTPClient oFTPC, String JavaDoc sBaseDir, char cType)
616     throws FTPException, IOException {
617
618     if (DebugFile.trace) {
619       DebugFile.writeln("Begin FileSystem.listFTP(" + sBaseDir + "," + cType + ")");
620       DebugFile.incIdent();
621     }
622
623     String JavaDoc[] aFileNames = oFTPC.dir(sBaseDir);
624     String JavaDoc[] aFileAttrs = oFTPC.dir(sBaseDir, true);
625
626     int iFileCount = aFileNames.length;
627     int iAttrCount = aFileAttrs.length;
628
629     boolean[] aIsDirectory = new boolean[iFileCount];
630
631     for (int i=0; i<iFileCount; i++) aIsDirectory[i] = false;
632
633     String JavaDoc sFile;
634     int iDirCount = 0;
635
636     for (int f=0; f<iFileCount; f++) {
637       sFile = aFileNames[f];
638       for (int a=0; a<iAttrCount; a++) {
639         if ((aFileAttrs[a].charAt(0)==cType))
640           if (aFileAttrs[a].endsWith(sFile)) {
641             aIsDirectory[f] = true;
642             iDirCount++;
643             break;
644           } // fi
645
} // next
646
} // next
647

648     String JavaDoc[] aDirNames = new String JavaDoc[iDirCount];
649
650     iDirCount = 0;
651
652     for (int d=0; d<iFileCount; d++)
653       if (aIsDirectory[d])
654         aDirNames[iDirCount++] = aFileNames[d];
655
656     if (DebugFile.trace) {
657       DebugFile.decIdent();
658       DebugFile.writeln("End FileSystem.listFTP()");
659     }
660
661     return aDirNames;
662   } // listFTP
663

664   // ----------------------------------------------------------
665

666   private static String JavaDoc[] listDirsFTP (FTPClient oFTPC, String JavaDoc sBaseDir)
667     throws FTPException, IOException {
668     return listFTP(oFTPC, sBaseDir, 'd');
669   }
670
671   // ----------------------------------------------------------
672

673   private static String JavaDoc[] listFilesFTP (FTPClient oFTPC, String JavaDoc sBaseDir)
674     throws FTPException, IOException {
675     return listFTP(oFTPC, sBaseDir, '-');
676   }
677
678   // ----------------------------------------------------------
679

680   private static boolean isDirectoryFTP (FTPClient oFTPC, String JavaDoc sFilePath)
681     throws FTPException, IOException {
682
683     if (DebugFile.trace) {
684       DebugFile.writeln("Begin FileSystem.isDirectoryFTP(" + sFilePath + ")");
685       DebugFile.incIdent();
686     }
687
688     if (sFilePath.equals("/")) return true;
689
690     String JavaDoc sPathName, sFileName;
691
692     int iSlash = sFilePath.lastIndexOf('/');
693     if (iSlash<1) {
694       sPathName = "/";
695       sFileName = sFilePath.substring(1);
696     }
697     else {
698       sPathName = sFilePath.substring(0, iSlash);
699       sFileName = sFilePath.substring(iSlash+1);
700     }
701
702     String JavaDoc[] aFileAttrs = oFTPC.dir(sPathName, true);
703     boolean bIsDir = false;
704
705     int iFileCount = aFileAttrs.length;
706
707     for (int d=0; d<iFileCount; d++) {
708       if (aFileAttrs[d].endsWith(sFileName)) {
709         bIsDir = (aFileAttrs[d].charAt(0) == 'd');
710         break;
711       } // fi()
712
} // next
713

714     if (DebugFile.trace) {
715       DebugFile.decIdent();
716       DebugFile.writeln("End FileSystem.isDirectoryFTP() : " + String.valueOf(bIsDir));
717     }
718
719     return bIsDir;
720   } // isDirectoryFTP
721

722   // ----------------------------------------------------------
723

724   /**
725    * Remove a directory and all its subdirectories and files.
726    * @param sFullURI Directory URI. For example: file:///tmp/upload
727    * @return <b>true</b> if Directory was successfully deleted.
728    * This return value should always be checked as Java functions may not return
729    * any error but not delete a directory that is in use by another process.
730    * @throws IOException
731    */

732   public boolean rmdir (String JavaDoc sFullURI) throws IOException {
733     File oFile;
734     int iReaded;
735     String JavaDoc sFullPath;
736     boolean bRetVal = false;
737     boolean bFTPSession = false;
738     FTPClient oFTPC = null;
739     String JavaDoc sCmd = null;
740     InputStream oStdOut;
741     byte verbose[] = new byte[256];
742
743     if (DebugFile.trace) {
744       DebugFile.writeln("Begin FileSystem.rmdir(" + sFullURI + ")");
745       DebugFile.incIdent();
746     }
747
748     if (sFullURI.startsWith("file://")) {
749       sFullPath = sFullURI.substring(7);
750       if (sFullPath.endsWith(SLASH)) sFullPath = sFullPath.substring(0, sFullPath.length()-SLASH.length());
751       oFile = new File(sFullPath);
752
753       if (DebugFile.trace) DebugFile.writeln(sFullPath + " is a directory");
754
755       switch (OS) {
756           case OS_PUREJAVA:
757             bRetVal = oFile.delete();
758             break;
759           case OS_UNIX:
760             sCmd = "rm -rf \"" + sFullPath + "\"";
761             break;
762           case OS_WINDOWS:
763             sCmd = "DEL /F /S /Q \"" + sFullPath + "\"";
764             break;
765       } // end switch()
766

767       if (null!=sCmd) {
768           if (DebugFile.trace) {
769             DebugFile.writeln("Runtime.exec(" + sCmd + ")");
770             oStdOut = oRunner.exec(sCmd).getInputStream();
771             iReaded = oStdOut.read(verbose, 0, 255);
772             oStdOut.close();
773             if (iReaded > 0) {
774               DebugFile.writeln(new String JavaDoc(verbose, iReaded));
775               bRetVal = false;
776             }
777             else
778               bRetVal = true;
779           }
780           else {
781             oRunner.exec(sCmd);
782             bRetVal = true;
783           }
784       } // fi (sCmd)
785

786       if (oFile.exists()) bRetVal = false;
787
788       oFile = null;
789     }
790
791     else if (sFullURI.startsWith("ftp://")) {
792
793       splitURI(sFullURI);
794
795       try {
796         if (DebugFile.trace) DebugFile.writeln("new FTPClient(" + sHost + ")");
797
798         oFTPC = new FTPClient(sHost);
799
800         if (DebugFile.trace) DebugFile.writeln("oFTPC.login(" + sUsr + ", ...);");
801
802         oFTPC.login(sUsr, sPwd);
803
804         bFTPSession = true;
805
806         sFullPath = Gadgets.chomp(sPath, '/') + sFile;
807
808         String JavaDoc[] aSubDirs = listDirsFTP(oFTPC, sFullPath);
809
810         for (int d = 0; d < aSubDirs.length; d++) {
811           delete (Gadgets.chomp(sFullURI, '/') + aSubDirs[d]);
812         }
813
814         String JavaDoc[] aFiles = listFilesFTP(oFTPC, sFullPath);
815
816         for (int f=0; f<aFiles.length; f++) {
817           if (DebugFile.trace) DebugFile.writeln("FTPClient.delete(" + Gadgets.chomp(sPath,'/') + Gadgets.chomp(sFile,'/') + aFiles[f] + ")");
818
819           oFTPC.delete (Gadgets.chomp(sPath,'/') + Gadgets.chomp(sFile,'/') + aFiles[f]);
820         }
821
822         if (DebugFile.trace) DebugFile.writeln("FTPClient.rmdir(" + sFullPath + ")");
823
824         oFTPC.rmdir(sFullPath);
825
826         bRetVal = true;
827       } catch (FTPException ftpe) {
828         bRetVal = false;
829         throw new IOException(ftpe.getMessage());
830       }
831       catch (Exception JavaDoc xcpt) {
832         bRetVal = false;
833         throw new IOException(xcpt.getMessage());
834       }
835       finally {
836         try { if (bFTPSession) oFTPC.quit(); } catch (Exception JavaDoc xcpt) { }
837       }
838     }
839     // fi(sFullURI.startsWith(...))
840

841     if (DebugFile.trace) {
842       DebugFile.decIdent();
843       DebugFile.writeln("End FileSystem.rmdir() : " + String.valueOf(bRetVal));
844     }
845
846     return bRetVal;
847   } // rmdir
848

849   /**
850    * <p>Delete o file or directory</p>
851    * <p>Can recursively delete local or FTP directories</p>
852    * @param sFullURI File or directory URI.
853    * For example ftp://localhost/opt/temp/upload/logo.gif
854    * @return <b>true</b> if File or Directory was successfully deleted.
855    * This return value should always be checked as Java functions may not return
856    * any error but not delete a directory or file that is in use by another process.
857    * @throws IOException
858    */

859   public boolean delete (String JavaDoc sFullURI) throws IOException {
860     File oFile;
861     String JavaDoc sFullPath;
862     boolean bRetVal = false;
863     boolean bFTPSession = false;
864     FTPClient oFTPC = null;
865     String JavaDoc sCmd = null;
866     byte verbose[] = new byte[256];
867
868     if (DebugFile.trace) {
869       DebugFile.writeln("Begin FileSystem.delete(" + sFullURI + ")");
870       DebugFile.incIdent();
871       switch (OS) {
872         case OS_PUREJAVA:
873           DebugFile.writeln("OS mode is Pure Java");
874           break;
875         case OS_UNIX:
876           DebugFile.writeln("OS mode is Unix");
877           break;
878         case OS_WINDOWS:
879           DebugFile.writeln("OS mode is Windows");
880           break;
881       }
882     }
883
884     // Codigo a ejecutar por el protocolo de ficheros locales
885
if (sFullURI.startsWith("file://")) {
886       sFullPath = sFullURI.substring(7);
887       if (sFullPath.endsWith(SLASH)) sFullPath = sFullPath.substring(0, sFullPath.length()-SLASH.length());
888       oFile = new File(sFullPath);
889
890       if (oFile.isFile()) {
891         if (DebugFile.trace) DebugFile.writeln(sFullPath + " is a file");
892         bRetVal = oFile.delete();
893       }
894       else {
895         bRetVal = rmdir(sFullURI);
896       } // fi (isFile())
897
oFile = null;
898     }
899     // Codigo a ejecutar por el protocolo FTP
900
else if (sFullURI.startsWith("ftp://")) {
901
902       splitURI(sFullURI);
903
904       try {
905         if (DebugFile.trace) DebugFile.writeln("new FTPClient(" + sHost + ")");
906
907         oFTPC = new FTPClient(sHost);
908
909         if (DebugFile.trace) DebugFile.writeln("oFTPC.login(" + sUsr + ", ...);");
910
911         oFTPC.login(sUsr, sPwd);
912
913         bFTPSession = true;
914
915         sFullPath = Gadgets.chomp(sPath,'/') + sFile;
916
917         if (isDirectoryFTP(oFTPC, sFullPath)) {
918           oFTPC.quit();
919           bFTPSession = false;
920           rmdir (sFullURI);
921         }
922         else {
923           oFTPC.delete(sFullPath);
924         }
925
926         bRetVal = true;
927       } catch (FTPException ftpe) {
928         bRetVal = false;
929         throw new IOException(ftpe.getMessage());
930       }
931       catch (Exception JavaDoc xcpt) {
932         bRetVal = false;
933         throw new IOException(xcpt.getMessage());
934       }
935       finally {
936         try { if (bFTPSession) oFTPC.quit(); } catch (Exception JavaDoc xcpt) { }
937       }
938     }
939     // fi(sFullURI.startsWith(...))
940

941     if (DebugFile.trace) {
942       DebugFile.decIdent();
943       DebugFile.writeln("End FileSystem.delete() : " + String.valueOf(bRetVal));
944     }
945
946     return bRetVal;
947   } // delete()
948

949   // ----------------------------------------------------------
950

951   /**
952    * <p>Mark an URI for deffered deletion</p>
953    * Because web servers often cache and lock files as they are accessed,
954    * it is sometimes not possible to delete recently accessed files inmediately.
955    * This method just appends the given URI at the end of a plain text file
956    * containing a list of file names. This file name list can be later used upon
957    * Web Server re-start for purging files that could no be deleted before because
958    * they where locked.
959    * @param sFullURI File URI to delete, ej. file:///opt/knowgate/files/deleteme.txt
960    * @param sDeferedFiles Local path to file containing delete list
961    * @throws IOException
962    */

963
964   public boolean delete (String JavaDoc sFullURI, String JavaDoc sDeferedFiles) throws IOException {
965     boolean bRetVal = delete(sFullURI);
966     FileWriter oWrt;
967
968     if (sDeferedFiles.startsWith("file://")) sDeferedFiles = sDeferedFiles.substring(7);
969
970     if (!bRetVal && sFullURI.startsWith("file://")) {
971       oWrt = new FileWriter(sDeferedFiles, true);
972       oWrt.write("\"" + sFullURI.substring(7) + "\"\n");
973       oWrt.close();
974     } // fi ()
975

976     return bRetVal;
977   } // delete
978

979   // ----------------------------------------------------------
980

981   private boolean moveFTPToFTP (String JavaDoc sSourceURI, String JavaDoc sTargetURI) throws FTPException, IOException {
982     boolean bRetVal = true;
983     String JavaDoc sSourceHost, sTargetHost, sSourcePath, sTargetPath, sSourceFile, sTargetFile;
984     FTPWorkerThread oReader,oWriter;
985     FTPClient oFTPC;
986
987     if (DebugFile.trace) {
988       DebugFile.writeln("Begin FileSystem.moveFTPToFTP(" + sSourceURI + "," + sTargetURI + ")");
989       DebugFile.incIdent();
990     }
991
992     splitURI(sSourceURI);
993     sSourceHost = sHost;
994     sSourcePath = sPath;
995     if (!sSourcePath.endsWith("/")) sSourcePath+="/";
996     sSourceFile = sFile;
997
998     splitURI(sTargetURI);
999     sTargetHost = sHost;
1000    sTargetPath = sPath;
1001    if (!sTargetPath.endsWith("/")) sTargetPath+="/";
1002    sTargetFile = sFile;
1003
1004    if (sSourceHost.equals(sTargetHost)) {
1005      if (DebugFile.trace) DebugFile.writeln("new FTPClient(" + sTargetHost + ")");
1006
1007      oFTPC = new FTPClient(sTargetHost);
1008      oFTPC.login(user(), password());
1009
1010      if (DebugFile.trace) DebugFile.writeln("FTPClient.rename(" + sSourcePath + sSourceFile + "," + sTargetPath + sTargetFile + ")");
1011
1012      oFTPC.rename(sSourcePath + sSourceFile, sTargetPath + sTargetFile);
1013      oFTPC.quit();
1014    }
1015    else {
1016
1017      oReader = new FTPWorkerThread(sSourceHost, sUsr, sPwd);
1018      oWriter = new FTPWorkerThread(sTargetHost, sUsr, sPwd);
1019
1020      oReader.move(sSourcePath+sSourceFile);
1021      oWriter.put (sTargetPath+sTargetFile);
1022
1023      oReader.connect(oWriter.getInputPipe());
1024
1025      if (DebugFile.trace) DebugFile.writeln("starting read pipe...");
1026
1027      oReader.start();
1028
1029      if (DebugFile.trace) DebugFile.writeln("starting write pipe...");
1030
1031      oWriter.start();
1032    }
1033
1034    if (DebugFile.trace) {
1035      DebugFile.decIdent();
1036      DebugFile.writeln("End FileSystem.moveFTPToFTP()");
1037    }
1038    return bRetVal;
1039  } // moveFTPToFTP
1040

1041  // ----------------------------------------------------------
1042

1043  /**
1044   * <p>Move a file from one location to another</p>
1045   * @param sSourceURI Source URI
1046   * @param sTargetURI Target URI
1047   * @return
1048   * @throws Exception
1049   * @throws IOException
1050   */

1051
1052  public boolean move (String JavaDoc sSourceURI, String JavaDoc sTargetURI) throws Exception JavaDoc, IOException {
1053    boolean bRetVal;
1054
1055    if (sSourceURI.startsWith("ftp://") && sTargetURI.startsWith("ftp://")) {
1056      bRetVal = moveFTPToFTP(sSourceURI, sTargetURI);
1057    }
1058    else {
1059      bRetVal = copy(sSourceURI, sTargetURI);
1060      if (bRetVal)
1061        bRetVal = delete(sSourceURI);
1062    }
1063    return bRetVal;
1064  } // move
1065

1066  // ----------------------------------------------------------
1067

1068  /**
1069   * Rename file
1070   * @param sSourceURI Source URI (ej. "file:///tmp/files/oldfile.txt")
1071   * @param sTargetURI Target URI (ej. "file:///tmp/files/newfile.txt")
1072   * @since 2.1
1073   * @throws Exception
1074   * @throws IOException
1075   * @throws ProtocolException If source and target file does not use the same protocol, either file:// or ftp://
1076   */

1077  public boolean rename (String JavaDoc sSourceURI, String JavaDoc sTargetURI)
1078    throws Exception JavaDoc, IOException, ProtocolException JavaDoc {
1079    boolean bRetVal;
1080
1081    if (sSourceURI.startsWith("file://") && sTargetURI.startsWith("file://")) {
1082      File oOldFile = new File (sSourceURI.substring(7));
1083      File oNewFile = new File (sTargetURI.substring(7));
1084      bRetVal = oOldFile.renameTo(oNewFile);
1085    }
1086    else if (sSourceURI.startsWith("ftp://") && sTargetURI.startsWith("ftp://")) {
1087      bRetVal = moveFTPToFTP(sSourceURI, sTargetURI);
1088    }
1089    else {
1090      throw new ProtocolException JavaDoc("");
1091    }
1092    return bRetVal;
1093  } // move
1094

1095  // ----------------------------------------------------------
1096

1097  private static void mkdirsFTP (FTPClient oFTPC, String JavaDoc sPath) throws IOException,FTPException {
1098    String JavaDoc aPath[] = Gadgets.split( (sPath.endsWith("/") ? sPath.substring(0, sPath.length()-1) : sPath), "/");
1099    String JavaDoc sCurrent = "/";
1100    int l = aPath.length;
1101    boolean bAlreadyExists;
1102
1103    for (int p=0; p<=l; p++) {
1104      try {
1105        if (DebugFile.trace) DebugFile.writeln("oFTPC.chdir(" + sCurrent + ")");
1106        oFTPC.chdir(sCurrent);
1107        bAlreadyExists = true;
1108      }
1109      catch (FTPException ftpe) {
1110        if (DebugFile.trace) DebugFile.writeln(sCurrent + " does not exist");
1111        bAlreadyExists = false;
1112      }
1113      if (!bAlreadyExists) {
1114        if (DebugFile.trace) DebugFile.writeln("oFTPC.mkdir(" + sCurrent + ")");
1115        oFTPC.mkdir(sCurrent);
1116      }
1117      if (p==l) break;
1118      sCurrent += aPath[p] + "/";
1119    } // next (p)
1120
} // mkdirsFTP
1121

1122  // ----------------------------------------------------------
1123

1124  /**
1125   * <p>Create a complete directory branch.</p>
1126   * @param sFullURI Full path of directory to create,
1127   * ej. file:///tmp/uploads/binaries/images
1128   * ej. ftp://ftpserver/tmp/uploads/binaries/images
1129   * @throws Exception
1130   * @throws IOException
1131   */

1132
1133  public boolean mkdirs (String JavaDoc sFullURI) throws Exception JavaDoc,IOException {
1134    boolean bFTPSession = false;
1135    String JavaDoc sCmd;
1136
1137    if (DebugFile.trace) {
1138      DebugFile.writeln("Begin FileSystem.mkdirs(" + sFullURI + ")");
1139      DebugFile.incIdent();
1140    }
1141
1142    File oFile;
1143    FTPClient oFTPC = null;
1144    boolean bRetVal = false;
1145    String JavaDoc sFullPath = sFullURI.substring(7);
1146
1147    // Assume file protocol by default
1148
if (!sFullURI.startsWith("file://") && !sFullURI.startsWith("ftp://"))
1149      sFullURI = "file://" + sFullURI;
1150
1151    if (sFullURI.startsWith("file://")) {
1152      switch (OS) {
1153        case OS_PUREJAVA:
1154          oFile = new File(sFullPath);
1155          if (DebugFile.trace) DebugFile.writeln("File.mkdirs(" + sFullPath + ")");
1156          bRetVal = oFile.mkdirs();
1157          oFile = null;
1158          break;
1159        case OS_UNIX:
1160          if (DebugFile.trace) DebugFile.writeln("mkdir -p \"" + sFullPath + "\"");
1161          sCmd = "mkdir -p \"" + sFullPath + "\"";
1162          oRunner.exec(sCmd);
1163          break;
1164        case OS_WINDOWS:
1165          if (DebugFile.trace) DebugFile.writeln("md \"" + sFullPath + "\"");
1166          sCmd = "md \"" + sFullPath + "\"";
1167          oRunner.exec(sCmd);
1168          break;
1169      }
1170    }
1171    else if (sFullURI.startsWith("ftp://")) {
1172      if (!sFullURI.endsWith("/")) sFullURI += "/";
1173      splitURI(sFullURI);
1174
1175      try {
1176        if (DebugFile.trace) DebugFile.writeln("new FTPClient(" + sHost + ")");
1177        oFTPC = new FTPClient(sHost);
1178
1179        if (DebugFile.trace) DebugFile.writeln("FTPClient.login(" + sUsr + "," + sPwd + ")");
1180        oFTPC.login(sUsr, sPwd);
1181        bFTPSession = true;
1182
1183        if (DebugFile.trace) DebugFile.writeln("FileSystem.mkdirsFTP(" + sPath + ")");
1184
1185        mkdirsFTP(oFTPC, sPath);
1186        bRetVal = true;
1187      }
1188      catch (FTPException ftpe) {
1189        throw new IOException(ftpe.getMessage());
1190      }
1191      finally {
1192        if (bFTPSession) oFTPC.quit();
1193      }
1194    } // fi(sFullURI.startsWith(...))
1195

1196    if (DebugFile.trace) {
1197      DebugFile.decIdent();
1198      DebugFile.writeln("End FileSystem.mkdirs() : " + String.valueOf(bRetVal));
1199    }
1200
1201    return bRetVal;
1202  } // mkdirs()
1203

1204  // ----------------------------------------------------------
1205

1206  /**
1207   * <p>Convert a text file from one character set to another</p>
1208   * The input file is overwritten.
1209   * @param sFilePath File Path
1210   * @param sOldCharset Original file character set
1211   * @param sNewCharset New character set
1212   * @throws FileNotFoundException
1213   * @throws IOException
1214   * @throws UnsupportedEncodingException
1215   */

1216  public static void convert (String JavaDoc sFilePath, String JavaDoc sOldCharset, String JavaDoc sNewCharset)
1217    throws FileNotFoundException, IOException,UnsupportedEncodingException {
1218
1219    if (DebugFile.trace) {
1220      DebugFile.writeln("Begin FileSystem.convert(" + sFilePath + "," + sOldCharset + "," + sNewCharset + ")");
1221      DebugFile.incIdent();
1222    }
1223
1224    final int iBufferSize = 8192;
1225    int iReaded;
1226    char[] cBuffer = new char[iBufferSize];
1227
1228    FileInputStream oFileStrm = new FileInputStream(sFilePath);
1229
1230    BufferedInputStream oInStrm = new BufferedInputStream(oFileStrm);
1231
1232    InputStreamReader oStrm = new InputStreamReader(oInStrm, sOldCharset);
1233
1234    FileOutputStream oOutStrm = new FileOutputStream(sFilePath + ".tmp");
1235
1236    while (true) {
1237      iReaded = oStrm.read(cBuffer,0,iBufferSize);
1238
1239      if (-1==iReaded) break;
1240
1241      oOutStrm.write(new String JavaDoc(cBuffer,0,iReaded).getBytes(sNewCharset));
1242    }
1243
1244    oOutStrm.close();
1245
1246    oStrm.close();
1247    oInStrm.close();
1248    oFileStrm.close();
1249
1250    File oOld = new File(sFilePath);
1251    oOld.delete();
1252
1253    File oNew = new File(sFilePath + ".tmp");
1254    oNew.renameTo(oOld);
1255
1256    if (DebugFile.trace) {
1257      DebugFile.decIdent();
1258      DebugFile.writeln("End FileSystem.convert()");
1259    }
1260
1261  } // convert
1262

1263  // ----------------------------------------------------------
1264

1265  /**
1266   * <p>Read a text file and returns a character array with it</p>
1267   * Enconding is UTF-8 by default
1268   * @param sFilePath Full path of file to be readed
1269   * @return character array with full contents of file
1270   * @throws FileNotFoundException
1271   * @throws IOException
1272   * @throws OutOfMemoryError
1273   * @throws FTPException
1274   */

1275  public static char[] readfile (String JavaDoc sFilePath)
1276    throws FileNotFoundException, IOException, OutOfMemoryError JavaDoc, FTPException {
1277
1278    if (DebugFile.trace) {
1279      DebugFile.writeln("Begin FileSystem.readfile(" + sFilePath + ")");
1280      DebugFile.incIdent();
1281    }
1282
1283    char[] aBuffer;
1284    String JavaDoc sLower = sFilePath.toLowerCase();
1285
1286    if (sLower.startsWith("file://")) sFilePath = sFilePath.substring(7);
1287
1288    if (sLower.startsWith("http://") || sLower.startsWith("https://") || sLower.startsWith("ftp://")) {
1289      aBuffer = new FileSystem().readfilestr(sFilePath, "UTF-8").toCharArray();
1290    }
1291    else {
1292      File oFile = new File(sFilePath);
1293
1294      aBuffer = new char[(int) oFile.length()];
1295
1296      FileReader oReader = new FileReader(oFile);
1297
1298      oReader.read(aBuffer);
1299
1300      oReader.close();
1301
1302      oReader = null;
1303      oFile = null;
1304    }
1305
1306    if (DebugFile.trace) {
1307      DebugFile.decIdent();
1308      DebugFile.writeln("End FileSystem.readfile() : " + String.valueOf(aBuffer.length));
1309    }
1310
1311    return aBuffer;
1312  } // readfile
1313

1314  // ----------------------------------------------------------
1315

1316  /**
1317   * <p>Read a text file and returns a character array with it</p>
1318   * @param sFilePath Full path of file to be readed
1319   * @param sCharSet Encoding character set name
1320   * @return character array with full contents of file
1321   * @throws FileNotFoundException
1322   * @throws IOException
1323   * @throws OutOfMemoryError
1324   * @throws FTPException
1325   */

1326  public static char[] readfile (String JavaDoc sFilePath, String JavaDoc sCharSet)
1327    throws FileNotFoundException, IOException, OutOfMemoryError JavaDoc, FTPException {
1328
1329    if (DebugFile.trace) {
1330      DebugFile.writeln("Begin FileSystem.readfile(" + sFilePath + ", charset=" + sCharSet + ")");
1331      DebugFile.incIdent();
1332    }
1333
1334    char[] aBuffer;
1335    String JavaDoc sLower = sFilePath.toLowerCase();
1336
1337    if (sLower.startsWith("file://")) sFilePath = sFilePath.substring(7);
1338
1339    aBuffer = new FileSystem().readfilestr(sFilePath, sCharSet).toCharArray();
1340
1341    if (DebugFile.trace) {
1342      DebugFile.decIdent();
1343      DebugFile.writeln("End FileSystem.readfile() : " + String.valueOf(aBuffer.length));
1344    }
1345
1346    return aBuffer;
1347  } // readfile
1348

1349  // ----------------------------------------------------------
1350

1351  /**
1352   * <p>Read a binary file into a byte array</p>
1353   * @param sFilePath Full path of file to be readed
1354   * @return byte array with full contents of file
1355   * @throws FileNotFoundException
1356   * @throws IOException
1357   * @throws OutOfMemoryError
1358   * @throws MalformedURLException
1359   * @throws FTPException
1360   */

1361  public byte[] readfilebin (String JavaDoc sFilePath)
1362    throws MalformedURLException JavaDoc, FTPException, FileNotFoundException, IOException, OutOfMemoryError JavaDoc {
1363
1364    if (DebugFile.trace) {
1365      DebugFile.writeln("Begin FileSystem.readfilebin(" + sFilePath + ")");
1366      DebugFile.incIdent();
1367    }
1368
1369    byte[] aRetVal;
1370    String JavaDoc sLower = sFilePath.toLowerCase();
1371
1372    if (sLower.startsWith("file://")) sFilePath = sFilePath.substring(7);
1373
1374    if (sLower.startsWith("http://") || sLower.startsWith("https://")) {
1375
1376      URL JavaDoc oUrl = new URL JavaDoc(sFilePath);
1377
1378      ByteArrayOutputStream oStrm = new ByteArrayOutputStream();
1379
1380      DataHandler JavaDoc oHndlr = new DataHandler JavaDoc(oUrl);
1381
1382      oHndlr.writeTo(oStrm);
1383
1384      aRetVal = oStrm.toByteArray();
1385
1386      oStrm.close();
1387    }
1388    else if (sLower.startsWith("ftp://")) {
1389
1390      FTPClient oFTPC = null;
1391      boolean bFTPSession = false;
1392
1393      splitURI (sFilePath);
1394
1395      try {
1396
1397        if (DebugFile.trace) DebugFile.writeln("new FTPClient(" + sHost + ")");
1398        oFTPC = new FTPClient(sHost);
1399
1400        if (DebugFile.trace) DebugFile.writeln("FTPClient.login(" + sUsr + "," + sPwd + ")");
1401        oFTPC.login(sUsr, sPwd);
1402
1403        bFTPSession = true;
1404
1405        if (DebugFile.trace) DebugFile.writeln("FTPClient.chdir(" + sPath + ")");
1406        oFTPC.chdir(sPath);
1407
1408        ByteArrayOutputStream oStrm = new ByteArrayOutputStream();
1409
1410        oFTPC.setType(FTPTransferType.BINARY);
1411
1412        if (DebugFile.trace) DebugFile.writeln("FTPClient.get(" + sPath + sFile + "," + sFile + ",false)");
1413        oFTPC.get(oStrm, sFile);
1414
1415        aRetVal = oStrm.toByteArray();
1416
1417        oStrm.close();
1418      } catch (FTPException ftpe) {
1419        throw new FTPException(ftpe.getMessage());
1420      }
1421      finally {
1422        if (DebugFile.trace) DebugFile.writeln("FTPClient.quit()");
1423        if (bFTPSession) oFTPC.quit();
1424      }
1425
1426    }
1427    else {
1428
1429      File oFile = new File(sFilePath);
1430      int iFLen = (int) oFile.length();
1431
1432      BufferedInputStream oBfStrm;
1433      FileInputStream oInStrm;
1434
1435      if (iFLen>0) {
1436        aRetVal = new byte[iFLen];
1437        oInStrm = new FileInputStream(oFile);
1438        oBfStrm = new BufferedInputStream(oInStrm, iFLen);
1439
1440        int iReaded = oBfStrm.read(aRetVal, 0, iFLen);
1441
1442        oBfStrm.close();
1443        oInStrm.close();
1444
1445        oInStrm = null;
1446        oFile = null;
1447
1448      }
1449      else
1450        aRetVal = null;
1451    }
1452
1453    if (DebugFile.trace) {
1454      DebugFile.decIdent();
1455      DebugFile.writeln("End FileSystem.readfilebin()");
1456    }
1457
1458    return aRetVal;
1459  } // readfilebin
1460

1461  // ----------------------------------------------------------
1462

1463  /**
1464   * <p>Read a text file into a String</p>
1465   * @param sFilePath Full path of file to be readed
1466   * @param sEncoding Text Encoding for file {UTF-8, ISO-8859-1, ...}<BR>
1467   * if <b>null</b> then if first two bytes of file are FF FE then UTF-8 will be assumed<BR>
1468   * else ISO-8859-1 will be assumed.
1469   * @return String with full contents of file
1470   * @throws FileNotFoundException
1471   * @throws IOException
1472   * @throws OutOfMemoryError
1473   * @throws MalformedURLException
1474   * @throws FTPException
1475   */

1476  public String JavaDoc readfilestr (String JavaDoc sFilePath, String JavaDoc sEncoding)
1477    throws MalformedURLException JavaDoc, FTPException, FileNotFoundException, IOException, OutOfMemoryError JavaDoc {
1478
1479    if (DebugFile.trace) {
1480      DebugFile.writeln("Begin FileSystem.readfilestr(" + sFilePath + "," + sEncoding + ")");
1481      DebugFile.incIdent();
1482    }
1483
1484    String JavaDoc sRetVal;
1485    String JavaDoc sLower = sFilePath.toLowerCase();
1486
1487    if (sLower.startsWith("file://")) sFilePath = sFilePath.substring(7);
1488
1489    if (sLower.startsWith("http://") || sLower.startsWith("https://")) {
1490
1491      URL JavaDoc oUrl = new URL JavaDoc(sFilePath);
1492
1493      ByteArrayOutputStream oStrm = new ByteArrayOutputStream();
1494
1495      DataHandler JavaDoc oHndlr = new DataHandler JavaDoc(oUrl);
1496
1497      oHndlr.writeTo(oStrm);
1498
1499      sRetVal = oStrm.toString(sEncoding);
1500
1501      oStrm.close();
1502    }
1503    else if (sLower.startsWith("ftp://")) {
1504
1505      FTPClient oFTPC = null;
1506      boolean bFTPSession = false;
1507
1508      splitURI (sFilePath);
1509
1510      try {
1511
1512        if (DebugFile.trace) DebugFile.writeln("new FTPClient(" + sHost + ")");
1513        oFTPC = new FTPClient(sHost);
1514
1515        if (DebugFile.trace) DebugFile.writeln("FTPClient.login(" + sUsr + "," + sPwd + ")");
1516        oFTPC.login(sUsr, sPwd);
1517
1518        bFTPSession = true;
1519
1520        if (DebugFile.trace) DebugFile.writeln("FTPClient.chdir(" + sPath + ")");
1521        oFTPC.chdir(sPath);
1522
1523        ByteArrayOutputStream oStrm = new ByteArrayOutputStream();
1524
1525        oFTPC.setType(FTPTransferType.BINARY);
1526
1527        if (DebugFile.trace) DebugFile.writeln("FTPClient.get(" + sPath + sFile + "," + sFile + ",false)");
1528        oFTPC.get(oStrm, sFile);
1529
1530        sRetVal = oStrm.toString(sEncoding);
1531
1532        oStrm.close();
1533      } catch (FTPException ftpe) {
1534        throw new FTPException(ftpe.getMessage());
1535      }
1536      finally {
1537        if (DebugFile.trace) DebugFile.writeln("FTPClient.quit()");
1538        try { if (bFTPSession) oFTPC.quit(); } catch (Exception JavaDoc ignore) { }
1539      }
1540    }
1541    else {
1542
1543      File oFile = new File(sFilePath);
1544      int iFLen = (int) oFile.length();
1545
1546      byte byBuffer[] = new byte[3];
1547      char aBuffer[] = new char[iFLen];
1548      StringBuffer JavaDoc oBuffer = new StringBuffer JavaDoc(iFLen);
1549      BufferedInputStream oBfStrm;
1550      FileInputStream oInStrm;
1551      InputStreamReader oReader;
1552
1553      if (sEncoding==null) {
1554        oInStrm = new FileInputStream(oFile);
1555        oBfStrm = new BufferedInputStream(oInStrm, iFLen);
1556
1557        int iReaded = oBfStrm.read(byBuffer, 0,3);
1558
1559        if (iReaded>2)
1560          // byBuffer = EF BB BF
1561
if (byBuffer[0]==-1 && byBuffer[1]==-2 )
1562            sEncoding = "UTF-16LE";
1563          else if (byBuffer[0]==-2 && byBuffer[1]==-1 )
1564            sEncoding = "UTF-16BE";
1565          else if (byBuffer[0]==-17 && byBuffer[1]==-69 && byBuffer[2]==-65)
1566            sEncoding = "UTF-8";
1567          else
1568            sEncoding = "ISO-8859-1";
1569        else
1570          sEncoding = "ISO-8859-1";
1571
1572        if (DebugFile.trace) DebugFile.writeln("encoding is " + sEncoding);
1573
1574        oBfStrm.close();
1575        oInStrm.close();
1576      }
1577
1578      if (iFLen>0) {
1579        oInStrm = new FileInputStream(oFile);
1580        oBfStrm = new BufferedInputStream(oInStrm, iFLen);
1581
1582        oReader = new InputStreamReader(oBfStrm, sEncoding);
1583
1584        int iReaded = oReader.read(aBuffer, 0, iFLen);
1585
1586        // Skip FF FE character mark for Unidode files
1587
int iSkip = ( (int) aBuffer[0] == 65279 || (int) aBuffer[0] == 65534 ? 1 : 0);
1588
1589        oBuffer.append(aBuffer, iSkip, iReaded - iSkip);
1590
1591        aBuffer = null;
1592
1593        oReader.close();
1594        oBfStrm.close();
1595        oInStrm.close();
1596
1597        oReader = null;
1598        oInStrm = null;
1599        oFile = null;
1600
1601        sRetVal = oBuffer.toString();
1602      }
1603      else
1604        sRetVal = "";
1605    }
1606
1607    if (DebugFile.trace) {
1608      DebugFile.decIdent();
1609      DebugFile.writeln("End FileSystem.readfilestr() : " + String.valueOf(sRetVal.length()));
1610    }
1611
1612    return sRetVal;
1613  } // readfilestr
1614

1615  // ----------------------------------------------------------
1616

1617  /**
1618   * Write a String to a text file using given encoding
1619   * @param sFilePath Full file path. For example "file:///tmp/myfile.txt" or "ftp://localhost:21/tmp/myfile.txt"
1620   * @param sText String to be written
1621   * @param sEncoding Encoding to be used
1622   * see <a HREF="http://java.sun.com/j2se/1.4.2/docs/guide/intl/encoding.doc.html">Java Supported Encodings</a>
1623   * @throws IOException
1624   * @throws OutOfMemoryError
1625   */

1626  public void writefilestr (String JavaDoc sFilePath, String JavaDoc sText, String JavaDoc sEncoding)
1627    throws IOException, OutOfMemoryError JavaDoc {
1628
1629    if (DebugFile.trace) {
1630      DebugFile.writeln("Begin FileSystem.writefilestr(" + sFilePath + ", ..., " + sEncoding + ")");
1631      DebugFile.incIdent();
1632    }
1633
1634    String JavaDoc sLower = sFilePath.toLowerCase();
1635
1636    if (sLower.startsWith("file://")) sFilePath = sFilePath.substring(7);
1637
1638    if (sLower.startsWith("ftp://")) {
1639
1640      FTPClient oFTPC = null;
1641      boolean bFTPSession = false;
1642
1643      splitURI(sFilePath);
1644
1645      try {
1646
1647        if (DebugFile.trace) DebugFile.writeln("new FTPClient(" + sHost + ")");
1648        oFTPC = new FTPClient(sHost);
1649
1650        if (DebugFile.trace) DebugFile.writeln("FTPClient.login(" + sUsr + "," +
1651                                               sPwd + ")");
1652        oFTPC.login(sUsr, sPwd);
1653
1654        bFTPSession = true;
1655
1656        if (DebugFile.trace) DebugFile.writeln("FTPClient.chdir(" + sPath + ")");
1657        oFTPC.chdir(sPath);
1658
1659        oFTPC.setType(FTPTransferType.BINARY);
1660        if (DebugFile.trace) DebugFile.writeln("FTPClient.put(byte[], " + sFile + ")");
1661        oFTPC.put(sText.getBytes(sEncoding), sFile);
1662      }
1663      catch (FTPException ftpe) {
1664        throw new IOException(ftpe.getMessage());
1665      }
1666      finally {
1667        if (DebugFile.trace) DebugFile.writeln("FTPClient.quit()");
1668        try { if (bFTPSession) oFTPC.quit(); } catch (Exception JavaDoc ignore) { }
1669      }
1670    }
1671    else {
1672      FileOutputStream oOutStrm = new FileOutputStream(sFilePath);
1673
1674      if (sText.length() > 0) {
1675          BufferedOutputStream oBFStrm = new BufferedOutputStream(oOutStrm,
1676              sText.length());
1677          OutputStreamWriter oWriter = new OutputStreamWriter(oBFStrm, sEncoding);
1678          oWriter.write(sText);
1679          oWriter.close();
1680          oBFStrm.close();
1681      } // fi (sText!="")
1682

1683      oOutStrm.close();
1684    }
1685    if (DebugFile.trace) {
1686      DebugFile.decIdent();
1687      DebugFile.writeln("End FileSystem.writefilestr()");
1688    }
1689  } // writefilestr
1690

1691  // ----------------------------------------------------------
1692

1693  /**
1694   * Write a byte array to a text file
1695   * @param sFilePath Full file path. For example "file:///tmp/myfile.bin" or "ftp://localhost:21/tmp/myfile.bin"
1696   * @param aBytes Bytes to be written
1697   * @throws IOException
1698   * @since 3.0
1699   */

1700  public void writefilebin (String JavaDoc sFilePath, byte[] aBytes)
1701    throws IOException {
1702
1703    if (DebugFile.trace) {
1704      DebugFile.writeln("Begin FileSystem.writefilebin(" + sFilePath + ", ...)");
1705      DebugFile.incIdent();
1706    }
1707
1708    String JavaDoc sLower = sFilePath.toLowerCase();
1709
1710    if (sLower.startsWith("file://")) sFilePath = sFilePath.substring(7);
1711
1712    if (sLower.startsWith("ftp://")) {
1713
1714      FTPClient oFTPC = null;
1715      boolean bFTPSession = false;
1716
1717      splitURI(sFilePath);
1718
1719      try {
1720
1721        if (DebugFile.trace) DebugFile.writeln("new FTPClient(" + sHost + ")");
1722        oFTPC = new FTPClient(sHost);
1723
1724        if (DebugFile.trace) DebugFile.writeln("FTPClient.login(" + sUsr + "," +
1725                                               sPwd + ")");
1726        oFTPC.login(sUsr, sPwd);
1727
1728        bFTPSession = true;
1729
1730        if (DebugFile.trace) DebugFile.writeln("FTPClient.chdir(" + sPath + ")");
1731        oFTPC.chdir(sPath);
1732
1733        oFTPC.setType(FTPTransferType.BINARY);
1734        if (DebugFile.trace) DebugFile.writeln("FTPClient.put(byte[], " + sFile + ")");
1735        oFTPC.put(aBytes, sFile);
1736      }
1737      catch (FTPException ftpe) {
1738        throw new IOException(ftpe.getMessage());
1739      }
1740      finally {
1741        if (DebugFile.trace) DebugFile.writeln("FTPClient.quit()");
1742        try { if (bFTPSession) oFTPC.quit(); } catch (Exception JavaDoc ignore) { }
1743      }
1744    }
1745    else {
1746      FileOutputStream oOutStrm = new FileOutputStream(sFilePath);
1747      oOutStrm.write(aBytes);
1748      oOutStrm.close();
1749    }
1750    if (DebugFile.trace) {
1751      DebugFile.decIdent();
1752      DebugFile.writeln("End FileSystem.writefilebin()");
1753    }
1754  } // writefilebin
1755

1756  // ----------------------------------------------------------
1757

1758  // ******************
1759
// Private variables
1760

1761  private int OS;
1762  protected String JavaDoc SLASH;
1763  private Runtime JavaDoc oRunner;
1764  private String JavaDoc sUsr;
1765  private String JavaDoc sPwd;
1766  private String JavaDoc sProtocol;
1767  private String JavaDoc sHost;
1768  private String JavaDoc sPort;
1769  private String JavaDoc sPath;
1770  private String JavaDoc sFile;
1771
1772  // ******************
1773
// Static values
1774

1775  public static final int OS_PUREJAVA = 0;
1776  public static final int OS_UNIX = 1;
1777  public static final int OS_WINDOWS = 2;
1778}
1779
Popular Tags