001    /*
002     * $RCSfile: FilesystemToolkit.java,v $
003     *
004     * Created on February 27, 2003, 11:43 AM
005     *
006     * This file is part of the STAR Scheduler.
007     * Copyright (c) 2002-2006 STAR Collaboration - Brookhaven National Laboratory
008     *
009     * STAR Scheduler is free software; you can redistribute it and/or modify
010     * it under the terms of the GNU General Public License as published by
011     * the Free Software Foundation; either version 2 of the License, or
012     * (at your option) any later version.
013     *
014     * STAR Scheduler is distributed in the hope that it will be useful,
015     * but WITHOUT ANY WARRANTY; without even the implied warranty of
016     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
017     * GNU General Public License for more details.
018     *
019     * You should have received a copy of the GNU General Public License
020     * along with STAR Scheduler; if not, write to the Free Software
021     * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
022     */
023    
024    package gov.bnl.star.offline.scheduler.util;
025    
026    import java.io.*;
027    import java.io.File;
028    import java.net.URI;
029    import java.net.URL;
030    import java.util.*;
031    import java.util.Hashtable;
032    import java.util.Map;
033    import java.util.logging.Level;
034    import org.apache.log4j.Logger;
035    
036    
037    
038    
039    
040    
041    /**
042     * Tools for accessing the file system on the host computer. 
043     * @author  Gabriele Carcassi & Jerome LAURET & Levente Hajdu
044     * @version $Revision: 1.15 $ $Date: 2006/11/21 00:41:29 $
045     */
046    public class FilesystemToolkit {
047        static private Logger log = Logger.getLogger(FilesystemToolkit.class.getName());
048        //TODO include wildcard resolution in this class
049        
050        private static String currentDir;
051        
052        /** Creates a new instance of FilesystemToolkit **/
053        private FilesystemToolkit() {
054        }
055        
056    
057     /**    
058      * This function is used to get the current working directory. Because under UNIX file systems can 
059      * be mounted at different locations this function needs to get the path right from the $PWD. All 
060      * attempts to get this call using less expensive java calls such as System.getProperties() and 
061      * java.io.File.getAbsolutePath() returned the operating systems path not the mount point path 
062      * causing problems. Because we are not aware of this problem under windows, windows uses a less 
063      * expensive way of retrieving the path.
064      *
065      *@return the current working directory.
066      */ 
067    public static String getCurrentDirectory()
068    {
069        if (currentDir == null) {
070            if (System.getProperty("os.name").startsWith("Win") ){
071                java.io.File f = new java.io.File(".");
072                currentDir = f.getAbsolutePath();
073            } else {
074                CSHCommandLineTask cwd = new CSHCommandLineTask("echo $PWD", true);
075                cwd.run();
076                currentDir = cwd.getOutput().trim();
077            }  
078        }
079        
080        return currentDir;   
081    }
082        
083        /** Check if a file exist. This is not thread safe and can not time out. **/
084        public static boolean checkIfFileExists(URL file, boolean hostAllowed) {
085            log.debug("Check whether file '" + file.getPath() + "' exists.");
086            
087            if ((file.getHost() != null) && (!file.getHost().equals(""))) {
088                if (hostAllowed) { //TODO: Can't check if a file exists on a non-local disk
089                    return true;
090                } else {
091                    System.out.println(
092                    "The following file can't be specified on a local machine.");
093                    System.out.println("Must be like \"file:/path/name\"");
094                    
095                    return false;
096                }
097            }
098            
099            return new File(file.getPath()).exists();
100        }
101        
102        /** Check if a directory exist. This is not thread safe and can not time out. **/
103        public static boolean checkIfDirExists(URI file, boolean hostAllowed) {
104            String temp = file.getPath();
105            int lastBar = temp.lastIndexOf('/');
106            String path = temp.substring(0, lastBar + 1);
107            return checkIfDirExists(path, file.getHost(), hostAllowed);
108        }
109        
110        /** Check if a directory exist. This is not thread safe and can not time out. **/
111        public static boolean checkIfDirExists(String path, String machine, boolean hostAllowed) {
112            log.debug("Check whether directory " + path + " esists.");
113            if ((machine != null) && (!machine.equals(""))) {
114                if (hostAllowed) {
115                    log.warn( "TODO: Can't check if a directory exists on a non-local disk. Host: '" + machine + "'");
116                    return true;
117                } else {
118                    System.out.println(
119                    "The following file can't be specified on a local machine.");
120                    System.out.println("Must be like \"file:/path/name\"");
121                    
122                    return false;
123                }
124            }
125            
126            return new File(path).exists();
127            
128        }
129        
130        /** Check if a directory exist. This is not thread safe and can not time out. **/
131        public static boolean checkIfDirExists(URL file, boolean hostAllowed) {
132            String temp = file.getPath();
133            int lastBar = temp.lastIndexOf('/');
134            String path = temp.substring(0, lastBar + 1);
135            return checkIfDirExists(path, file.getHost(), hostAllowed);
136        }
137        
138        // TODO: maybe it should be wrapped in an another class
139        public static Map mockWildcards = new Hashtable();
140        public static String[] resolveWildcard(String wildcard) {
141            String[] result = (String[]) mockWildcards.get(wildcard);
142            if (result != null) return result;
143            
144            System.out.println("Resolving File system wildcards");
145            ResolveFilesystemWildcards task = new ResolveFilesystemWildcards(wildcard);
146            task.execute();
147            
148            return task.getResult();
149        }
150        
151        public static Map mockfilelists = new Hashtable();
152        public static List retrieveFileListContents(String fileList, int nfiles) {
153            List result = (List) mockfilelists.get(fileList);
154            if (result != null) return result;
155            
156            log.debug("Getting content of filelist '" + fileList + "'.");
157            
158            try {
159                List files = new ArrayList();
160                BufferedReader r = new BufferedReader( new FileReader(fileList));
161                String line;
162                int fileNum = 0;
163                while(((line = r.readLine()) != null) &&  fileNum != nfiles) {
164                    if (!line.trim().equals("")) {
165                        log.debug("Found file '" + line + "'.");
166                        files.add(line);
167                        fileNum ++;
168                    }
169                }
170                return files;
171            } catch (Exception e) {
172                // TODO Exception user message
173                log.fatal("Couldn't read fileList '" + fileList + "'.");
174                System.out.println("Couldn't read fileList '" + fileList + "'.");
175                throw new RuntimeException();
176            }
177        }
178        
179        public static void main(String[] args) {
180            System.out.println(getCurrentDirectory());
181        }
182    }