FileUtilities.java 13.4 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.pdfg.exception.PDFGBaseException
 *  com.adobe.pdfg.logging.PDFGLogger
 */
package com.adobe.pdfg.common;

import com.adobe.pdfg.common.Guid;
import com.adobe.pdfg.exception.PDFGBaseException;
import com.adobe.pdfg.logging.PDFGLogger;
import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Serializable;
import java.io.Writer;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class FileUtilities {
    private static PDFGLogger pdfgLogger = PDFGLogger.getPDFGLogger(FileUtilities.class);
    private static String pdfgUserId = null;
    protected static final int BUFFER = 2048;
    protected static File guidRootDir = null;

    public static File getGuidRootDir() {
        if (guidRootDir == null) {
            String tmpDir = null;
            try {
                tmpDir = System.getProperty("com.adobe.tempDirectory");
            }
            catch (Exception e) {
                pdfgLogger.trace(e.getMessage(), null, (Throwable)e);
            }
            if (tmpDir == null || "".equals(tmpDir)) {
                try {
                    tmpDir = System.getProperty("java.io.tmpdir");
                }
                catch (Exception e) {
                    pdfgLogger.trace(e.getMessage(), null, (Throwable)e);
                }
            } else {
                tmpDir = new File(tmpDir).getParent();
            }
            String userId = System.getProperty("user.name");
            if (pdfgUserId == null || "".equals(pdfgUserId)) {
                pdfgUserId = userId.replaceAll("[\\$,\\\\,\\/,\\?,\\@,\\*,\\+,\\\",\\|,\\:,\\;\\,\\=,>,<,\\[,\\]]", "_");
            }
            guidRootDir = new File(tmpDir, "pdfg-" + pdfgUserId);
        }
        return guidRootDir;
    }

    public static File getGuidDir(String guid) throws IllegalArgumentException {
        if (guid == null || guid.length() < 6) {
            throw new IllegalArgumentException("Invalid ID - '" + guid + "'");
        }
        File aesDir = FileUtilities.getGuidRootDir();
        File dir1 = new File(aesDir, guid.substring(0, 2));
        File directory = new File(dir1, guid.substring(2));
        return directory;
    }

    public static File createGuidDir(String guid) throws IOException {
        File directory = FileUtilities.getGuidDir(guid);
        while (directory.exists()) {
            directory = FileUtilities.getGuidDir(new Guid().toString());
        }
        if (!directory.mkdirs()) {
            throw new IOException("Directory '" + directory.getCanonicalPath() + "' couldn't be created or already existed");
        }
        return directory;
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    public static File saveStringToUtf8GuidFile(String str, File directory, String filename) throws IOException, PDFGBaseException {
        File outputFile = new File(directory, filename);
        BufferedWriter writer = null;
        try {
            writer = new BufferedWriter(new OutputStreamWriter((OutputStream)new FileOutputStream(outputFile), "UTF-8"));
            writer.write(str);
        }
        finally {
            if (writer != null) {
                writer.flush();
                writer.close();
                writer = null;
            }
        }
        return outputFile;
    }

    public static String getExtension(String canonicalPath) {
        String result = "";
        if (canonicalPath != null) {
            int lastDot = canonicalPath.lastIndexOf(46);
            int lastSep = canonicalPath.lastIndexOf(File.separatorChar);
            int canonicalLength = canonicalPath.length();
            if (-1 < lastDot && lastDot + 1 < canonicalLength && lastSep < lastDot) {
                result = canonicalPath.substring(lastDot + 1, canonicalLength);
            }
        }
        return result;
    }

    public static String changeExtension(String canonicalPath, String extension) {
        String result = "";
        String basePath = "";
        if (canonicalPath != null) {
            String oldExtension = FileUtilities.getExtension(canonicalPath);
            int toRemove = oldExtension.length() + 1;
            int canonicalLength = canonicalPath.length();
            int toStay = canonicalLength - toRemove;
            if (toStay < 0) {
                toStay = 0;
            }
            basePath = canonicalPath.substring(0, toStay);
        }
        if (extension != null) {
            StringBuffer newPath = new StringBuffer(basePath);
            newPath.append('.');
            newPath.append(extension);
            result = newPath.toString();
        }
        return result;
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    public static byte[] objectToByteArray(Object obj) throws IOException {
        if (obj == null || !(obj instanceof Serializable)) {
            return new byte[0];
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream objectStream = null;
        try {
            objectStream = new ObjectOutputStream(baos);
            objectStream.writeObject(obj);
            objectStream.flush();
            byte[] bytedata = baos.toByteArray();
            objectStream.close();
            byte[] arrby = bytedata;
            return arrby;
        }
        finally {
            if (objectStream != null) {
                objectStream.close();
            } else {
                baos.close();
            }
        }
    }

    public static void binaryDataToFile(byte[] sourceData, File dataFile) throws FileNotFoundException, IOException {
        FileOutputStream fos = new FileOutputStream(dataFile);
        fos.write(sourceData);
        fos.close();
    }

    public static byte[] fileToByteArray(File sourceFile) throws IOException {
        byte[] byteData = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        FileUtilities.copyStreams(new FileInputStream(sourceFile), baos, -1, -1, true, false);
        byteData = baos.toByteArray();
        baos.close();
        return byteData;
    }

    public static String fileToString(File sourceFile) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        FileUtilities.copyStreams(new FileInputStream(sourceFile), baos, -1, -1, true, false);
        return baos.toString();
    }

    public static String inputStreamToString(InputStream is) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        FileUtilities.copyStreams(is, baos, -1, -1, true, false);
        return baos.toString("UTF-8");
    }

    public static boolean deleteDir(File dir) {
        if (dir == null) {
            return false;
        }
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; ++i) {
                boolean success = FileUtilities.deleteDir(new File(dir, children[i]));
                if (success) continue;
                return false;
            }
        }
        return dir.delete();
    }

    public static long copyStreams(InputStream inputStream, OutputStream outputStream) throws IOException {
        return FileUtilities.copyStreams(inputStream, outputStream, -1, -1);
    }

    protected static long copyStreams(InputStream inputStream, OutputStream outputStream, long length, int buffSize) throws IOException {
        long bytesToWrite;
        if (buffSize < 0) {
            buffSize = 16384;
        }
        if ((bytesToWrite = length) < 0) {
            bytesToWrite = Long.MAX_VALUE;
        }
        long totalBytesWritten = 0;
        int bytesInBuff = 0;
        byte[] buff = new byte[buffSize];
        while (bytesToWrite > 0 && (bytesInBuff = inputStream.read(buff)) != -1) {
            if (bytesToWrite < (long)bytesInBuff) {
                bytesInBuff = (int)bytesToWrite;
            }
            outputStream.write(buff, 0, bytesInBuff);
            bytesToWrite -= (long)bytesInBuff;
            totalBytesWritten += (long)bytesInBuff;
        }
        outputStream.flush();
        return totalBytesWritten;
    }

    public static void addFilesToZip(String dest, String path, ZipOutputStream out) {
        byte[] data = new byte[2048];
        File f = new File(path);
        File[] files = f.listFiles();
        BufferedInputStream origin = null;
        try {
            for (int i = 0; i < files.length; ++i) {
                if (files[i].isFile() && !files[i].getCanonicalPath().equals(dest)) {
                    int count;
                    FileInputStream fi = new FileInputStream(files[i]);
                    origin = new BufferedInputStream(fi, 2048);
                    ZipEntry entry = new ZipEntry(files[i].getAbsolutePath());
                    out.putNextEntry(entry);
                    while ((count = origin.read(data, 0, 2048)) != -1) {
                        out.write(data, 0, count);
                    }
                    origin.close();
                }
                if (!files[i].isDirectory()) continue;
                FileUtilities.addFilesToZip(dest, files[i].getCanonicalPath(), out);
            }
        }
        catch (FileNotFoundException t) {
            pdfgLogger.trace(t.getMessage(), null, (Throwable)t);
        }
        catch (IOException t) {
            pdfgLogger.trace(t.getMessage(), null, (Throwable)t);
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    public static long copyStreams(InputStream in, OutputStream out, long copyLength, int preferredCopySize, boolean closeInput, boolean closeOutput) throws IOException {
        try {
            long l = FileUtilities.copyStreams(in, out, copyLength, preferredCopySize);
            return l;
        }
        finally {
            if (closeInput) {
                FileUtilities.closeStream(in);
            }
            if (closeOutput) {
                FileUtilities.closeStream(out);
            }
        }
    }

    public static void closeStream(InputStream is) {
        if (is != null) {
            try {
                is.close();
                is = null;
            }
            catch (IOException ie) {
                pdfgLogger.trace(ie.getMessage(), null, (Throwable)ie);
            }
        }
    }

    public static void closeStream(OutputStream os) {
        if (os != null) {
            try {
                os.close();
                os = null;
            }
            catch (IOException ie) {
                pdfgLogger.trace(ie.getMessage(), null, (Throwable)ie);
            }
        }
    }

    public static void closeReader(Reader in) {
        if (in != null) {
            try {
                in.close();
                in = null;
            }
            catch (IOException e) {
                pdfgLogger.trace(e.getMessage(), null, (Throwable)e);
            }
        }
    }

    public static void closeWriter(Writer out) {
        if (out != null) {
            try {
                out.close();
                out = null;
            }
            catch (IOException e) {
                pdfgLogger.trace(e.getMessage(), null, (Throwable)e);
            }
        }
    }

    public static boolean isLegalFileName(String name) {
        if (name == null) {
            return false;
        }
        char[] badChars = new char[]{'/', '\\', ':', '*', '?', '\"', '<', '>', '|'};
        boolean result = true;
        for (int i = 0; result && i < badChars.length; ++i) {
            result = name.indexOf(badChars[i]) == -1;
        }
        return result;
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    public static void moveFile(File source, File destination) {
        boolean bRenameSuccessful = source.renameTo(destination);
        if (!bRenameSuccessful) {
            FileInputStream in = null;
            FileOutputStream out = null;
            try {
                int nBytesRead;
                int BUFFER_SIZE_BYTES = 32768;
                in = new FileInputStream(source);
                out = new FileOutputStream(destination);
                byte[] buffer = new byte[32768];
                while ((nBytesRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, nBytesRead);
                }
            }
            catch (IOException e) {
                pdfgLogger.trace(e.getMessage(), null, (Throwable)e);
            }
            finally {
                if (in != null) {
                    try {
                        in.close();
                    }
                    catch (IOException e) {
                        pdfgLogger.trace(e.getMessage(), null, (Throwable)e);
                    }
                }
                if (out != null) {
                    try {
                        out.close();
                    }
                    catch (IOException e) {
                        pdfgLogger.trace(e.getMessage(), null, (Throwable)e);
                    }
                }
            }
            source.delete();
        }
    }

    public static void setGuidRootDir(File guidRootDir) {
        FileUtilities.guidRootDir = guidRootDir;
    }
}