JSF upload& play audio

JSF Upload Audio

 

JSP:

 

<%@ taglib prefix="h" uri="http://java.sun.com/jsf/html" %>
<%@ taglib prefix="f" uri="http://java.sun.com/jsf/core" %>

<%@ taglib prefix="rich" uri="http://richfaces.ajax4jsf.org/rich" %>
<%@ taglib prefix="a4j" uri="http://richfaces.org/a4j" %>
<h:panelGroup id="audios">
    <script type="text/javascript" src="<h:outputText value="#{request.contextPath}/js/flowplayer.3.1.2.min.js"/>"></script>
    <script type="text/javascript">
        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";
            }
        }
     </script>
   
     <style type="text/css">
        .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;
        }
    </style>
     <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}">
       
         <rich:column style="text-align:center;width:50%;">
              <f:facet name="header">
                  <h:outputText value="Description"/>
              </f:facet>
              <h:outputText value="#{audio.descriptionDesc}"/>
         </rich:column>
         <rich:column style="text-align:center;width:10%;">
              <f:facet name="header">
                  <h:outputText value="Duration"/>
              </f:facet>
              <h:outputText value="#{audio.durationNum}"/>
         </rich:column>
         <rich:column>
              <f:facet name="header">
                  <h:outputText value="audition"/>
              </f:facet>
              <h:panelGroup>
                   <a href="javascript:controlAudio(<h:outputText value='#{rowNo + 1}'/>);" id="play<h:outputText value='#{rowNo + 1}'/>" class="play">
                    <img src="<h:outputText value='#{request.contextPath}'/>/img/clear.gif" width="46" height="20" alt="" title=""/>
                 </a>
                 <div id="audio<h:outputText value='#{rowNo + 1}'/>" style="margin: 0pt; padding: 0pt; width: 10px; height: 5px;"></div>                
                   <script type="text/javascript">
                    $f("audio<h:outputText value='#{rowNo + 1}'/>", "<h:outputText value='#{request.contextPath}/swf/flowplayer-3.1.2.swf'/>", {
                          plugins: {
                              controls: {
                                  all: false,
                                  backgroundColor: '#ffffff',
                                  fontColor: '#ffffff',
                                  timeFontColor: '#ffffff'
                              }
                          },
                          clip: {
                              url: "<h:outputText value='#{request.contextPath}/audio?filename=/#{audio.name.fullPath}'/>",
                              autoPlay: false,
                              autoBuffering: false
                          }
                      });
                </script>

              </h:panelGroup>
            
         </rich:column>
         <rich:column>
              <f:facet name="header">
                  <h:outputText value="Operation"/>
              </f:facet>
              <h:panelGroup>
                   <a4j:commandLink id="edit" value="Edit" immediate="true"
                      reRender="artist:audios"
                      action="#{artistManageBean.doEditAudio}"/>&nbsp;|&nbsp;
                    <a4j:commandLink id="del" value="Delete" immediate="true"
                     reRender="artist:audios"
                     action="#{artistManageBean.doRemoveAudio}"/>
                   
              </h:panelGroup>
            
         </rich:column>

        </rich:dataTable>
   
       
       <a4j:outputPanel id="uploadAudio">
          <a4j:commandButton reRender="uploadAudio" rendered="#{artistManageBean.profileAudio == null}"
                value="Upload Audio" action="#{artistManageBean.doCreateAudio}"/>
        <h:panelGrid  columns="2" rendered="#{artistManageBean.profileAudio != null}">
             <h:outputText value="#{artistManageBean.profileAudio.name != null ? 'Replace Current Audio' : 'Upload Audio'}"/>
             <h:panelGroup id="audio">
                    <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}">
                    </rich:fileUpload>
                   <rich:message for="videoUpload" errorClass="error_single"/>
                   <h:outputText value="Audio types allowed: MP3, WAV, WMA" />
               </h:panelGroup>
            
            <h:outputLabel value="Description: " />
            <h:inputText value="#{artistManageBean.profileAudio.descriptionDesc}" />
            <h:outputLabel value="Duration: " />
            <h:selectOneListbox id="audioDuration" style="width:50px;" size="1"
                            value="#{artistManageBean.profileAudio.durationNum}">
                        <f:selectItem itemValue="1" itemLabel="1"/>
                        <f:selectItem itemValue="2" itemLabel="2"/>
                        <f:selectItem itemValue="3" itemLabel="3"/>
                        <f:selectItem itemValue="4" itemLabel="4"/>
                        <f:selectItem itemValue="5" itemLabel="5"/>
            </h:selectOneListbox>
               <h:outputLabel value=" " />
                  <h:panelGroup>
                     <a4j:commandButton value="Upload" reRender="artist:audios" action="#{artistManageBean.doSaveAudio}"/>
                     &nbsp;&nbsp;
                     <a4j:commandButton value="Cancel" reRender="artist:audios" action="#{artistManageBean.doCancelAudio}"/>
                </h:panelGroup>
        </h:panelGrid>
       </a4j:outputPanel>

</h:panelGroup>

Background Bean:

 

    private boolean isEditAudio = false;
    private MediaVO<ProfileAudio> 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<ProfileAudio> getProfileAudios() {
        try {
            if (profileAudioVO == null) {
                profileAudioVO = new MediaVO<ProfileAudio>();
                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<_ProfileMedia extends EntityDomainType> implements Serializable {

    private List<_ProfileMedia> current = null;
    private List<_ProfileMedia> created = null;
    private List<_ProfileMedia> changed = null;
    private List<_ProfileMedia> removed = null;

    public List<_ProfileMedia> getCurrent() {
        if (current == null) {
            current = newListInstance();
        }
        return current;
    }

    public List<_ProfileMedia> getCreated() {
        if (created == null) {
            created = newListInstance();
        }
        return created;
    }

    public List<_ProfileMedia> getChanged() {
        if (changed == null) {
            changed = newListInstance();
        }
        return changed;
    }

    public List<_ProfileMedia> getRemoved() {
        if (removed == null) {
            removed = newListInstance();
        }
        return removed;
    }

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

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

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

    public boolean hasRemoved() {
        return (removed != null && removed.size() > 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<_ProfileMedia> newListInstance() {
        return new ArrayList<_ProfileMedia>();
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值