com.gantzgulch.sharing.service.impl.StorageManagerImpl.java Source code

Java tutorial

Introduction

Here is the source code for com.gantzgulch.sharing.service.impl.StorageManagerImpl.java

Source

/*
 * Copyright 2011 GantzGulch, Inc.
 * 
 * This file is part of GantzFileSharing.
 * 
 * GantzFileSharing 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.
 * 
 * GantzFileSharing 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 GantzFileSharing.  If not, see <http://www.gnu.org/licenses/>. 
 */
package com.gantzgulch.sharing.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gantzgulch.sharing.domain.SharedFile;
import com.gantzgulch.sharing.service.StorageManager;

@Service("storageManager")
public class StorageManagerImpl implements StorageManager {

    private final File storageLocation;
    private final File filesStorageLocation;

    @Autowired
    public StorageManagerImpl(String storageLocation) {
        this.storageLocation = new File(storageLocation);
        this.filesStorageLocation = new File(this.storageLocation, "files");
        this.filesStorageLocation.mkdirs();
    }

    @Override
    public void storeFile(SharedFile sharedFile, InputStream inputStream) throws IOException {

        String onDiskFilename = StringUtils.defaultIfEmpty(sharedFile.getOnDiskFilename(),
                "sf_" + System.currentTimeMillis() + ".dat");
        sharedFile.setOnDiskFilename(onDiskFilename);

        File file = new File(filesStorageLocation, onDiskFilename);
        OutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(file);
            IOUtils.copyLarge(inputStream, outputStream);
        } finally {
            IOUtils.closeQuietly(outputStream);
            IOUtils.closeQuietly(inputStream);
        }
    }

    @Override
    public InputStream loadFile(SharedFile sharedFile) throws IOException {
        File file = new File(filesStorageLocation, sharedFile.getOnDiskFilename());
        return new FileInputStream(file);
    }

    @Override
    public void delete(SharedFile sharedFile) {
        File file = new File(filesStorageLocation, sharedFile.getOnDiskFilename());
        file.delete();
    }

}