2012-01-02 65 views
1

我希望有人能幫助我。我正在嘗試創建一個上傳程序,可以上傳一個或多個mp3文件並將其屬性添加到數據庫(歌曲標題,專輯等)。我不確定我遇到的問題是由於數據庫問題還是因爲我不太瞭解CommonsMultipartFile的工作原理。總之,這裏是我的代碼」grails錯誤PatchedDefaultFlushEventListener

查看:

<g:form name="fileupload" url="[action:'uploads',controller:'fileResource']" method="POST" enctype="multipart/form-data">   
    <span>Add files...</span> 
    <input type="file" name="files" multiple>   
</g:form> 

fileResource:

def uploads = {     
    Collection result = [] 
    if (request instanceof MultipartHttpServletRequest) { 
     MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request; 
     CommonsMultipartFile file = (CommonsMultipartFile)multiRequest.getFile("files");    
      println"one" 
      moveFile(file) 
      println"three"    
     result << [name: file.originalFilename, size:file.size] 
    }   
    render result as JSON 
} 

private moveFile(CommonsMultipartFile file){ 
    println"two" 
    try{    
     def userId = getUserId() 
     def newFileName = java.util.UUID.randomUUID().toString()      
     def userGuid = SecUser.get(userId.id).uid 
     def webRootDir = servletContext.getRealPath("/")    
     File myFile = new File(webRootDir + "/myUsers/${userGuid}/music",newFileName + ".") 
     file.transferTo(myFile) 
     MP3File mp3file = new MP3File(myFile); 
     String duration = mp3file.getAudioHeader().getTrackLength() 
     String bitRate = mp3file.getAudioHeader().getBitRate() 
     String encodingType = mp3file.getAudioHeader().getEncodingType() 
     String getFormat = mp3file.getAudioHeader().getFormat() 
     String trackLength = mp3file.getAudioHeader().getTrackLength() 
     String fileName = file.originalFilename 
     String  artistName = "" 
     String  albumName = "" 
     String  songName = "" 

     def getArtistId="" 
     try{ 
      if (mp3file.hasID3v2Tag()){ 
       //println("has id3v2 tag") 
       ID3v24Tag id3v24tag = mp3file.getID3v2TagAsv24(); 
       artistName = (id3v24tag.getFirst(ID3v24Frames.FRAME_ID_ARTIST).trim()) 
       albumName = (id3v24tag.getFirst(ID3v24Frames.FRAME_ID_ALBUM).trim()) 
       songName = (id3v24tag.getFirst(ID3v24Frames.FRAME_ID_TITLE).trim()) 
      }else if (mp3file.hasID3v1Tag()) { 
       //println("has id3v1 tag") 
       ID3v1Tag tag = mp3file.getID3v1Tag(); 
       artistName = tag.getFirst(FieldKey.ARTIST).trim() 
       albumName = tag.getFirst(FieldKey.ALBUM).trim() 
       songName = tag.getFirst(FieldKey.TITLE).trim() 
      } 
      else{ 
       println("this format not yet supported:" + getFormat) 
      } 
     }catch (Exception ex) { 
      log.error("ERROR: FILE NOT PROCESSED") 
     } 

     try{ 
      def oArtist = "" 
      def c = Artist.createCriteria() 
      def getMyArtist = c.get { 
       eq('artistName', artistName) 
       secUser { 
        eq('id', userId.id) 
       } 
      } 
      if (getMyArtist == null){ 
       //artist does not exist 
       // 1c. add artist 
       // 1d. add album 
       // 1e. add song 
       // 1f. move song 
       // 1g. DONE 
       oArtist= new com.jason.score.Artist(
        artistName : artistName , 
        secUser : userId.id 
       ) 
       userId.addToArtist(oArtist).save(flush:true) 
       def oAlbum  = new Album 
       (
        albumName:  albumName 
       ) 
       oArtist.addToAlbum(oAlbum).save(flush:true) 

       def oSong = new Song 
       (
        fileLocation: webRootDir + "myUsers/${userGuid}/music/", 
        songBitRate: bitRate, 
        songDuration: duration, 
        songEncodeType: encodingType, 
        songName: songName 
       ) 
       oAlbum.addToSong(oSong).save(flush:true) 
      }else{ 
       //artist exists with that username 
       //need album name and artist id 
       def d = Album.createCriteria() 
       def getMyAlbum = d.get { 
       eq('albumName', albumName) 
       artist { 
        eq('id', getMyArtist.id) 
       } 
         } 
       if(getMyAlbum == null){ 
        //    3. add album 
        //    3a. add song 
        //    3b. move song 
        //    3c. DONE         
        Artist findArtist = Artist.get(getMyArtist.id) 
        def oAlbum  = new Album 
        (
         albumName:  albumName 
        ) 
        findArtist.addToAlbum(oAlbum).save(flush:true) 
        def oSong = new Song 
        (
         fileLocation: webRootDir + "myUsers/${userGuid}/music/", 
         songBitRate: bitRate, 
         songDuration: duration, 
         songEncodeType: encodingType, 
         songName: songName 
        ) 
        oAlbum.addToSong(oSong).save(flush:true) 
        }else{ 
         //album does exist 
         //check if song exists with album id        
         def e = Song.createCriteria() 
         def getMySong = e.get { 
          eq('songName', songName) 
          album { 
           eq('id', getMyAlbum.id) 
          } 
         } 
         if (getMySong==null){ 
          Album findAlbum = Album.get(getMyAlbum.id)         
          def oSong = new Song 
          (
           fileLocation: webRootDir + "myUsers/${userGuid}/music/", 
           songBitRate: bitRate, 
           songDuration: duration, 
           songEncodeType: encodingType, 
           songName: songName 
          ) 
          findAlbum.addToSong(oSong).save(flush:true) 
         }else{ 
          //it already exists, so do nothing 
         }     


        } 
       }       
     }catch (Exception ex){ 
      log.error("ERROR: ADDING TO DB: " + ex) 
     } 
    }catch (Exception ex){ 
     log.error("error" + ex) 
    } 
} 

    private getUserId(){ 
    return SecUser.get(springSecurityService.principal.id) 
} 
private getUser(){ 
    return SecUser.get(springSecurityService.principal) 
} 

