001    /*
002    
003      $Id: LocalFileManager.java,v 1.11 2003/04/30 20:49:46 culdesac Exp $
004    
005    */
006    
007    package sharpster.daemon.filemanagement;
008    
009    import sharpster.daemon.SharpsterDaemon;
010    import sharpster.common.*;
011    import java.io.*;
012    import java.util.*;
013    import net.jxta.id.*;
014    /**
015     * Class responsible for the management of local files not stored in the CVS.
016     */
017    
018    public class LocalFileManager {
019    
020        private CVSManager cvsManager;
021    
022        /**
023         * Creates an instance of the object.
024         */
025        public LocalFileManager(CVSManager cvsm) {
026            cvsManager = cvsm;
027        }
028        
029        public boolean localClearDirectory(String workingDirectory) {
030            boolean res = true;
031            
032            File root = new File(workingDirectory);
033            if(root == null || !root.isDirectory()) return false;
034                    
035            File[] fileList = root.listFiles();
036            for(int i=0;i<fileList.length;i++) {
037                if(fileList[i].isDirectory()) {
038                    res = res & localClearDirectory(fileList[i].getAbsolutePath());
039                }
040                fileList[i].delete();
041            }
042                    
043                    
044            return res;
045        }
046        
047        public ResponseCollection localLoadFiles(FileCollection files,
048                                                 String workingDirectory,
049                                                 boolean cvs) {
050            boolean binary = false;
051    
052            for(int i=0;i<files.getFileCount();i++) {
053                SharedFile file = files.getFile(i);
054                try {
055                    File ioFile = new File(workingDirectory,file.getFullPath());
056                    if(ioFile == null || !ioFile.exists()) throw new Exception();
057                    
058                    FileInputStream input = new FileInputStream(ioFile);
059                    if(input == null) throw new Exception();
060                    
061                    byte[] data = new byte[input.available()];
062                    input.read(data,0,input.available());
063                    input.close();
064    
065                    if(cvs) {
066                        SharedFile localFile = cvsManager.translatePath(ioFile.getAbsolutePath());
067                        file.setVersion(localFile.getVersion());
068                        if(localFile != null) binary = localFile.getBody().isBinary();
069                    }
070    
071                    Body body = new Body();
072                    body.setData(data);
073                    body.setBinary(binary);
074                    file.setBody(body);
075                }
076                catch(Exception e) {
077                    e.printStackTrace();
078                    continue;
079                }
080            }
081    
082            return new ResponseCollection();
083        }
084    
085        /**
086         * Saves the specified files in the given working directory. This
087         * method stores additional information, like user and path in CVS,
088         * which exists in the <code>files</code> file collection, in a
089         * configuration file in each directory where files are saved.
090         */
091        public ResponseCollection localSaveFiles(FileCollection files, 
092                                                 String workingDirectory) {
093            for(int i=0;i<files.getFileCount();i++) {
094                try {
095                    SharedFile file = files.getFile(i);
096                    
097                    File dir = new File(workingDirectory,file.getPathInCVS());
098                    if(!dir.exists()) dir.mkdirs();
099    
100                    File hddfile = new File(workingDirectory,file.getFullPath());
101                    hddfile.createNewFile();
102    
103                    FileOutputStream out = new FileOutputStream(hddfile);
104                    if(out != null) {
105                        Body body = file.getBody();
106                        byte[] data = body.getData();
107                        out.write(data,0,data.length);
108                        out.flush();
109                        out.close();
110                    }
111                    else throw new Exception();
112    
113                    if(!ConfigManager.writeFileConfig(file,hddfile)) throw new Exception();
114                }
115                catch(Exception e) {
116                    e.printStackTrace();
117                }
118            }
119    
120            return new ResponseCollection();
121        }
122    
123        /**
124         * Update the <code>files</code> object and inserts a file object with 
125         * its filename and path in the local CVS for each file that is 
126         * specified in the <code>files</code> object.
127         * This is done by reading the CVS configuration files that CVS
128         * stores in each checked out directory. The updated 
129         * <code>files</code> object is returned by a 
130         * <code>ResponseCollection</code>
131         */
132        public ResponseCollection translateLocalPaths(FileCollection files, 
133                                                      String workingDirectory, 
134                                                      boolean cvs) {
135            int count = files.getFileCount();
136            FileCollection newFiles = new FileCollection();
137            FileCollection missingFiles = new FileCollection();
138            FileCollection missingCVSFiles = new FileCollection();
139            ResponseCollection responseCollection = new ResponseCollection();
140            
141            for(int i=0;i<count;i++) {
142                SharedFile sharpsterFile = files.getFile(i);
143                File filteredFile = new File(sharpsterFile.getFileName());
144                
145                if(!filteredFile.isAbsolute()) {
146                    filteredFile = new File(workingDirectory, 
147                                            sharpsterFile.getFileName());
148                }
149    
150                if(filteredFile.exists()) {
151                    //the file is identified, locate it in the local hdd
152                    try {
153                        SharedFile file;
154                        if(cvs) file = cvsManager.translatePath(filteredFile.getCanonicalPath());   
155                        else file = ConfigManager.translatePath(filteredFile.getCanonicalPath());
156                        if(file == null) {
157                            missingCVSFiles.addFile(sharpsterFile);
158                        }
159                        else {
160                            sharpsterFile.setPathInCVS(file.getPathInCVS());
161                            sharpsterFile.setFileName(file.getFileName());
162                            sharpsterFile.setVersion(file.getVersion());
163                        }
164                    } catch(Exception e) {
165                        e.printStackTrace();
166                    }
167                }
168                else {
169                    missingFiles.addFile(sharpsterFile);
170                    continue;
171                }
172                
173                /*else {
174                    File parentFile = filteredFile.getParentFile();
175                    File subFiles[] = parentFile.listFiles(new WildcardFilter(filteredFile.getName()));
176                    if(subFiles != null) {
177                        System.out.println("The file/s was located:");
178                        for(int j=0;j<subFiles.length;j++) {
179                            try {
180                                System.out.println(subFiles[j].getCanonicalPath());
181                            } catch(Exception e) {
182                            }
183                        }
184                    }
185                }*/
186            }
187            
188            if(missingFiles.getFileCount() != 0) {
189                MissingFilesResponse response = new MissingFilesResponse();
190                response.setUser("localhost"); //Should be replaced with the local users real username.
191                response.setOrigin("FileManager"); 
192                response.setError(true);
193                response.setLocation(FileLocation.LOCAL_HDD);
194                response.setFiles(missingFiles);
195                responseCollection.addResponse(response);
196            }
197            
198            if(missingCVSFiles.getFileCount() != 0) {
199                MissingFilesResponse response = new MissingFilesResponse();
200                response.setUser("localhost"); //Should be replaces with the local users real username.
201                response.setOrigin("FileManager");
202                response.setError(true);
203                response.setLocation(FileLocation.LOCAL_CVS);
204                response.setFiles(missingCVSFiles);
205                responseCollection.addResponse(response);
206            }
207    
208            return responseCollection;      
209        }
210    
211        /**
212         * Updates the <code>files</code> object and inserts a file object
213         * with its filename, remote owning user and path to the remote CVS 
214         * for each file which is specified in the <code>files</code> object.
215         * This is done by reading the Sharpster configuration files
216         * which are stored in each directory where remote files are saved.
217         * These configuration files are saved by the 
218         * <code>localSaveFiles</code> method.
219         */
220        public ResponseCollection translateRemotePaths(FileCollection files,
221                                                       FileMap fileMap,
222                                                       boolean recursive) {
223            ResponseCollection responses = new ResponseCollection();
224            FileCollection newFiles = new FileCollection();
225            FileCollection missingFiles = new FileCollection();
226    
227            for(int i=0;i<files.getFileCount();i++) {
228                SharedFile file = files.getFile(i);
229                String filename = file.getFileName();
230                filename = filename.replaceAll("\\x2A",")[^(/)]*(");
231                filename = "(" + filename + ")";
232                
233                LinkedList paths = fileMap.getAllPaths(filename);
234                
235                if(paths.size() == 0) {
236                    missingFiles.addFile(file);
237                    continue;
238                }
239                else if(paths.size() == 1) {
240                    String str = (String)paths.get(0);
241                    ID id = fileMap.getID(str);
242                    if(str.equals(file.getFileName())) {
243                        if(fileMap.isDirectory(id)) {
244                            LinkedList newPaths = fileMap.getAllPaths("("+str+"/).*");
245                            paths.clear();
246                            paths.addAll(newPaths);
247                        }
248                    }
249                }
250    
251                ListIterator iter = paths.listIterator();
252                while(iter.hasNext()) {
253                    String str = (String)iter.next();
254                    ID id = fileMap.getID(str);
255                   
256                    if(!fileMap.isDirectory(id)) {
257                        SharedFile newFile = new SharedFile(file);
258                        int index = str.lastIndexOf('/');
259                        String fp = str.substring(0,index);
260                        String fn = str.substring(index+1,str.length());
261                        newFile.setFileName(fn);
262                        newFile.setPathInCVS(fp);
263                        newFiles.addFile(newFile);
264                    }
265                }
266            }
267    
268            if(missingFiles.getFileCount() > 0) {
269                MissingFilesResponse resp = new MissingFilesResponse();
270                resp.setOrigin("FileManagement");
271                resp.setUser(SharpsterDaemon.getPeerName());
272                resp.setError(true);
273                resp.setLocation(FileLocation.REMOTE_CVS);
274                resp.setFiles(missingFiles);
275                responses.addResponse(resp);
276            }
277    
278            files.removeAllFiles();
279            files.appendCollection(newFiles);
280            
281            return responses;
282        }
283    
284        /**
285         * Verifies that the given <code>files</code> exists.
286         */
287        public ResponseCollection checkFilesExistence(FileCollection files) {
288            return new ResponseCollection();
289        }
290    }