san.FileSystemImpl.java Source code

Java tutorial

Introduction

Here is the source code for san.FileSystemImpl.java

Source

/**
* Copyright (c) 2001-2012 "Redbasin Networks, INC" [http://redbasin.org]
*
* This file is part of Redbasin OpenDocShare community project.
*
* Redbasin OpenDocShare is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

package san;

import util.RegexStrUtil;
import util.SanConstants;
import util.SanUtils;
import san.SanException;

import java.util.ArrayList;
import java.util.List;

import java.io.IOException;
import java.io.File;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.BufferedInputStream;
import java.io.BufferedInputStream;
import java.io.*;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
//import org.apache.commons.fileupload.FileItem;

public class FileSystemImpl implements FileSystemApi {

    /** Logger for this class and subclasses */
    protected final Log logger = LogFactory.getLog(getClass());

    /**
    * that creates the file in the tomcat directory:
    * $CATALINA_HOME/<mountedfilesystem>/<directory>/<fileName>
    * you can mount any san root on the video directory and save the file
    * to a san volume.  Creates directory if it does not exist
    * @param blob - data  
    * @param fileName  name of the file
    * @param filePath  directoryname
    * @param path  pathname
    * @throws Exception
    * @return success or failure
    */
    public void saveFile(byte[] blob, String fileName, String filePath, String path) throws SanException {

        // retrieve the video using FileUpload API
        // byte[] blob = item.get();
        // once retrieved, save it to a file in tomcat's home
        //File dir = new File("video");

        if ((blob == null) || RegexStrUtil.isNull(fileName) || RegexStrUtil.isNull(filePath)
                || RegexStrUtil.isNull(path)) {
            throw new SanException("params are null");
        }

        logger.info("saveFile ");

        File dir = getDir(filePath, path);
        if (dir == null) {
            throw new SanException("saveFile(), getDir()" + path + filePath);
        }
        if (!dir.exists()) {
            dir.mkdir();
            logger.info("creating dir" + filePath);
        }

        File file = new File(dir, fileName);
        if (file == null) {
            throw new SanException("saveFile(), file null, new File(dir,filename)" + path + filePath + fileName);
        }
        //String newpath = file.getAbsolutePath();
        logger.info("saveFile() file path: " + path);
        try {
            OutputStream fos = new FileOutputStream(file);
            OutputStream os = new BufferedOutputStream(fos);
            os.write(blob);
            os.close();
            fos.close();
        } catch (Exception e) {
            throw new SanException("saveFile() error in writing the file to directory " + filePath + " filename "
                    + fileName + e.getMessage(), e);
        }
    }

    /**
    * renameFile() - renames the file 
    * @param filePath - filePath 
    * @param path - path
    * @param fileName - src fileName
    * @param dest - destination file name
    * @throws - error when the File object is null
    */
    public void renameFile(String filePath, String path, String fileName, String dest) throws SanException {

        logger.info("filePath = " + filePath + " path = " + path + " fileName = " + fileName + " dest = " + dest);

        File dir = getDir(filePath, path);
        if (dir == null) {
            throw new SanException("renameFile(), dir is null " + path + filePath);
        }
        try {
            File file = new File(dir, fileName);
            if (file == null) {
                throw new SanException("renameFile(), file null " + path + fileName + fileName);
            }

            File destFile = null;
            if (file.exists()) {
                destFile = new File(dir, dest);
            } else {
                throw new SanException(
                        "renameFile(), file does not exist, path=" + filePath + " fileName= " + fileName);
            }

            if (destFile == null) {
                throw new SanException("renameFile(), destFile null " + path + filePath + dest);
            }

            if (destFile.exists()) {
                logger.info("destfile exists" + dest);
                return;
            } else {
                logger.info("destFile does not exist " + dest);
                try {
                    file.renameTo(destFile);
                } catch (SanException e1) {
                    throw new SanException(
                            "renameTo() error, destFile " + destFile + " Error msg= " + e1.getMessage(), e1);
                }
            }
        } catch (SanException e) {
            throw new SanException("renameFile(), new File(), path=" + path + " filePath=" + filePath + " fileName="
                    + fileName + " destFile=" + dest + " Error Msg=" + e.getMessage(), e);
        }
    }

    /**
    * getDir() - returns the File directory
    * @param filePath - directory name
    * @param path - path
    * @return File - File Object
    * @throws - error when the File object is null
    */
    private File getDir(String filePath, String path) throws SanException {

        StringBuffer sb = null;
        if (!RegexStrUtil.isNull(path)) {
            //sb = new StringBuffer("'");
            //sb.append(path);
            sb = new StringBuffer(path);
            if (sb == null) {
                throw new SanException("new StringBuffer(path) is null");
            }
            if (!RegexStrUtil.isNull(filePath)) {
                sb.append(filePath);
                //sb.append("'");
            }
        } else {
            if (!RegexStrUtil.isNull(filePath)) {
                sb = new StringBuffer(filePath);
                //sb = new StringBuffer("'");
                //sb.append(filePath);
                //sb.append("'");
            }
        }
        if (sb == null) {
            throw new SanException("getDir() new StringBuffer(filePath) sb is null");
        }
        logger.info("getDir() sb.toString() " + sb.toString());

        File dir = null;
        try {
            dir = new File(sb.toString());
        } catch (Exception e) {
            throw new SanException("error new File(), " + e.getMessage(), e);
        }
        if (dir == null) {
            throw new SanException("getDir() dir == null, dirpath " + sb.toString());
        }
        return dir;
    }

    /**
    * deleteFile() - deletes file 
    * @param filePath - file Path
    * @param path - san or mounted path
    * @param fileName - fileName
    * @throws - error when the File object is null
    */
    public void deleteFile(String filePath, String path, String fileName) throws SanException {
        File dir = getDir(filePath, path);
        if (dir == null) {
            throw new SanException("deleteFile(), getDir() null, dirpath= " + path + filePath);
        }

        if (!dir.exists()) {
            logger.info("deleteFile() dir does not exist");
            throw new SanException("deleteFile(), directory does not exist, dirpath " + path + filePath);
        }

        File file = null;
        try {
            file = new File(dir, fileName);
        } catch (Exception e) {
            throw new SanException("new File() error, deleteFile(), " + e.getMessage(), e);
        }

        if (file == null) {
            throw new SanException("deleteFile(), file.delete() path= " + path + ",filePath=" + filePath
                    + ",fileName=" + fileName);
        } else {
            try {
                if (file.exists()) {
                    file.delete();
                } else {
                    throw new SanException("deleteFile(), file does not exists. file.exists() path= " + path
                            + ",filePath=" + filePath + ",fileName=" + fileName);
                }
            } catch (Exception e) {
                throw new SanException("file.delete error, " + e.getMessage(), e);
            }
        }
    }

    /**
    * createDirectory() - creates a directory
    * @param filePath - file path where directory is created
    * @param path - path
    * @throws SanException - error when the File object is null
    *              when the directory already exists
    */
    public void createDirectory(String dirPath, String path) throws SanException {

        logger.info("createDirectory() path + dirPath = " + path + dirPath);

        File dir = getDir(dirPath, path);
        if (dir == null) {
            throw new SanException("createDirectory() file null, new File(dir,filename)" + path + dirPath);
        }

        if (!dir.exists()) {
            logger.info("dir does not exist");
            try {
                dir.mkdir();
                logger.info("mkdir completed, " + dirPath);
            } catch (Exception e) {
                throw new SanException("dir.mkdir(), createDirectory(), directory already exists" + path + dirPath
                        + e.getMessage(), e);
            }
        } else {
            throw new SanException(
                    "createDirectory(), directory already exists, path=" + path + " dirPath=" + dirPath);
        }
        logger.info("createDirectory() completed");
    }

    /**
    * listDirFiles() - list files in a directory
    * @param filePath - includes the directory path for files to list
    * @param path - path (prefix)
    * @return string[] -list of filenames
    * @throws SanException - error when the File object is null
    */
    public String[] listDirFiles(String filePath, String path) throws SanException {
        File dir = getDir(filePath, path);
        if (dir == null) {
            throw new SanException("listDirFiles() dir null, getDir(dirPath,path)" + path + filePath);
        }

        try {
            if (dir.exists()) {
                return (dir.list());
            }
        } catch (Exception e) {
            throw new SanException("error in listing directory " + e.getMessage(), e);
        }
        if (!dir.exists()) {
            throw new SanException("listDirFiles(), directory does not exist " + path + filePath);
        }
        return null;
    }

    /**
    * readFile() - read file
    * @param filePath - filePath
    * @param path - path
    * @param fileName - file to be read
    * @return byte[]
    * @throws SanException - error when the File object is null
    */
    public byte[] readFile(String filePath, String path, String fileName) throws SanException {

        File dir = getDir(filePath, path);
        if (dir == null) {
            throw new SanException("readFile(), directory does not exist" + path + filePath + fileName);
        } else {
            if (!dir.exists()) {
                throw new SanException("readFile(), directory does not exist" + path + filePath + fileName);
            }
        }

        File file = null;
        try {
            file = new File(dir, fileName);
        } catch (Exception e) {
            throw new SanException("new File() error, readFile, " + e.getMessage(), e);
        }

        if (file == null) {
            throw new SanException("readFile(), file null, new File(dir,filename)" + path + filePath + fileName);
        }

        InputStream os = null;
        InputStream fos = null;
        byte[] blob = new byte[(int) file.length()];
        try {
            fos = new FileInputStream(file);
            os = new BufferedInputStream(fos);
            if (os.read(blob) == -1) {
                throw new SanException("readFile(), error reading file," + path + filePath + fileName);
            }
            os.close();
            fos.close();
        } catch (Exception e) {
            try {
                if (os != null) {
                    os.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (Exception e1) {
                throw new SanException("os.close(), fos.close() error " + path + filePath + fileName, e1);
            }
            throw new SanException("readFile() error in writing the file to directory " + filePath + " filename "
                    + fileName + e.getMessage(), e);
        }
        return blob;
    }

    /**
     * deleteDirectory - deletes directory and the files within the directory
     * @param dirPath - directory path
     * @param path - path (prefix)
     * @returns - none
     * @throws - exception
     */
    public void deleteDirectory(String dirPath, String path) throws SanException {
        if (RegexStrUtil.isNull(dirPath) || RegexStrUtil.isNull(path)) {
            throw new SanException("deleteDirectory(), dirPath or path is null");
        }

        File dir = getDir(dirPath, path);
        if (dir == null) {
            throw new SanException("deleteDirectory() file null, getDir(dirPath,path)" + path + dirPath);
        }

        try {
            if (dir.exists()) {
                String[] fileList = dir.list();
                if (fileList == null) {
                    dir.delete(); // remove directory
                } else {
                    for (int i = 0; i < fileList.length; i++) {
                        if (!RegexStrUtil.isNull(fileList[i])) {
                            logger.info("fileList[" + i + "]=" + fileList[i]);
                            try {
                                File myFile = new File(dir, fileList[i]);
                                if (myFile != null && myFile.exists()) {
                                    logger.info("deleting file[" + i + "]=" + fileList[i]);
                                    myFile.delete(); // remove file 
                                }
                            } catch (Exception e) {
                                throw new SanException(
                                        "deleteDirectory() error in deleting file from a directory, fileName = "
                                                + fileList[i] + ", path= " + path + e.getMessage(),
                                        e);
                            }
                        }
                    }
                    dir.delete(); // remove directory
                }
            }
        } catch (Exception e) {
            throw new SanException("error, deleteDirectory(), " + e.getMessage(), e);
        }
    }

    /**
    * getFreeSpace()
    * @param dirpath - directory path
    * @param path - path
    * @throws - SanException
    * @returns - Returns the number of unallocated bytes 
    *            in the partition named by this abstract path name
    */
    public long getFreeSpace(String dirPath, String path) throws SanException {

        if (RegexStrUtil.isNull(dirPath) || RegexStrUtil.isNull(path)) {
            throw new SanException("getFreeSpace(), dirPath or path is null");
        }

        File dir = getDir(dirPath, path);
        if (dir == null) {
            throw new SanException("getFreeSapce() " + path + dirPath);
        }

        if (dir.exists()) {
            //return dir.getFreeSpace();
            //long freeSpace = dir.getFreeSpace();
            //System.out.println("freeSpace = " + freeSpace);
            //return freeSpace;
        }
        return 0;
    }

    /**
    * getUsableSapce()
    * @param dirPath - directory path
    * @param path - path
    * @throws - SanException
    * @returns - Returns the number of bytes available to this VM
    *            in the partition named by this abstract path name
    */
    public long getUsableSpace(String dirPath, String path) throws SanException {

        if (RegexStrUtil.isNull(dirPath) || RegexStrUtil.isNull(path)) {
            throw new SanException("getFreeSpace(), dirPath or path is null");
        }

        File dir = getDir(dirPath, path);
        if (dir == null) {
            throw new SanException("getFreeSapce() " + path + dirPath);
        }

        try {
            if (dir.exists()) {
                long usableSpace = dir.getUsableSpace();
                logger.info("usableSpace = " + usableSpace);
                return dir.getUsableSpace();
            } else {
                return 0;
            }
        } catch (Exception e) {
            throw new SanException("error in dir.getUsableSpace()" + e.getMessage(), e);
        }
    }

    /**
    * getTotalSpace()
    * @param dirPath - directory path
    * @param path - path
    * @throws - SanException
    * @returns - Returns the size of the partition named by this 
    *            abstract path name
    */
    public long getTotalSpace(String dirPath, String path) throws SanException {

        if (RegexStrUtil.isNull(dirPath) || RegexStrUtil.isNull(path)) {
            throw new SanException("getTotalSpace(), dirPath or path is null");
        }

        File dir = getDir(dirPath, path);
        if (dir == null) {
            throw new SanException("getTotalSpace() " + path + dirPath);
        }

        try {
            if (dir.exists()) {
                long totalSpace = dir.getTotalSpace();
                logger.info("totalSpace = " + totalSpace);
                return dir.getTotalSpace();
            } else {
                return 0;
            }
        } catch (Exception e) {
            throw new SanException("error in dir.getTotalSpace()" + e.getMessage(), e);
        }
    }

    /**
    * getFileSize()
    * @param dirPath - directory path
    * @param path - path
    * @throws - SanException
    * @returns - Returns the size of the partition named by this 
    *            abstract path name
    */
    public long getFileSize(String filePath, String path, String fileName) throws SanException {

        File dir = getDir(filePath, path);
        if (dir == null) {
            throw new SanException("getFileSize(), directory does not exist" + path + filePath + fileName);
        } else {
            if (!dir.exists()) {
                throw new SanException("getFileSize(), directory does not exist" + path + filePath + fileName);
            }
        }

        long fileSize = 0;
        try {
            File file = new File(dir, fileName);
            if (file == null) {
                throw new SanException(
                        "getFileSize(), file null, new File(dir,filename)" + path + filePath + fileName);
            } else {
                fileSize = file.length();
                logger.info("fileSize = " + fileSize);
            }
        } catch (Exception e) {
            throw new SanException("file.length() error, " + e.getMessage(), e);
        }
        return fileSize;
    }

    /**
    * moveFile() - move file 
    * @param filePath - filePath 
    * @param path - path
    * @param fileName - fileName
    * @param destPath - destination filePath
    * @param destFileName - destinationFile
    * @throws - error when the File object is null
    */
    public void moveFile(String filePath, String path, String fileName, String destPath, String destFileName)
            throws SanException {

        logger.info("filePath = " + filePath + " path = " + path + " fileName = " + fileName + " destPath = "
                + destPath + " destFileName = " + destFileName);

        StringBuffer srcdir = new StringBuffer(path);
        srcdir.append(filePath);

        logger.info("srcdir= " + srcdir.toString());

        StringBuffer newdir = new StringBuffer(path);
        newdir.append(destPath);
        newdir.append(File.separator);
        newdir.append(destFileName);

        logger.info("newdir= " + newdir.toString());

        try {
            Runtime runtime = Runtime.getRuntime();

            // It is important to break up the command into a String[] array
            // I couldn't get it working without resorting to arg array
            //  Process proc = runtime.exec(new String[] {"/bin/mv", srcdir.toString() + fileName, newdir.toString()});
            Process proc = runtime
                    .exec(new String[] { SanConstants.sanMove, srcdir.toString() + fileName, newdir.toString() });

            // Very important to check errors returned by the process as
            // the java program will not print out the error that is output by
            // the child process unless you do this
            InputStream stdin = proc.getErrorStream();
            InputStreamReader isr = new InputStreamReader(stdin);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null)
                throw new SanException("error " + line);
        } catch (Exception e) {
            throw new SanException("error " + e.getMessage());
        }
    }

    /**
    * deleteRoot() - deletes the entire directory including subdirs, files
    * @param filePath - filePath 
    * @param path - path
    * @param fileName - fileName
    * @throws - error when the File object is null
    */
    public void deleteAll(String filePath, String path, String fileName) throws SanException {

        logger.info("filePath = " + filePath + " path = " + path + " fileName = " + fileName);

        StringBuffer srcdir = new StringBuffer(path);
        srcdir.append(filePath);
        logger.info("srcdir= " + srcdir.toString());

        try {
            Runtime runtime = Runtime.getRuntime();

            // It is important to break up the command into a String[] array
            //  Process proc = runtime.exec(new String[] {"/bin/rm -f", srcdir.toString() + fileName, newdir.toString()});

            Process proc = runtime.exec(new String[] { SanConstants.sanRemove, SanConstants.sanRemoveOption,
                    srcdir.toString() + fileName });

            // Very important to check errors returned by the process as
            // the java program will not print out the error that is output by
            // the child process unless you do this
            InputStream stdin = proc.getErrorStream();
            InputStreamReader isr = new InputStreamReader(stdin);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null)
                throw new SanException("error " + line);
        } catch (Exception e) {
            throw new SanException("deleteAll() using sanConstants.sanRemove, error " + e.getMessage());
        }
    }

    /**
    * copyDirectory() - copy the entire directory to another directory using unix command (cp -r)
    * @param filePath - filePath 
    * @param path - path
    * @param fileName - fileName or directory name
    * @param destPath - destination filePath
    * @param destFileName - destinationFile
    * @throws - error when the File object is null
    */
    public void copyDirectory(String filePath, String path, String fileName, String destPath, String destFileName)
            throws SanException {

        logger.info("filePath = " + filePath + " path = " + path + " fileName = " + fileName + " destPath = "
                + destPath + " destFileName = " + destFileName);

        StringBuffer srcdir = new StringBuffer(path);
        srcdir.append(filePath);

        logger.info("srcdir= " + srcdir.toString());

        StringBuffer newdir = new StringBuffer(path);
        newdir.append(destPath);
        if (!destPath.endsWith(File.separator)) {
            newdir.append(File.separator);
        }
        newdir.append(destFileName);

        logger.info("newdir= " + newdir.toString());

        try {
            Runtime runtime = Runtime.getRuntime();

            // It is important to break up the command into a String[] array
            // I couldn't get it working without resorting to arg array
            //  Process proc = runtime.exec(new String[] {"/bin/mv", srcdir.toString() + fileName, newdir.toString()});
            Process proc = runtime.exec(new String[] { SanConstants.sanCopy, SanConstants.sanCopyOption,
                    srcdir.toString() + fileName, newdir.toString() });

            // Very important to check errors returned by the process as
            // the java program will not print out the error that is output by
            // the child process unless you do this
            InputStream stdin = proc.getErrorStream();
            InputStreamReader isr = new InputStreamReader(stdin);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null)
                throw new SanException("error " + line);
        } catch (Exception e) {
            throw new SanException("error " + e.getMessage());
        }
    }

    /**
    * diskUsageOfDirectory() - get the disk usage of this directory
    * @param dirName - dirName
    * @param path - path
    * @param filePath - path of the directory (if there is any from db)
    * @throws - error when the File object is null
    */
    public String diskUsageOfDirectory(String dirName, String path, String filePath) throws SanException {

        logger.info("dirName = " + dirName + " path = " + path + " filePath = " + filePath);

        StringBuffer srcdir = new StringBuffer(path);
        srcdir.append(filePath);

        logger.info("srcdir= " + srcdir.toString());

        try {
            Runtime runtime = Runtime.getRuntime();

            // It is important to break up the command into a String[] array
            // I couldn't get it working without resorting to arg array
            //  Process proc = runtime.exec(new String[] {"/bin/mv", srcdir.toString() + fileName, newdir.toString()});
            Process proc = runtime.exec(new String[] { SanConstants.sanDiskUsage, SanConstants.sanDiskUsageOption1,
                    SanConstants.sanDiskUsageOption2, SanConstants.sanDiskUsageOption3,
                    srcdir.toString() + dirName });

            // Very important to check errors returned by the process as
            // the java program will not print out the error that is output by
            // the child process unless you do this

            InputStream stdin = null;
            int exitVal = proc.waitFor();
            if (exitVal == 0)
                stdin = proc.getInputStream();
            else
                stdin = proc.getErrorStream();

            InputStreamReader isr = new InputStreamReader(stdin);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null) {
                logger.info("line = " + line);
                int index = line.indexOf("total");
                if (index != -1) {
                    logger.info("index = " + index);
                    String usedSize = line.substring(0, index);
                    logger.info("usedSize = " + usedSize);
                    if (usedSize == null) {
                        logger.info("usedSize is null");
                        return null;
                    } else {
                        usedSize = usedSize.trim();
                        logger.info("usedSize " + usedSize);
                        return usedSize;
                        //return "24000M";
                    }
                }
            }
        } catch (Exception e) {
            throw new SanException("error " + e.getMessage());
        }
        return null;
    }

    /**
    * fileContentType() - read the content type of the file
    * @param fileName - fileName including the entire path
    * @returns String - content type as a string
    * @throws - error when the File object is null
    */
    public String getFileContentType(String fileName) throws SanException {

        logger.info(" getFileContentType() fileName = " + fileName);

        try {
            Runtime runtime = Runtime.getRuntime();

            // It is important to break up the command into a String[] array
            // I couldn't get it working without resorting to arg array
            //  Process proc = runtime.exec(new String[] {"/bin/mv", srcdir.toString() + fileName, newdir.toString()});
            //Process proc = runtime.exec(new String[] {"/usr/bin/file", "/tmp/redbasin_facilities.doc"});
            Process proc = runtime.exec(new String[] { SanConstants.sanFileCmd, fileName });

            // Very important to check errors returned by the process as
            // the java program will not print out the error that is output by
            // the child process unless you do this

            InputStream stdin = null;
            int exitVal = proc.waitFor();
            if (exitVal == 0)
                stdin = proc.getInputStream();
            else
                stdin = proc.getErrorStream();

            InputStreamReader isr = new InputStreamReader(stdin);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null) {
                logger.info("line = " + line);
                int index = line.lastIndexOf(":");
                if (index != -1 && index < line.length()) {
                    String contentType = line.substring(index + 1, line.length());
                    logger.info("contentType = " + contentType);
                }
            }
        } catch (Exception e) {
            throw new SanException("error " + e.getMessage());
        }
        return null;
    }
}