我得到的錯誤是:

2012-01-02 14:25:25,314 [http-8080-1] ERROR events.PatchedDefaultFlushEventListener - Could not synchronize database state with session 
org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [com.jason.score.SecUser#1] 
at org.hibernate.persister.entity.AbstractEntityPersister.check(AbstractEntityPersister.java:1792) 
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2435) 
at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:2335) 
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2635) 
at org.hibernate.action.EntityUpdateAction.execute(EntityUpdateAction.java:115) 
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:279) 
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:263) 
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:168) 
at org.codehaus.groovy.grails.orm.hibernate.events.PatchedDefaultFlushEventListener.performExecutions(PatchedDefaultFlushEventListener.java:46) 
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50) 
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1027) 
at org.springframework.orm.hibernate3.HibernateTemplate$28.doInHibernate(HibernateTemplate.java:883) 
at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:406) 
at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374) 
at org.springframework.orm.hibernate3.HibernateTemplate.flush(HibernateTemplate.java:881) 
at org.codehaus.groovy.grails.orm.hibernate.metaclass.SavePersistentMethod$1.doInHibernate(SavePersistentMethod.java:58) 
at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:406) 
at org.springframework.orm.hibernate3.HibernateTemplate.execute(HibernateTemplate.java:339) 
at org.codehaus.groovy.grails.orm.hibernate.metaclass.SavePersistentMethod.performSave(SavePersistentMethod.java:53) 
at org.codehaus.groovy.grails.orm.hibernate.metaclass.AbstractSavePersistentMethod.doInvokeInternal(AbstractSavePersistentMethod.java:179) 
at org.codehaus.groovy.grails.orm.hibernate.metaclass.AbstractDynamicPersistentMethod.invoke(AbstractDynamicPersistentMethod.java:59) 
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) 
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) 
at java.lang.reflect.Method.invoke(Method.java:597) 
at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoCachedMethodSite.invoke(PojoMetaMethodSite.java:188) 
.... 

2012-01-02 14: 25:25,379 [http-8080-1] ERROR errors.GrailsExceptionResolver - 處理請求時發生異常:[POST] /com.jason.score/fileResource/uploads Stacktrace如下: org.springframework.orm.hibernate3.HibernateOptimisticLockingFailureException:具有標識符[1]的類[com.jason.score.SecUser]的對象:樂觀鎖定失敗;嵌套的異常是org.hibernate.StaleObjectStateException:行由另一個事務更新或刪除(或未保存值映射不正確):[com.jason.score.SecUser#1] at java.lang.Thread.run(Thread。 java:662) 引起:org.hibernate.StaleObjectStateException:行被另一個事務更新或刪除(或未保存值映射不正確):[com.jason.score.SecUser#1] ... 1更多

+0

「getUserId()」方法/閉包的外觀如何?堆棧跟蹤的底部是什麼 - 有沒有關於錯誤源於您的自定義代碼的信息? – david 2012-01-02 20:26:47

+0

我添加了getUserId()方法。錯誤日誌很大,以適應這裏的所有。我只是在錯誤日誌的底部添加了原始文章 – jason 2012-01-02 20:31:36

+0

,當我一次只上傳一個文件時,一切正常。只有當我處理多個文件時纔會發生這種情況。 – jason 2012-01-02 20:40:05

回答

1

該錯誤歸因於Hibernate。您的標準查詢可能存在錯誤。這看起來像一個可能的候選人

oAlbum.addToSong(oSong).save(flush:true) 

那些應該是單獨的操作。標準查詢應該由服務層中的方法封裝。對於這樣簡單的操作,使用GORM動態查找器的標準可能看不出多少好處。

你也試圖在一個地方做得太多。重構您的控制器以使用服務來執行這些操作。將moveFile()分成多個解析MP3文件的方法,然後將其傳遞給另一種方法,將其添加到用戶的歌曲中。

如果直接在域中創建關係,則不需要使用用戶的ID。

爲每個原子片寫一些測試,它應該使錯誤更容易找到。

+0

感謝您的回覆。我對grails仍然陌生,所以我有一些跟進問題。首先,你在封裝服務層的方法是什麼意思?另外,我該如何折射我的控制器以使用服務?再次感謝您的幫助 – jason 2012-01-02 20:48:40

+0

如果您還不熟悉Grails,那麼我建議您查看Manning的Ledbrook&Smith的Grails in Action。如果您想要免費的教程,請查看Scott Davis的Mastering Grails系列。這個特定的人處理服務。 http://www.ibm.com/developerworks/java/library/j-grails05208/index.html另外,請查看用戶指南http://www.grails.org/doc/latest/guide/services。HTML – 2012-01-04 02:09:34