001/**
002 *
003 * Copyright the original author or authors
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 */
017package org.jivesoftware.smack.util;
018
019import java.io.BufferedReader;
020import java.io.File;
021import java.io.FileNotFoundException;
022import java.io.FileReader;
023import java.io.FileWriter;
024import java.io.IOException;
025import java.io.InputStream;
026import java.io.InputStreamReader;
027import java.io.Reader;
028import java.net.MalformedURLException;
029import java.net.URI;
030import java.util.ArrayList;
031import java.util.List;
032import java.util.Set;
033import java.util.logging.Level;
034import java.util.logging.Logger;
035
036public final class FileUtils {
037
038    private static final Logger LOGGER = Logger.getLogger(FileUtils.class.getName());
039
040    public static InputStream getStreamForUrl(String url, ClassLoader loader) throws MalformedURLException, IOException {
041        URI fileUri = URI.create(url);
042
043        if (fileUri.getScheme() == null) {
044            throw new MalformedURLException("No protocol found in file URL: " + url);
045        }
046
047        if (fileUri.getScheme().equals("classpath")) {
048            // Get an array of class loaders to try loading the providers files from.
049            List<ClassLoader> classLoaders = getClassLoaders();
050            if (loader != null) {
051                classLoaders.add(0, loader);
052            }
053            for (ClassLoader classLoader : classLoaders) {
054                InputStream is = classLoader.getResourceAsStream(fileUri.getSchemeSpecificPart());
055
056                if (is != null) {
057                    return is;
058                }
059            }
060        }
061        else {
062            return fileUri.toURL().openStream();
063        }
064        return null;
065    }
066
067    /**
068     * Returns default classloaders.
069     *
070     * @return a List of ClassLoader instances.
071     */
072    public static List<ClassLoader> getClassLoaders() {
073        ClassLoader[] classLoaders = new ClassLoader[2];
074        classLoaders[0] = FileUtils.class.getClassLoader();
075        classLoaders[1] = Thread.currentThread().getContextClassLoader();
076
077        // Clean up possible null values. Note that #getClassLoader may return a null value.
078        List<ClassLoader> loaders = new ArrayList<ClassLoader>(classLoaders.length);
079        for (ClassLoader classLoader : classLoaders) {
080            if (classLoader != null) {
081                loaders.add(classLoader);
082            }
083        }
084        return loaders;
085    }
086
087    public static boolean addLines(String url, Set<String> set) throws MalformedURLException, IOException {
088        InputStream is = getStreamForUrl(url, null);
089        if (is == null) return false;
090        BufferedReader br = new BufferedReader(new InputStreamReader(is));
091        String line;
092        while ((line = br.readLine()) != null) {
093            set.add(line);
094        }
095        return true;
096    }
097
098    /**
099     * Reads the contents of a File
100     *
101     * @param file
102     * @return the content of file or null in case of an error
103     * @throws IOException 
104     */
105    public static String readFileOrThrow(File file) throws FileNotFoundException, IOException {
106        Reader reader = null;
107        try {
108            reader = new FileReader(file);
109            char buf[] = new char[8192];
110            int len;
111            StringBuilder s = new StringBuilder();
112            while ((len = reader.read(buf)) >= 0) {
113                s.append(buf, 0, len);
114            }
115            return s.toString();
116        }
117        finally {
118            if (reader != null) {
119                reader.close();
120            }
121        }
122    }
123
124    public static String readFile(File file) {
125        try {
126            return readFileOrThrow(file);
127        } catch (Exception e) {
128            LOGGER.log(Level.WARNING, "readFile", e);
129        }
130        return null;
131    }
132
133    public static void writeFileOrThrow(File file, String content) throws IOException {
134        FileWriter writer = new FileWriter(file, false);
135        writer.write(content);
136        writer.close();
137    }
138
139    public static boolean writeFile(File file, String content) {
140        try {
141            writeFileOrThrow(file, content);
142            return true;
143        }
144        catch (IOException e) {
145            LOGGER.log(Level.WARNING, "writeFile", e);
146            return false;
147        }
148    }
149}