---
title: "JSF upload& play audio"
author: "dragon0929"
date: "2010-06-10T14:32:31Z"
tags: ["F#", "JSF", "JavaScript", "jQuery", "richfaces"]
categories: ["编程语言"]
slug: "jsf-upload-play-audio"
draft: false
lastmod: "2010-06-10T14:32:31Z"
id: 688827
url: "https://dragon0929.iteye.com/blog/688827"
---

JSF Upload Audio

 

**JSP:**

 

&lt;%@ taglib prefix="h" uri="http://java.sun.com/jsf/html" %&gt;  
&lt;%@ taglib prefix="f" uri="http://java.sun.com/jsf/core" %&gt;

&lt;%@ taglib prefix="rich" uri="http://richfaces.ajax4jsf.org/rich" %&gt;  
&lt;%@ taglib prefix="a4j" uri="http://richfaces.org/a4j" %&gt;  
&lt;h:panelGroup id="audios"&gt;  
    &lt;script type="text/javascript" src="&lt;h:outputText value="#{request.contextPath}/js/flowplayer.3.1.2.min.js"/&gt;"&gt;&lt;/script&gt;  
    &lt;script type="text/javascript"&gt;  
        function controlAudio(index) {  
            if (jQuery("#play" + index).hasClass("play")) {  
                play(index);  
            }  
            else {  
                stop(index);  
            }  
        }  
        function play(index) {  
            jQuery("#play" + index).removeClass("play").addClass("stop");  
            try{  
                $f("audio" + index).play();  
            }catch(err)  
               {  
               var txt="There was an error on this page.\\n\\n"  
               txt+="Error description: " + err.description + "\\n\\n"  
               txt+="Click OK to continue.\\n\\n";  
               throw err;  
            }  
        }

        function stop(index) {  
            jQuery("#play" + index).removeClass("stop").addClass("play");  
            try{  
                $f("audio" + index).stop();  
            }catch(err)  
               {  
               var txt="There was an error on this page.\\n\\n"  
               txt+="Error description: " + err.description + "\\n\\n"  
               txt+="Click OK to continue.\\n\\n";  
            }  
        }  
     &lt;/script&gt;  
     
     &lt;style type="text/css"&gt;  
        .play {  
            display: block;  
            float: left;  
            width: 46px;  
            height: 20px;  
            padding: 0;  
            text-decoration: none;  
            background: url(../img/btn/play.gif) no-repeat 0 0;  
        }

        .stop {  
            display: block;  
            float: left;  
            width: 46px;  
            height: 20px;  
            padding: 0;  
            text-decoration: none;  
            background: url(../img/btn/stop.gif) no-repeat 0 0;  
        }  
    &lt;/style&gt;  
     &lt;rich:dataTable id="audioTable" value="#{artistManageBean.profileAudios}" var="audio" rowKeyVar="rowNo" rowClasses="odd, even"  
                     style="width:60%;text-align:left;" rendered="#{not empty artistManageBean.profileAudios}"&gt;  
         
         &lt;rich:column style="text-align:center;width:50%;"&gt;  
              &lt;f:facet name="header"&gt;  
                  &lt;h:outputText value="Description"/&gt;  
              &lt;/f:facet&gt;  
              &lt;h:outputText value="#{audio.descriptionDesc}"/&gt;  
         &lt;/rich:column&gt;  
         &lt;rich:column style="text-align:center;width:10%;"&gt;  
              &lt;f:facet name="header"&gt;  
                  &lt;h:outputText value="Duration"/&gt;  
              &lt;/f:facet&gt;  
              &lt;h:outputText value="#{audio.durationNum}"/&gt;  
         &lt;/rich:column&gt;  
         &lt;rich:column&gt;  
              &lt;f:facet name="header"&gt;  
                  &lt;h:outputText value="audition"/&gt;  
              &lt;/f:facet&gt;  
              &lt;h:panelGroup&gt;  
                   &lt;a href="javascript:controlAudio(&lt;h:outputText value='#{rowNo + 1}'/&gt;);" id="play&lt;h:outputText value='#{rowNo + 1}'/&gt;" class="play"&gt;  
                    &lt;img src="&lt;h:outputText value='#{request.contextPath}'/&gt;/img/clear.gif" width="46" height="20" alt="" title=""/&gt;  
                 &lt;/a&gt;  
                 &lt;div id="audio&lt;h:outputText value='#{rowNo + 1}'/&gt;" style="margin: 0pt; padding: 0pt; width: 10px; height: 5px;"&gt;&lt;/div&gt;                  
                   &lt;script type="text/javascript"&gt;  
                    $f("audio&lt;h:outputText value='#{rowNo + 1}'/&gt;", "&lt;h:outputText value='#{request.contextPath}/swf/flowplayer-3.1.2.swf'/&gt;", {  
                          plugins: {  
                              controls: {  
                                  all: false,  
                                  backgroundColor: '#ffffff',  
                                  fontColor: '#ffffff',  
                                  timeFontColor: '#ffffff'  
                              }  
                          },  
                          clip: {  
                              url: "&lt;h:outputText value='#{request.contextPath}/audio?filename=/#{audio.name.fullPath}'/&gt;",  
                              autoPlay: false,  
                              autoBuffering: false  
                          }  
                      });  
                &lt;/script&gt;  
              &lt;/h:panelGroup&gt;  
              
         &lt;/rich:column&gt;  
         &lt;rich:column&gt;  
              &lt;f:facet name="header"&gt;  
                  &lt;h:outputText value="Operation"/&gt;  
              &lt;/f:facet&gt;  
              &lt;h:panelGroup&gt;  
                   &lt;a4j:commandLink id="edit" value="Edit" immediate="true"  
                      reRender="artist:audios"  
                      action="#{artistManageBean.doEditAudio}"/&gt;&nbsp;|&nbsp;  
                    &lt;a4j:commandLink id="del" value="Delete" immediate="true"  
                     reRender="artist:audios"  
                     action="#{artistManageBean.doRemoveAudio}"/&gt;  
                     
              &lt;/h:panelGroup&gt;  
              
         &lt;/rich:column&gt;

        &lt;/rich:dataTable&gt;  
     
         
       &lt;a4j:outputPanel id="uploadAudio"&gt;  
          &lt;a4j:commandButton reRender="uploadAudio" rendered="#{artistManageBean.profileAudio == null}"  
                value="Upload Audio" action="#{artistManageBean.doCreateAudio}"/&gt;  
        &lt;h:panelGrid  columns="2" rendered="#{artistManageBean.profileAudio != null}"&gt;  
             &lt;h:outputText value="#{artistManageBean.profileAudio.name != null ? 'Replace Current Audio' : 'Upload Audio'}"/&gt;  
             &lt;h:panelGroup id="audio"&gt;  
                    &lt;rich:fileUpload id="audioUpload" acceptedTypes="mp3, wav, wma" required="true"  
                             immediate="true" listWidth="280" listHeight="60" autoclear="false"  
                             maxFilesQuantity="1" addControlLabel="Upload" immediateUpload="true"  
                             requiredMessage="Audio is required."  
                             fileUploadListener="#{artistManageBean.audioUploadListener}"&gt;  
                    &lt;/rich:fileUpload&gt;  
                   &lt;rich:message for="videoUpload" errorClass="error\_single"/&gt;  
                   &lt;h:outputText value="Audio types allowed: MP3, WAV, WMA" /&gt;  
               &lt;/h:panelGroup&gt;  
              
            &lt;h:outputLabel value="Description: " /&gt;  
            &lt;h:inputText value="#{artistManageBean.profileAudio.descriptionDesc}" /&gt;  
            &lt;h:outputLabel value="Duration: " /&gt;  
            &lt;h:selectOneListbox id="audioDuration" style="width:50px;" size="1"  
                            value="#{artistManageBean.profileAudio.durationNum}"&gt;  
                        &lt;f:selectItem itemValue="1" itemLabel="1"/&gt;  
                        &lt;f:selectItem itemValue="2" itemLabel="2"/&gt;  
                        &lt;f:selectItem itemValue="3" itemLabel="3"/&gt;  
                        &lt;f:selectItem itemValue="4" itemLabel="4"/&gt;  
                        &lt;f:selectItem itemValue="5" itemLabel="5"/&gt;  
            &lt;/h:selectOneListbox&gt;  
               &lt;h:outputLabel value=" " /&gt;  
                  &lt;h:panelGroup&gt;  
                     &lt;a4j:commandButton value="Upload" reRender="artist:audios" action="#{artistManageBean.doSaveAudio}"/&gt;  
                     &nbsp;&nbsp;  
                     &lt;a4j:commandButton value="Cancel" reRender="artist:audios" action="#{artistManageBean.doCancelAudio}"/&gt;  
                &lt;/h:panelGroup&gt;  
        &lt;/h:panelGrid&gt;  
       &lt;/a4j:outputPanel&gt;

