PrimeFaces Upload p:graphicImage BUG

Nel seguente codice si aggiorna l’immagine dopo aver effettuato l’upload di un file:

<h:form id="faqAddUpdateForm">
<p:fileUpload
fileUploadListener="#{userBean.uploadPhotoProfile}"
mode="advanced" dragDropSupport="false"
auto="true" label="#{msg['label.getMediaObj']}"
update="commentlist" />

<h:panelGroup id="commentlist">
<h:outputLabel id="test" value="#{userBean.images}" style="padding-left:100px"/>
<p:graphicImage value="/GetMedia?photoProfile=y" width="200px" />
</h:panelGroup>
</h:form>

NOTA BENE in teoria dovrebbe funzionare così ma, per un bug presenta almeno in primefaces 4.0, il panelgroup viene refreshato  ma l’immagine non viene aggiornata. Per aggirare il problema bisogna inserire un attributo di p:graphicimage che varia di valore durante l’aggiornamento, in questo caso basta aggiungere il seguente attributo:

<p:graphicImage value="/GetMedia?photoProfile=y"  title="#{userBean.images}" width="200px"    />


JSF2 – p:remoteCommand Example Chat Primefaces

p:remoteCommand chiama un metodo di un backing bean (tramite actionlistener) e, fondamentalemnte, fa da trigger ad uno javascript(oncomplete):

<p:remoteCommand name="nextMessage"
actionListener="#{messageBean.firstUnreadMessage}"
oncomplete="javascript:updateMessages(xhr, status, args);" />

Back-End

MessageBean.java

package com;

import java.io.Serializable;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ActionEvent;
import org.primefaces.context.RequestContext;


@ManagedBean
@ViewScoped
public class MessageBean implements Serializable {



private final List messages;
private Date lastUpdate;
private Message message;

/**
* Creates a new instance of MessageBean
*/
public MessageBean() {
messages = Collections.synchronizedList(new LinkedList());
lastUpdate = new Date(0);
message = new Message();
}

public Date getLastUpdate() {
return lastUpdate;
}

public void setLastUpdate(Date lastUpdate) {
this.lastUpdate = lastUpdate;
}

public Message getMessage() {
return message;
}

public void setMessage(Message message) {
this.message = message;
}


public void firstUnreadMessage(ActionEvent evt) {
RequestContext ctx = RequestContext.getCurrentInstance();

ctx.addCallbackParam("ok", message!=null);
if(message==null)
return;

lastUpdate = message.getDateSent();

ctx.addCallbackParam("user", message.getUser());
ctx.addCallbackParam("dateSent", new Date().toString());
ctx.addCallbackParam("text", message.getMessage());

}

}

Message.java
package com;
import java.io.Serializable;

public class Message implements Serializable {
private Date dateSent;
private String user;
private String message;

public Date getDateSent() {
return dateSent;
}

public void setDateSent(Date dateSent) {
this.dateSent = dateSent;
}

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

public String getUser() {
return user;
}

public void setUser(String user) {
this.user = user;
}
}

Front-End

Chat1.xhtml
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Chat test!</title>
<script type="text/javascript"
src="#{facesContext.externalContext.requestContextPath}/util.js"></script>

</h:head>

<h:body>
<h:form prependId="false">
<h:panelGrid columns="2">
Name: <p:inputText value="#{messageBean.message.user}" />
Text: <p:inputText
value="#{messageBean.message.message}" />
<p:commandButton type="reset" value="Clear" />
<p:commandButton value="Send!"
actionListener="#{messageBean.sendMessage}" onclick="nextMessage();" />
</h:panelGrid>
<p:remoteCommand name="nextMessage"
actionListener="#{messageBean.firstUnreadMessage}"
oncomplete="javascript:updateMessages(xhr, status, args);" />
</h:form>

<hr />
<h3>Live chat</h3>
<div id="chat"></div>
</h:body>
</html>


util.js

function updateMessages(xhr, status, args) {
if(!args.ok) return;
$('#chat').append('<div class="msg">[' +args.dateSent+ '] <strong>'+args.user+'</strong>: '+args.text+'</div>');
}

Esecuzione

lanciando da browser l’url
http://localhost:8080/JSFProject/faces/chat1.xhtml

si ha una simulazione di chat 


JSF2 Primefaces – p:galleria Example

p:galleria è un tag per la visualizzazione delle immagini:

<p:galleria value=”#{galleriaBean.images}” var=”image” >
    <p:graphicImage value=”/resources/images/#{image}” />
</p:galleria>

Si hanno a disposizione vari effetti:
http://primefaces-rocks.appspot.com/ui/galleria.jsf

Bean java e pagina xhtml

galleria.xhtml

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”
xmlns:f=”http://java.sun.com/jsf/core”
xmlns:h=”http://java.sun.com/jsf/html”
xmlns:ui=”http://java.sun.com/jsf/facelets”
xmlns:p=”http://primefaces.org/ui”
xmlns:c=”http://java.sun.com/jsp/jstl/core”>
<h:head/>
<h:body>
<h:form>
<h3>Images1 </h3>  
<p:galleria value=”#{galleriaBean.images}” var=”image” panelWidth=”500″ panelHeight=”313″ effectSpeed=”1000″>  
    <p:graphicImage value=”/resources/images/#{image}” />  
