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
041     * specified in file's path, then nothing is done and this returns
042     * gracefully.
043     *
044     * @param file file whose parent directories (if any) should be created
045     * @return {@code true} if either no parents were specified, or if all
046     * parent directories were created successfully; {@code false} otherwise
047     */
048    static public boolean createMissingParentDirectories(File file) {
049        File parent = file.getParentFile();
050        if (parent == null) {
051            // Parent directory not specified, therefore it's a request to
052            // create nothing. Done! ;)
053            return true;
054        }
055
056        // File.mkdirs() creates the parent directories only if they don't
057        // already exist; and it's okay if they do.
058        parent.mkdirs();
059        return parent.exists();
060    }
061
062    public String resourceAsString(ClassLoader classLoader, String resourceName) {
063        URL url = classLoader.getResource(resourceName);
064        if (url == null) {
065            addError("Failed to find resource [" + resourceName + "]");
066            return null;
067        }
068
069        InputStreamReader isr = null;
070        try {
071            URLConnection urlConnection = url.openConnection();
072            urlConnection.setUseCaches(false);
073            isr = new InputStreamReader(urlConnection.getInputStream());
074            char[] buf = new char[128];
075            StringBuilder builder = new StringBuilder();
076            int count = -1;
077            while ((count = isr.read(buf, 0, buf.length)) != -1) {
078                builder.append(buf, 0, count);
079            }
080            return builder.toString();
081        } catch (IOException e) {
082            addError("Failed to open " + resourceName, e);
083        } finally {
084            if (isr != null) {
085                try {
086                    isr.close();
087                } catch (IOException e) {
088                    // ignore
089                }
090            }
091        }
092        return null;
093    }
094
095    static final int BUF_SIZE = 32 * 1024;
096
097    public void copy(String src, String destination) throws RolloverFailure {
098        BufferedInputStream bis = null;
099        BufferedOutputStream bos = null;
100        try {
101            bis = new BufferedInputStream(new FileInputStream(src));
102            bos = new BufferedOutputStream(new FileOutputStream(destination));
103            byte[] inbuf = new byte[BUF_SIZE];
104            int n;
105
106            while ((n = bis.read(inbuf)) != -1) {
107                bos.write(inbuf, 0, n);
108            }
109
110            bis.close();
111            bis = null;
112            bos.close();
113            bos = null;
114        } catch (IOException ioe) {
115            String msg = "Failed to copy [" + src + "] to [" + destination + "]";
116            addError(msg, ioe);
117            throw new RolloverFailure(msg);
118        } finally {
119            if (bis != null) {
120                try {
121                    bis.close();
122                } catch (IOException e) {
123                    // ignore
124                }
125            }
126            if (bos != null) {
127                try {
128                    bos.close();
129                } catch (IOException e) {
130                    // ignore
131                }
132            }
133        }
134    }
135}