&lt;/h:panelGroup&gt;

**Background Bean:**

 

    private boolean isEditAudio = false;  
    private MediaVO&lt;ProfileAudio&gt; profileAudioVO;  
    private ProfileAudio profileAudio;

 

public void audioUploadListener(UploadEvent event) {  
        InputStream fileInputStream = null;  
        try {  
            UploadItem upload = event.getUploadItem();  
            if (upload.isTempFile()) {  
                removeOldAudio();  
                fileInputStream = new FileInputStream(upload.getFile());  
                AudioHelperWrapper wrapper = new AudioHelperWrapper();  
                wrapper.initialize();  
                wrapper.download(upload.getFileName(), fileInputStream);  
                profileAudio.setName(wrapper.getMediaName());

                MessageUtil.addGlobalInfoMessage("Audio is uploaded successfully.");  
            }  
        } catch (Exception e) {  
            MessageUtil.addGlobalErrorMessage("Cannot upload audio.");  
            log.error("Error to close uploaded audio input stream.", e);  
        } finally {  
            if (fileInputStream != null) {  
                try {  
                    fileInputStream.close();  
                } catch (Exception e) {

                }  
            }  
        }  
    }  
     
    private void removeOldAudio() {  
        if (profileAudio.getName() != null) {  
            AudioHelper.removeFile(profileAudio.getName().getFullPath());  
            profileAudio.setName(null);  
        }  
    }  
       
    public List&lt;ProfileAudio&gt; getProfileAudios() {  
        try {  
            if (profileAudioVO == null) {  
                profileAudioVO = new MediaVO&lt;ProfileAudio&gt;();  
                if (getMemberProfile().getId() != null) {  
                    try {  
                        profileAudioVO.getCurrent().addAll(profileAudioManager.getByMemberProfileID(getMemberProfile().getId()));  
                         if (!profileAudioVO.hasCurrent()) {  
                             profileAudio = new ProfileAudio();  
                         }  
                    } catch (FinderException e) {  
                        e.printStackTrace();  
                    }  
                }  
            }

        } catch (Exception e) {  
            e.printStackTrace();  
            MessageUtil.addGlobalErrorMessage("Error to pload profile audios.");  
        }  
        return profileAudioVO.getCurrent();  
    }  
       
    public String doCreateAudio() {  
        profileAudio = new ProfileAudio();  
        isEditAudio= false;  
        return ActionForward.NONE;  
    }  
         
    public String doEditAudio() {  
        isEditAudio = true;  
        ProfileAudio audio = (ProfileAudio) requestMap().get("audio");  
         
        if (audio!= null) {  
            profileAudio = audio;  
        } else {  
            profileAudio = new ProfileAudio();  
        }  
         return ActionForward.NONE;  
     }  
       
     public String doRemoveAudio() {  
        ProfileAudio audio = (ProfileAudio) requestMap().get("audio");  
        if (audio != null) {  
            profileAudioVO.addRemoved(audio);  
            MessageUtil.addGlobalInfoMessage("Audio will be removed with saving artist profile.");  
        } else {  
            MessageUtil.addGlobalErrorMessage("Can't remove audio: it's not found.");  
        }  
        return ActionForward.NONE;  
    }  
       
    public String doSaveAudio() {  
        if (profileAudio != null) {  
            final MediaName audioName = profileAudio.getName();  
            if (audioName == null) {  
                MessageUtil.addGlobalErrorMessage("Please, upload audio file.");  
            } else {  
                ProfileAudio temp = new ProfileAudio();  
                temp.setName(audioName);  
                temp.setDescriptionDesc(profileAudio.getDescriptionDesc());  
                temp.setDurationNum(profileAudio.getDurationNum());  
                temp.setMemberProfileID(memberProfile.getId());  
                if (profileAudio.getId() != null) {  
                    temp.setId(profileAudio.getId());  
                    profileAudioVO.addChanged(temp);  
                } else if (!isEditAudio){  
                    profileAudioVO.addCreated(temp);  
                }  
                profileAudio = null;  
            }  
        }  
        isEditAudio = false;  
        return ActionForward.NONE;  
    }  
     
    public String doCancelAudio() {  
         
        if (!isEditVideo && profileAudio.getName() != null) {  
            VideoHelper.removeFile(profileAudio.getName().getFullPath());  
        }  
        profileAudio = null;  
        isEditAudio = false;  
         
        return ActionForward.NONE;  
    }

    public ProfileAudio getProfileAudio() {  
        return profileAudio;  
    }

    public void setProfileAudio(ProfileAudio profileAudio) {  
        this.profileAudio = profileAudio;  
    }

 

