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.File;
019import java.io.FileOutputStream;
020import java.io.IOException;
021import java.io.InputStream;
022import java.util.UUID;
023
024import org.apache.commons.io.FileUtils;
025import org.apache.commons.io.IOUtils;
026import org.apache.commons.lang3.ArrayUtils;
027import org.apache.commons.lang3.StringUtils;
028import org.apache.log4j.Logger;
029
030/**
031 * A simple helper class for saving and deleting a file, as well generating a random filename.
032 */
033public class FileHandler {
034  private static final char SEPARATOR_FILE_EXTENSION = '.';
035  private static final Logger LOGGER = Logger.getLogger(FileHandler.class);
036  
037  /**
038   * Saves the content of the input stream to the given path using the given filename
039   * 
040   * @param filePath absolute file path of the file to be created
041   * @param file the inputstream containing the file, the stream will NOT be closed
042   * @return true on success
043   */
044  public boolean save(String filePath, InputStream file){
045    try (FileOutputStream out = new FileOutputStream(filePath)) {
046      LOGGER.debug("Saved new file "+filePath+", size: "+IOUtils.copy(file, out));
047      return true;
048    } catch (IOException ex) {
049      LOGGER.error(ex, ex);
050    }
051    return false;
052  }
053  
054  /**
055   * 
056   * @param filePath the absolute file path of the file to be deleted
057   * @return true on success
058   */
059  public boolean delete(String filePath){
060    LOGGER.debug("Deleting file: "+filePath);
061    return FileUtils.deleteQuietly(new File(filePath));
062  }
063  
064  /**
065   * helper method for generating a new file name based on the given original filename.
066   * 
067   * The file names should be highly unique, but they are random, and it is up to the caller to take appropriate measures for validating the uniqueness of the file names.
068   * 
069   * @param filename
070   * @return randomly generated URI-safe (no URL encoding needed) file name
071   */
072  public String generateFilename(String filename){
073    String name = UUID.randomUUID().toString();
074    
075    String[] parts = StringUtils.split(filename, FileHandler.SEPARATOR_FILE_EXTENSION);
076    if(ArrayUtils.getLength(parts) < 2){
077      LOGGER.debug("No filename or missing file extension.");
078    }else{
079      String extension = parts[parts.length-1];
080      StringBuilder sb = new StringBuilder(name.length()+extension.length()+2); // initialize with fixed size because the size is known
081      sb.append(name);
082      sb.append(FileHandler.SEPARATOR_FILE_EXTENSION);
083      sb.append(extension);
084      name = sb.toString();
085    }
086    return name;
087  }
088}