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 


Java StringTokenizer Example

La classe StringTokenizer è usata per dividere una stringa in varie sottostringhe, delimitate da un carattere speciale.

1° Esempio – Lettura Stringa

Divisione di una stringa con il carattere speciale blank e la virgola.

StringTokenizer.java
package com;

import java.util.StringTokenizer;

public class StringTokenizerTest {

 /**
  * @param args
  */
 public static void main(String[] args) {
  String str = "prova1 prova2 , test1 test2, prova3 test3";
  StringTokenizer st = new StringTokenizer(str);
 
  System.out.println("---- Split by space ------");
  while (st.hasMoreElements()) {
   System.out.println(st.nextElement());
  }
 
  System.out.println("---- Split by comma ',' ------");
  StringTokenizer st2 = new StringTokenizer(str, ",");
 
  while (st2.hasMoreElements()) {
   System.out.println(st2.nextElement());
  }

 }

}


output:
2 Esempio: Lettura File CVS
Le stringhe da splittare sono lette da un file cvs.
friends.cvs
prova| prova1 | prova2| prova3
test | test1  | test2 | test3
CaricaFile.java
package com;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;

public class CaricaFile {

 public static void caricaUsers() throws IOException {
  BufferedReader reader = new BufferedReader(new FileReader(
    "D:\friends.txt"));
  String line = reader.readLine();
  while (line != null) {

  StringTokenizer stRecord = new StringTokenizer(line, "|");
   while (stRecord.hasMoreTokens()) {
    String record = stRecord.nextToken();
    System.out.print(record + "  ");
   }
   System.out.println("");
   line = reader.readLine();
  }
 }

 public static void main(String[] args) throws FileNotFoundException,
   IOException {
  caricaUsers();
 }
}


Output:

HQL – Like parameter

Hql con un parametro in input da mettere nella like con le percentuali:

String querySql = "select u from Users u  ";
String whereSql = whereSql + " u.currentLocation like :currentLocation";
querySql = querySql + whereSql;

Query q = this.getEntityManager().createQuery(querySql);
q.setParameter("currentLocation", '%'+user.getCurrentLocation()+'%');

JSF2 – Bean Method Call With Parameter

Un metodo di un bean può ricevere in input parametri da una pagina jsf:
#{bean.method(param)}
Questa  sintassi funziona con Tomcat 7, perchè supporta le EL 2.2 (el-impl-2.2.jar).

passParameter.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>
<h:commandButton action="#{passParameterBean.getParameter(gigi)}" />

 </h:form>
</h:body>
</html>
PassParameter.java
package com;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean
@SessionScoped
public class PassParameterBean {
 
 private String name;

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }
 
 
 public String getParameter(String name)
 {
  this.name = name;
  
  return "./passParameterResult.xhtml";
 }

}

PassParameterResult.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>
  <h:outputText value="#{passParameterBean.name}" />

 </h:form>
</h:body>
</html>


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:

JSF2 – Load Properties File Dentro Bean

Legge un file di properties (configurationFBM) da dentro un Backing Bean:

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;

@ManagedBean
@SessionScoped
public class GalleriaBean {

private ResourceBundle configurationFBM;
private String pathFileUser;

@PostConstruct
public void init() {
FacesContext context = FacesContext.getCurrentInstance();
configurationFBM = context.getApplication().getResourceBundle(context,
“configurationFBM”);
if (this.configurationFBM != null) {
this.pathFileUser = configurationFBM.getString(“pathFileUser”);
}

}

public String getPathFileUser() {
return pathFileUser;
}

public void setPathFileUser(String pathFileUser) {
this.pathFileUser = pathFileUser;
}

}

Java Read Properties File Servlet

Ipotizzando che il file di properties si trovi sotto 

web-infclassescomprova.properties

dentro la servlet è sufficiente la seguente istruzione

ResourceBundle handlers = ResourceBundle.getBundle(“com.prova”);

Spring 3 @autowired Esempio


@autowired è usata per iniettare direttamente i valori configurati nell’xml nel bean.
Si puo usare  sul metodo set, costruttore o direttamente sul campo.

Bean
Bean dichiarato nel file xml con un solo  campo msg.

package com;

public class Message {

private String author;
private String body;

public String getAuthor() {
return author;
}

public void setAuthor(String author) {
this.author = author;
}

public String getBody() {
return body;
}

public void setBody(String body) {
this.body = body;
}

}