**Batch Update code:**

 

if (profileAudioVO.hasCreated()) profileAudioManager.createBulk(profileAudioVO.getCreated());  
            if (profileAudioVO.hasChanged()) profileAudioManager.changeBulk(profileAudioVO.getChanged());  
            if (profileAudioVO.hasRemoved()) profileAudioManager.removeBulk(profileAudioVO.getRemoved());

**MediaVO.java**

 

public class MediaVO&lt;\_ProfileMedia extends EntityDomainType&gt; implements Serializable {

    private List&lt;\_ProfileMedia&gt; current = null;  
    private List&lt;\_ProfileMedia&gt; created = null;  
    private List&lt;\_ProfileMedia&gt; changed = null;  
    private List&lt;\_ProfileMedia&gt; removed = null;

    public List&lt;\_ProfileMedia&gt; getCurrent() {  
        if (current == null) {  
            current = newListInstance();  
        }  
        return current;  
    }

    public List&lt;\_ProfileMedia&gt; getCreated() {  
        if (created == null) {  
            created = newListInstance();  
        }  
        return created;  
    }

    public List&lt;\_ProfileMedia&gt; getChanged() {  
        if (changed == null) {  
            changed = newListInstance();  
        }  
        return changed;  
    }

    public List&lt;\_ProfileMedia&gt; getRemoved() {  
        if (removed == null) {  
            removed = newListInstance();  
        }  
        return removed;  
    }

    public boolean hasCurrent() {  
        return (current != null && current.size() &gt; 0);  
    }

    public boolean hasCreated() {  
        return (created != null && created.size() &gt; 0);  
    }

    public boolean hasChanged() {  
        return (changed != null && changed.size() &gt; 0);  
    }

    public boolean hasRemoved() {  
        return (removed != null && removed.size() &gt; 0);  
    }

    public void addCreated(\_ProfileMedia item) {  
        getCreated().add(item);  
        getCurrent().add(item);  
    }

    public void addChanged(\_ProfileMedia item) {  
        if (!hasChanged() || !getChanged().contains(item)) {  
            getChanged().add(item);  
        }  
    }

    public void addRemoved(\_ProfileMedia item) {  
        if (hasCreated() && getCreated().contains(item)) {  
            getCreated().remove(item);  
        } else {  
            getRemoved().add(item);  
        }  
        if (hasChanged()) {  
            getChanged().remove(item);  
        }  
        getCurrent().remove(item);  
         
    }

    public void reset() {  
        current = null;  
        created = null;  
        changed = null;  
        removed = null;  
    }

    private List&lt;\_ProfileMedia&gt; newListInstance() {  
        return new ArrayList&lt;\_ProfileMedia&gt;();  
    }  
}