001/**
002 * Copyright 2014 Tampere University of Technology, Pori Department
003 * 
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 * 
008 *   http://www.apache.org/licenses/LICENSE-2.0
009 * 
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package service.tut.pori.fileservice;
017
018import java.io.InputStream;
019
020import org.apache.log4j.Logger;
021
022import core.tut.pori.context.ServiceInitializer;
023import core.tut.pori.http.parameters.Limits;
024import core.tut.pori.users.UserIdentity;
025
026/**
027 * File Service core methods.
028 */
029public final class FileCore {
030  private static final FileHandler FILE_HANDLER = new FileHandler();
031  private static final Logger LOGGER = Logger.getLogger(FileCore.class);
032  
033  /**
034   * 
035   */
036  private FileCore(){
037    // nothing needed
038  }
039
040  /**
041   * 
042   * @param authenticatedUser
043   * @param file
044   * @param filename optional original filename. The real filename used to store the file on the system will be generated, thus giving filename as a parameter is optional.
045   * @return details of the added file or null on failure
046   */
047  public static File addFile(UserIdentity authenticatedUser, InputStream file, String filename) {
048    FileProperties fp = ServiceInitializer.getPropertyHandler().getSystemProperties(FileProperties.class);
049    
050    String savedName = FILE_HANDLER.generateFilename(filename);
051    FileDAO fileDAO = ServiceInitializer.getDAOHandler().getSQLDAO(FileDAO.class);
052    File savedFile = new File();
053    savedFile.setSavedName(savedName);
054    savedFile.setName(filename);
055    savedFile.setUserId(authenticatedUser);
056    fileDAO.save(savedFile); // save first to reserve the generated savedName in the database table, in theory this may also throw data violation exception if the name is already in use, though in practice that'll never happen
057    
058    if(!FILE_HANDLER.save(fp.getFilePath()+savedName, file)){ // save the file to file system
059      LOGGER.warn("Failed to save file: "+savedName);
060      fileDAO.delete(authenticatedUser, new long[]{savedFile.getFileId()});
061      return null;
062    }
063    savedFile.setUrl(createUrl(fp.getUriPath(),savedName));
064    
065    return savedFile;
066  }
067
068  /**
069   * Delete the files given as a list of file ids, if array is empty or null, all user's files will be deleted
070   * 
071   * @param authenticatedUser
072   * @param fileIds
073   */
074  public static void deleteFiles(UserIdentity authenticatedUser, long[] fileIds) {
075    /* process the deletion immediately, this could also be made into a quartz job if it starts to slow down or cause issues */
076    FileList files = ServiceInitializer.getDAOHandler().getSQLDAO(FileDAO.class).delete(authenticatedUser, fileIds); // delete files, this will also check permissions
077    if(FileList.isEmpty(files)){
078      LOGGER.debug("No files deleted.");
079    }else{
080      StringBuilder directoryPath = new StringBuilder(ServiceInitializer.getPropertyHandler().getSystemProperties(FileProperties.class).getFilePath());
081      int length = directoryPath.length();
082      for(File file : files.getFiles()){
083        directoryPath.setLength(length);
084        directoryPath.append(file.getSavedName());
085        if(!FILE_HANDLER.delete(directoryPath.toString())){
086          LOGGER.warn("Failed to delete file: "+file.getSavedName());
087        }
088      } // for
089    }
090  }
091
092  /**
093   * 
094   * @param authenticatedUser
095   * @param fileIds optional list of file ids, if missing all user's files will be returned
096   * @param limits
097   * @return list of files or null if none found
098   */
099  public static FileList listFiles(UserIdentity authenticatedUser, long[] fileIds, Limits limits) {
100    FileList files = ServiceInitializer.getDAOHandler().getSQLDAO(FileDAO.class).getFiles(authenticatedUser, fileIds, limits);
101    if(FileList.isEmpty(files)){
102      return null;
103    }else{
104      LOGGER.debug("Resolving URLs for file list...");
105      String uri = ServiceInitializer.getPropertyHandler().getSystemProperties(FileProperties.class).getUriPath();
106      for(File file : files.getFiles()){
107        file.setUrl(createUrl(uri,file.getSavedName()));
108      }
109      return files;
110    } // else
111  }
112  
113  /**
114   * 
115   * @param filePath
116   * @param savedName
117   * @return URL for the file created from the given values
118   */
119  private static final String createUrl(String filePath, String savedName){
120    return filePath+savedName;
121  }
122}