Exemple #1
0
  /**
   * 업로드된 {@code file}을 주어진 {@code name}으로 {@code container}에 첨부한다.
   *
   * <p>when: 업로드된 파일이 사용자에게 첨부될 때. 혹은 사용자를 거치지 않고 바로 다른 리소스로 첨부될 때.
   *
   * <p>업로드된 파일을 업로드 디렉토리로 옮긴다. 이 때 파일이름을 그 파일의 해시값으로 변경한다. 그 후 이 파일에 대한 메타정보 및 첨부될 대상에 대한 정보를 이
   * 엔터티에 담는다. 만약 이 엔터티와 같은 내용을 갖고 있는 엔터티가 이미 존재한다면, 이미 {@code container}에 같은 첨부가 존재하고 있으므로 첨부하지 않고
   * {@code false}를 반환한다. 그렇지 않다면 첨부 후 {@code true}를 반환한다.
   *
   * @param file 첨부할 파일
   * @param name 파일 이름
   * @param container 파일이 첨부될 리소스
   * @return 파일이 새로 첨부되었다면 {@code true}, 이미 같은 첨부가 존재하여 첨부되지 않았다면 {@code false}
   * @throws IOException
   * @throws NoSuchAlgorithmException
   */
  @Transient
  public boolean store(File file, String name, Resource container)
      throws IOException, NoSuchAlgorithmException {
    // Store the file as its SHA1 hash in filesystem, and record its
    // metadata - containerType, containerId, size and hash - in Database.
    this.containerType = container.getType();
    this.containerId = container.getId();
    this.createdDate = JodaDateUtil.now();

    if (name == null) {
      this.name = file.getName();
    } else {
      this.name = name;
    }

    if (this.mimeType == null) {
      this.mimeType = FileUtil.detectMediaType(file, name);
    }

    // the size must be set before it is moved.
    this.size = file.length();
    this.hash = Attachment.moveFileIntoUploadDirectory(file);

    // Add the attachment into the Database only if there is no same record.
    Attachment sameAttach = Attachment.findBy(this);
    if (sameAttach == null) {
      super.save();
      return true;
    } else {
      this.id = sameAttach.id;
      return false;
    }
  }