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