</p:galleria>  
  
<h3>Custom Content</h3>  
<p:galleria id=”contentGalleria” value=”#{galleriaBean.players}” var=”player” panelWidth=”250″ panelHeight=”300″  
            frameWidth=”48″ frameHeight=”65″ effect=”clip”>  
  
    <p:graphicImage id=”playerImage” value=”/resources/images/#{player.photo}” alt=”#{image}” title=”#{player.name}”/>  
    <f:facet name=”content”>  
        <h:panelGrid  columns=”2″ cellpadding=”5″>  
            <f:facet name=”header”>  
                <p:graphicImage value=”/resources/images/#{player.photo}” />  
            </f:facet>  
  
            <h:outputText value=”Name: ” />  
            <h:outputText id=”name” value=”#{player.name}”/>  
  
            <h:outputText value=”Number ” />  
            <h:outputText id=”number” value=”#{player.number}”/>  
  
            <h:outputText value=”Position ” />  
            <h:outputText id=”position” value=”#{player.position}”/>  
        </h:panelGrid>  
    </f:facet>  
  
</p:galleria>  
 </h:form>
</h:body>
</html>

GalleriaBean.java

package com;

import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.AjaxBehaviorEvent;

import java.util.ArrayList;  
import java.util.List;  
import javax.annotation.PostConstruct;  

@ManagedBean
@SessionScoped
public class GalleriaBean {  
  
    private List<String> images;  
  
    private List<Player> players;  
  
    private Player selectedPlayer;  
  
    @PostConstruct  
    public void init() {  
        images = new ArrayList<String>();  
  
        for(int i=1;i<=12;i++) {  
            images.add(“photoProfile.png”);  
        }  
  
        players = new ArrayList<Player>();  
  
        players.add(new Player(“Messi”, 10, “photoProfile.png”, “CF”));  
        players.add(new Player(“Iniesta”, 8, “photoProfile.png”, “CM”));  
        players.add(new Player(“Villa”, 7, “photoProfile.png”, “CF”));  
        players.add(new Player(“Xavi”, 6, “photoProfile.png”, “CM”));  
        players.add(new Player(“Puyol”, 5, “photoProfile.png”, “CB”));  
    }  
  
    public Player getSelectedPlayer() {  
        return selectedPlayer;  
    }  
  
    public void setSelectedPlayer(Player selectedPlayer) {  
        this.selectedPlayer = selectedPlayer;  
    }  
  
     
    public List<String> getImages() {  
        return images;  
    }  
  
    public List<Player> getPlayers() {  
        return players;  
    }  
}  
  


Esecuzione
Deployando e, da browser, chiamando l’url:

http://localhost:8080/JSFProject/faces/galleria.xhtml

si ottiene:

PrimeFaces Upload File

In PrimceFaces the tag for upload file is p:fileUpload.

This is the xhtml page

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”
xmlns:f=”http://java.sun.com/jsf/core”
xmlns:h=”http://java.sun.com/jsf/html”
xmlns:ui=”http://java.sun.com/jsf/facelets”
xmlns:p=”http://primefaces.org/ui”
xmlns:c=”http://java.sun.com/jsp/jstl/core”>
<h:head>
</h:head>
<h:body>
<h:form>
<p:fileUpload
fileUploadListener=”#{fileUploadController.handleFileUpload}”
mode=”advanced” dragDropSupport=”false” update=”messages”
sizeLimit=”100000″ fileLimit=”3″
allowTypes=”/(.|/)(gif|jpe?g|png)$/” />
<p:growl id=”messages” showDetail=”true” />
</h:form>
</h:body>
</html>

The managed bean is:

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;  
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;  
@Component
@ManagedBean
@SessionScoped
public class FileUploadController {
      public void handleFileUpload(FileUploadEvent event) {
        FacesMessage msg = new FacesMessage(“Succesful”, event.getFile().getFileName() + ” is uploaded.”);
        FacesContext.getCurrentInstance().addMessage(null, msg);
        //get uploaded file from the event
        UploadedFile uploadedFile = (UploadedFile)event.getFile();

        //create an InputStream from the uploaded file
        InputStream inputStr = null;
        try {
            inputStr = uploadedFile.getInputstream();
        } catch (IOException e) {
            //log error
        e.printStackTrace();
        }

        //create destination File
        String destPath = “D:\fbm\user\”+event.getFile().getFileName();
        File destFile = new File(destPath);

        //use org.apache.commons.io.FileUtils to copy the File
        try {                  
            FileUtils.copyInputStreamToFile(inputStr, destFile);
        } catch (IOException e) {
            //log error
        e.printStackTrace();
        }
    }
}

 In the web.xml add:

<filter>
    <filter-name>PrimeFaces FileUpload Filter</filter-name>
    <filter-class>
        org.primefaces.webapp.filter.FileUploadFilter
    </filter-class>
</filter>
<filter-mapping>
    <filter-name>PrimeFaces FileUpload Filter</filter-name>
    <servlet-name>Faces Servlet</servlet-name>
</filter-mapping>

download this jar:

commons-fileupload
commons-io

this is the output: