001    /**
002     *
003     * Copyright 2005 The Apache Software Foundation
004     *
005     *  Licensed under the Apache License, Version 2.0 (the "License");
006     *  you may not use this file except in compliance with the License.
007     *  You may obtain a copy of the License at
008     *
009     *     http://www.apache.org/licenses/LICENSE-2.0
010     *
011     *  Unless required by applicable law or agreed to in writing, software
012     *  distributed under the License is distributed on an "AS IS" BASIS,
013     *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     *  See the License for the specific language governing permissions and
015     *  limitations under the License.
016     */
017    package org.apache.geronimo.kernel.config;
018    
019    import java.io.File;
020    import java.io.FileInputStream;
021    import java.io.FileOutputStream;
022    import java.io.IOException;
023    import java.io.InputStream;
024    import java.io.OutputStream;
025    import java.io.Reader;
026    import java.io.Writer;
027    import java.net.MalformedURLException;
028    import java.net.URL;
029    import java.util.Collections;
030    import java.util.Enumeration;
031    import java.util.Iterator;
032    import java.util.LinkedHashMap;
033    import java.util.LinkedHashSet;
034    import java.util.Map;
035    import java.util.Set;
036    import java.util.jar.JarFile;
037    import java.util.zip.ZipEntry;
038    
039    /**
040     * @version $Rev: 410741 $ $Date: 2006-05-31 21:35:48 -0700 (Wed, 31 May 2006) $
041     */
042    public class IOUtil {
043        public static void recursiveCopy(File srcDir, File destDir) throws IOException {
044            if (srcDir == null)  throw new NullPointerException("sourceDir is null");
045            if (destDir == null)  throw new NullPointerException("destDir is null");
046            if (!srcDir.isDirectory() || ! srcDir.canRead()) {
047                throw new IllegalArgumentException("Source directory must be a readable directory " + srcDir);
048            }
049            if (destDir.exists()) {
050                throw new IllegalArgumentException("Destination directory already exists " + destDir);
051            }
052            if (srcDir.equals(destDir)) {
053                throw new IllegalArgumentException("Source and destination directory are the same " + srcDir);
054            }
055    
056            destDir.mkdirs();
057            if (!destDir.exists()) {
058                throw new IOException("Could not create destination directory " + destDir);
059            }
060    
061    
062            File[] srcFiles = srcDir.listFiles();
063            if (srcFiles != null) {
064                for (int i = 0; i < srcFiles.length; i++) {
065                    File srcFile = srcFiles[i];
066                    File destFile = new File(destDir, srcFile.getName());
067                    if (srcFile.isDirectory()) {
068                        recursiveCopy(srcFile, destFile);
069                    } else {
070                        copyFile(srcFile, destFile);
071                    }
072                }
073            }
074        }
075    
076        public static void copyFile(File source, File destination) throws IOException {
077            File destinationDir = destination.getParentFile();
078            if (!destinationDir.exists() && !destinationDir.mkdirs()) {
079                throw new IOException("Cannot create directory : " + destinationDir);
080            }
081    
082            InputStream in = null;
083            OutputStream out = null;
084            try {
085                in = new FileInputStream(source);
086                out = new FileOutputStream(destination);
087                writeAll(in, out);
088            } finally {
089                close(in);
090                close(out);
091            }
092        }
093    
094        public static void writeAll(InputStream in, OutputStream out) throws IOException {
095            byte[] buffer = new byte[4096];
096            int count;
097            while ((count = in.read(buffer)) > 0) {
098                out.write(buffer, 0, count);
099            }
100            out.flush();
101        }
102    
103        public static boolean recursiveDelete(File root) {
104            if (root == null) {
105                return true;
106            }
107    
108            if (root.isDirectory()) {
109                File[] files = root.listFiles();
110                if (files != null) {
111                    for (int i = 0; i < files.length; i++) {
112                        File file = files[i];
113                        if (file.isDirectory()) {
114                            recursiveDelete(file);
115                        } else {
116                            file.delete();
117                        }
118                    }
119                }
120            }
121            return root.delete();
122        }
123    
124        public static void flush(OutputStream thing) {
125            if (thing != null) {
126                try {
127                    thing.flush();
128                } catch(Exception ignored) {
129                }
130            }
131        }
132    
133        public static void flush(Writer thing) {
134            if (thing != null) {
135                try {
136                    thing.flush();
137                } catch(Exception ignored) {
138                }
139            }
140        }
141    
142        public static void close(JarFile thing) {
143            if (thing != null) {
144                try {
145                    thing.close();
146                } catch(Exception ignored) {
147                }
148            }
149        }
150    
151        public static void close(InputStream thing) {
152            if (thing != null) {
153                try {
154                    thing.close();
155                } catch(Exception ignored) {
156                }
157            }
158        }
159    
160        public static void close(OutputStream thing) {
161            if (thing != null) {
162                try {
163                    thing.close();
164                } catch(Exception ignored) {
165                }
166            }
167        }
168    
169        public static void close(Reader thing) {
170            if (thing != null) {
171                try {
172                    thing.close();
173                } catch(Exception ignored) {
174                }
175            }
176        }
177    
178        public static void close(Writer thing) {
179            if (thing != null) {
180                try {
181                    thing.close();
182                } catch(Exception ignored) {
183                }
184            }
185        }
186    
187        public static Set search(File root, String pattern) throws MalformedURLException {
188            if (root.isDirectory()) {
189                if (!SelectorUtils.hasWildcards(pattern)) {
190                    File match = new File(root, pattern);
191                    if (match.exists() && match.canRead()) {
192                        return Collections.singleton(match.toURL());
193                    } else {
194                        return Collections.EMPTY_SET;
195                    }
196                } else {
197                    Set matches = new LinkedHashSet();
198                    Map files = listAllFileNames(root);
199                    for (Iterator iterator = files.entrySet().iterator(); iterator.hasNext();) {
200                        Map.Entry entry = (Map.Entry) iterator.next();
201                        String fileName = (String) entry.getKey();
202                        if (SelectorUtils.matchPath(pattern, fileName)) {
203                            File file = (File) entry.getValue();
204                            matches.add(file.toURL());
205                        }
206                    }
207                    return matches;
208                }
209            } else {
210                JarFile jarFile = null;
211                try {
212                    jarFile = new JarFile(root);
213                    URL baseURL = new URL("jar:" + root.toURL().toString() + "!/");
214                    if (!SelectorUtils.hasWildcards(pattern)) {
215                        ZipEntry entry = jarFile.getEntry(pattern);
216                        if (entry != null) {
217                            URL match = new URL(baseURL, entry.getName());
218                            return Collections.singleton(match);
219                        } else {
220                            return Collections.EMPTY_SET;
221                        }
222                    } else {
223                        Set matches = new LinkedHashSet();
224                        Enumeration entries = jarFile.entries();
225                        while (entries.hasMoreElements()) {
226                            ZipEntry entry = (ZipEntry) entries.nextElement();
227                            String fileName = entry.getName();
228                            if (SelectorUtils.matchPath(pattern, fileName)) {
229                                URL url = new URL(baseURL, fileName);
230                                matches.add(url);
231                            }
232                        }
233                        return matches;
234                    }
235                } catch (MalformedURLException e) {
236                    throw e;
237                } catch (IOException e) {
238                    return Collections.EMPTY_SET;
239                } finally {
240                    close(jarFile);
241                }
242            }
243        }
244    
245        public static Map listAllFileNames(File base) {
246            return listAllFileNames(base, "");
247        }
248    
249        private static Map listAllFileNames(File base, String prefix) {
250            if (!base.canRead() || !base.isDirectory()) {
251                throw new IllegalArgumentException(base.getAbsolutePath());
252            }
253            Map map = new LinkedHashMap();
254            File[] hits = base.listFiles();
255            for (int i = 0; i < hits.length; i++) {
256                File hit = hits[i];
257                if (hit.canRead()) {
258                    if (hit.isDirectory()) {
259                        map.putAll(listAllFileNames(hit, prefix.equals("") ? hit.getName() : prefix + "/" + hit.getName()));
260                    } else {
261                        map.put(prefix.equals("") ? hit.getName() : prefix + "/" + hit.getName(), hit);
262                    }
263                }
264            }
265            map.put(prefix, base);
266            return map;
267        }
268    }