applicatioContext.xml
<beans xmlns=”http://www.springframework.org/schema/beans”
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xmlns:context=”http://www.springframework.org/schema/context”
xsi:schemaLocation=”http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd”
xmlns:util=”http://www.springframework.org/schema/util”>

<context:component-scan base-package=”com” />

<bean id=”provaBean” class=”com.ProvaBean”>

</bean>
<bean id=”message” class=”com.Message”>
<property name=”msg” value=”Hello World” />
<property name=”author” value=”Pippo” />
</bean>

</beans>


Abilitazione Annotazione
Per usare @autowired si deve registrare AutowiredAnnotationBeanPostProcessor. Questo si può fare in due modi:
1) si aggiunge
   <context:annotation-config />    
dentro applicationContext.xml
2) si aggiunge:
   <bean class=”org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor”/> dentro applicationContext.xml  
@autowired Esempi
@autowired su campo

ProvaBean.java
package com;

import org.springframework.beans.factory.annotation.Autowired;

public class ProvaBean {
@Autowired
private Message message;

public Message getMessage() {
return message;
}

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


}

@autowired sul metodo set

ProvaBean.java
package com;

import org.springframework.beans.factory.annotation.Autowired;

public class ProvaBean {

private Message message;

public Message getMessage() {
return message;
}

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


}


@autowired sul costruttore

ProvaBean.java
package com;

import org.springframework.beans.factory.annotation.Autowired;

public class ProvaBean {

private Message message;

@Autowired
public ProvaBean(Message msg)
{
message = msg;
}

public Message getMessage() {
return message;
}

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


}



Esecuzione Test

TestBean.java
package com;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestBean {

public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
“applicationContext.xml”);

ProvaBean obj = (ProvaBean) context.getBean(“provaBean”);
System.out.println(obj.getMessage().getBody());
System.out.println(obj.getMessage().getAuthor());
}

}


avviando il main si otterrà, in tutte e tre casi, il seguente output:

Java Reflection Esempio

Copiare due classi diverse ma con gli stessi campi tramite la reflection

Bean 

A.java

package com;

import java.lang.reflect.Field;

public class A {
private String name;

private long punteggio;

public long getPunteggio() {
return punteggio;
}

public void setPunteggio(long punteggio) {
this.punteggio = punteggio;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}

B.java

package com;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class B {
private String name;

private long punteggio;

public long getPunteggio() {
return punteggio;
}

public void setPunteggio(long punteggio) {
this.punteggio = punteggio;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public void copy(Object obj) {
try {

Method[] methods = obj.getClass().getMethods();

for (int i = 0; i < methods.length; i++) {
String methodName = methods[i].getName();
try{
if(methodName.startsWith(“get”)){
this.getClass().getMethod(methodName.replaceFirst(“get”, “set”) , methods[i].getReturnType() ).invoke(this, methods[i].invoke(obj, null));
}else if(methodName.startsWith(“is”) ){
this.getClass().getMethod(methodName.replaceFirst(“is”, “set”) ,  methods[i].getReturnType()  ).invoke(this, methods[i].invoke(obj, null));
}

}catch (NoSuchMethodException e) {
// TODO: handle exception
}catch (IllegalArgumentException e) {
// TODO: handle exception
}

}

} catch (Exception ex) {
ex.printStackTrace();
}
}

}


Classe per il test:
TestReflection.java
package com;
public class TestReflection {
public static void main(String[] args) {
A obj1 = new A();
obj1.setName(“hello world”);
A obj2 = new A();
obj2.copy(obj1);
System.out.println(“name obj copy with reflection:”+obj2.getName());
}
}
Esecuzione
lanciando il main si ottiene una copia identica dell’istanza obj1:

Spring 3 Bean Example

Configurazione
Mettere il seguente file dentro la cartella resources.

applicationContext.xml

<beans xmlns=”http://www.springframework.org/schema/beans”
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xmlns:context=”http://www.springframework.org/schema/context”
xsi:schemaLocation=”http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd”
xmlns:util=”http://www.springframework.org/schema/util”>

<context:component-scan base-package=”com” />

  <bean id=”provaBean” class=”com.ProvaBean”>
</bean>
</beans>

Bean Spring
creare un file java di nome ProvaBean nel package “com”
ProvaBean.java
package com;
public class ProvaBean {
private String msg = “HelloWord”;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
creare un file java di nome TestBean:
TestBean.java
package com;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestBean {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
“applicationContext.xml”);
ProvaBean obj = (ProvaBean) context.getBean(“provaBean”);
System.out.println(obj.getMsg());
}
}

Esecuzione
lanciare il main del file TestBean. L’ouput sarà: