org.opentestsystem.delivery.testreg.service.impl.FileUploadServiceImpl.java Source code

Java tutorial

Introduction

Here is the source code for org.opentestsystem.delivery.testreg.service.impl.FileUploadServiceImpl.java

Source

/*******************************************************************************
 * Educational Online Test Delivery System
 * Copyright (c) 2013 American Institutes for Research
 * 
 * Distributed under the AIR Open Source License, Version 1.0
 * See accompanying file AIR-License-1_0.txt or at
 * http://www.smarterapp.org/documents/American_Institutes_for_Research_Open_Source_Software_License.pdf
 ******************************************************************************/
package org.opentestsystem.delivery.testreg.service.impl;

import java.io.IOException;
import java.io.InputStream;

import org.opentestsystem.delivery.testreg.domain.FileUploadResponse;
import org.opentestsystem.delivery.testreg.persistence.FileUploadGridFsRepository;
import org.opentestsystem.delivery.testreg.service.FileUploadService;
import org.opentestsystem.shared.exception.LocalizedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSFile;

public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private FileUploadGridFsRepository fileUploadGridFsRepository;

    @Override
    public FileUploadResponse saveFile(final String fileName, final InputStream inputStream,
            final String formatType) {

        final DBObject metadata = new BasicDBObject("formatType", formatType);
        final FileUploadResponse response = new FileUploadResponse();
        try {
            final GridFSFile gridFile = this.fileUploadGridFsRepository.save(inputStream, fileName, metadata);
            inputStream.close();
            response.setFileName(fileName);
            response.setFileGridFsId(gridFile.getId().toString());
            response.setStatusCode(HttpStatus.CREATED.value());
            response.setMessage("File uploaded successfully");
        } catch (final IOException ioe) {
            response.setStatusCode(HttpStatus.UNPROCESSABLE_ENTITY.value());
            response.setMessage("File Failed to upload ");
            throw new LocalizedException("fileupload.save.error", ioe);
        }

        return response;
    }

    @Override
    public GridFSDBFile getFileById(final String fileId) {
        return this.fileUploadGridFsRepository.getById(fileId);
    }
}