001/**
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v1.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014package ch.qos.logback.core.util;
015
016import ch.qos.logback.core.Context;
017import ch.qos.logback.core.rolling.RolloverFailure;
018import ch.qos.logback.core.spi.ContextAwareBase;
019
020import java.io.*;
021import java.net.MalformedURLException;
022import java.net.URL;
023import java.net.URLConnection;
024
025public class FileUtil extends ContextAwareBase {
026
027    public FileUtil(Context context) {
028        setContext(context);
029    }
030
031    public static URL fileToURL(File file) {
032        try {
033            return file.toURI().toURL();
034        } catch (MalformedURLException e) {
035            throw new RuntimeException("Unexpected exception on file [" + file + "]", e);
036        }
037    }
038
039    /**
040     * Creates the parent directories of a file. If parent directories not specified
041     * in file's path, then nothing is done and this returns gracefully.
042     *
043     * @param file file whose parent directories (if any) should be created
044     * @return {@code true} if either no parents were specified, or if all parent
045     *         directories were created successfully; {@code false} otherwise
046     */
047    static public boolean createMissingParentDirectories(File file) {
048        File parent = file.getParentFile();
049        if (parent == null) {
050            // Parent directory not specified, therefore it's a request to
051            // create nothing. Done! ;)
052            return true;
053        }
054
055        // File.mkdirs() creates the parent directories only if they don't
056        // already exist; and it's okay if they do.
057        parent.mkdirs();
058        return parent.exists();
059    }
060
061    public String resourceAsString(ClassLoader classLoader, String resourceName) {
062        URL url = classLoader.getResource(resourceName);
063        if (url == null) {
064            addError("Failed to find resource [" + resourceName + "]");
065            return null;
066        }
067
068        InputStreamReader isr = null;
069        try {
070            URLConnection urlConnection = url.openConnection();
071            urlConnection.setUseCaches(false);
072            isr = new InputStreamReader(urlConnection.getInputStream());
073            char[] buf = new char[128];
074            StringBuilder builder = new StringBuilder();
075            int count = -1;
076            while ((count = isr.read(buf, 0, buf.length)) != -1) {
077                builder.append(buf, 0, count);
078            }
079            return builder.toString();
080        } catch (IOException e) {
081            addError("Failed to open " + resourceName, e);
082        } finally {
083            if (isr != null) {
084                try {
085                    isr.close();
086                } catch (IOException e) {
087                    // ignore
088                }
089            }
090        }
091        return null;
092    }
093
094    static final int BUF_SIZE = 32 * 1024;
095
096    public void copy(String src, String destination) throws RolloverFailure {
097        BufferedInputStream bis = null;
098        BufferedOutputStream bos = null;
099        try {
100            bis = new BufferedInputStream(new FileInputStream(src));
101            bos = new BufferedOutputStream(new FileOutputStream(destination));
102            byte[] inbuf = new byte[BUF_SIZE];
103            int n;
104
105            while ((n = bis.read(inbuf)) != -1) {
106                bos.write(inbuf, 0, n);
107            }
108
109            bis.close();
110            bis = null;
111            bos.close();
112            bos = null;
113        } catch (IOException ioe) {
114            String msg = "Failed to copy [" + src + "] to [" + destination + "]";
115            addError(msg, ioe);
116            throw new RolloverFailure(msg);
117        } finally {
118            if (bis != null) {
119                try {
120                    bis.close();
121                } catch (IOException e) {
122                    // ignore
123                }
124            }
125            if (bos != null) {
126                try {
127                    bos.close();
128                } catch (IOException e) {
129                    // ignore
130                }
131            }
132        }
133    }
134}