001/** 002 * Copyright 2011 The Kuali Foundation Licensed under the 003 * Educational Community License, Version 2.0 (the "License"); you may 004 * not use this file except in compliance with the License. You may 005 * obtain a copy of the License at 006 * 007 * http://www.osedu.org/licenses/ECL-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, 010 * software distributed under the License is distributed on an "AS IS" 011 * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 012 * or implied. See the License for the specific language governing 013 * permissions and limitations under the License. 014 */ 015 016package org.kuali.mobility.file.dao; 017 018import org.kuali.mobility.file.entity.File; 019import org.springframework.stereotype.Repository; 020 021import javax.persistence.EntityManager; 022import javax.persistence.OptimisticLockException; 023import javax.persistence.PersistenceContext; 024import javax.persistence.Query; 025import java.util.List; 026 027@Repository 028public class FileDaoImpl implements FileDao { 029 030 private static org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(FileDaoImpl.class); 031 private String ME = this.getClass().getName(); 032 033 @PersistenceContext 034 private EntityManager entityManager; 035 036 public FileDaoImpl(){} 037 038 public Long saveFile(File file){ 039 if(file == null){ 040 return null; 041 } 042 try { 043 if(file.getId() == null){ 044 entityManager.persist(file); 045 }else{ 046 entityManager.merge(file); 047 } 048 } catch (OptimisticLockException e) { 049 return null; 050 } 051 return file.getId(); 052 } 053 054 public boolean removeFile(File file){ 055 boolean result = true; 056 if(file == null){ 057 return false; 058 } 059 if(file.getId() != null){ 060 try{ 061 File f = entityManager.find(File.class, file.getId()); 062 entityManager.remove(f); 063 }catch(Exception e){ 064 LOG.info("Exception Caught: " + e.getMessage()); 065 result = false; 066 } 067 } 068 return result; 069 } 070 071 @SuppressWarnings("unchecked") 072 public File findFileById(Long Id){ 073 Query query = entityManager.createQuery("select f from File f where f.id = " + Id); 074 return (File) query.getSingleResult(); 075 } 076 077 @SuppressWarnings("unchecked") 078 public List<File> findFilesByName(String name){ 079 Query query = entityManager.createQuery("select f from File f where f.fileName like '" + name + "'"); 080 return query.getResultList(); 081 } 082 083 @SuppressWarnings("unchecked") 084 public List<File> findAllFiles(){ 085 086 Query query = entityManager.createQuery("select f from File f order by f.postedTimestamp desc"); 087 return query.getResultList(); 088 } 089 090 public EntityManager getEntityManager() { 091 return entityManager; 092 } 093 094 public void setEntityManager(EntityManager entityManager) { 095 this.entityManager = entityManager; 096 } 097}