Created
May 22, 2015 18:53
-
-
Save mariofts/574e7a580a8428d85121 to your computer and use it in GitHub Desktop.
WebSocket com JSF
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package br.com.caelum.notasfiscais.websocket; | |
import java.util.ArrayList; | |
import java.util.Arrays; | |
import javax.enterprise.context.ApplicationScoped; | |
import javax.websocket.OnClose; | |
import javax.websocket.OnMessage; | |
import javax.websocket.OnOpen; | |
import javax.websocket.Session; | |
import javax.websocket.server.ServerEndpoint; | |
@ApplicationScoped | |
@ServerEndpoint(value = "/apuracao") | |
public class Apuracao { | |
private static ArrayList<Session> sessions = new ArrayList<>(); | |
private String[][] ultimosDados = {}; | |
@OnMessage | |
public void messageReceiver(String message) { | |
System.out.println("Received message:" + message); | |
} | |
@OnOpen | |
public void onOpen(Session session) { | |
System.out.println("Conectando com: " + session.getId()); | |
sessions.add(session); | |
System.out.println("CLientes conectados" + sessions.size()); | |
} | |
@OnClose | |
public void onClose(Session session) { | |
System.out.println("Desconectando: " + session.getId()); | |
sessions.remove(session); | |
} | |
public String[][] getUltimosDados() { | |
return ultimosDados; | |
} | |
public void novoStatus(String[][] dados) { | |
System.out.println("Recebendo os ultimos dados"); | |
this.ultimosDados = dados; | |
for (Session session : sessions) { | |
session.getAsyncRemote().sendText(transform(dados)); | |
} | |
} | |
private String transform(String[][] dados) { | |
String result = "["; | |
for (String[] x : dados) { | |
result += "[\""+x[0]+"\"" + "," + x[1] + "],"; | |
} | |
return result.substring(0,result.length()-1) + "]"; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html xmlns="http://www.w3.org/1999/xhtml" | |
xmlns:h="http://java.sun.com/jsf/html" | |
xmlns:ui="http://java.sun.com/jsf/facelets" | |
xmlns:p="http://primefaces.org/ui" | |
xmlns:f="http://java.sun.com/jsf/core"> | |
<ui:composition template="/_template.xhtml"> | |
<ui:define name="corpo"> | |
<script type="text/javascript"> | |
var host = "ws://localhost:8080/fj26-notas-fiscais/apuracao" | |
var wSocket = new WebSocket(host); | |
var browserSupport = ("WebSocket" in window) ? true : false; | |
if (browserSupport) { | |
wSocket.onopen = function() { | |
//alert(" Web Socket is connected, sending data"); | |
wSocket.send("ping"); | |
}; | |
} else { | |
// The browser doesn't support WebSocket | |
alert("WebSocket is NOT supported by your Browser!"); | |
} | |
// called when a message is received | |
wSocket.onmessage = function(event) { | |
var received_msg = event.data; | |
// console.log(received_msg); | |
// var serie = JSON.parse(received_msg); | |
// console.log(serie) | |
alert('server msg:' + received_msg); | |
// var grafico = PF('grafico'); | |
// grafico.plot.replot({ series : serie}); | |
}; | |
// called when socket closes | |
wSocket.onclose = function() { | |
// websocket is closed. | |
console.log("Connection is closed..."); | |
}; | |
</script> | |
<h2>Dados de Apuração</h2> | |
<h:form id="formlogin"> | |
<h:messages styleClass="erros" /> | |
<fieldset> | |
<legend>Resultado parcial</legend> | |
<p:chart type="pie" model="#{dadosBean.dados}" widgetVar="grafico" /> | |
</fieldset> | |
</h:form> | |
</ui:define> | |
</ui:composition> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package br.com.caelum.notasfiscais.mb; | |
import javax.faces.view.ViewScoped; | |
import javax.inject.Inject; | |
import javax.inject.Named; | |
import org.primefaces.model.chart.PieChartModel; | |
import br.com.caelum.notasfiscais.websocket.Apuracao; | |
@Named | |
@ViewScoped | |
public class DadosBean { | |
@Inject | |
private Apuracao apuracao; | |
private PieChartModel dados = new PieChartModel();; | |
public PieChartModel getDados() { | |
System.out.println("Montando o gráfico..."); | |
String[][] ultimosDados = apuracao.getUltimosDados(); | |
for (String[] info : ultimosDados) { | |
dados.set(info[0], Integer.parseInt(info[1])); | |
} | |
dados.setTitle("Dados de apuração"); | |
dados.setLegendPosition("w"); | |
dados.setShowDataLabels(true); | |
return dados; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package br.com.caelum.notasfiscais.websocket; | |
import java.util.Random; | |
import javax.ejb.Schedule; | |
import javax.ejb.Singleton; | |
import javax.ejb.Startup; | |
import javax.inject.Inject; | |
@Startup | |
@Singleton | |
public class GeradorDeDados { | |
private String[] nomes = {"Huguinho", "Zezinho", "Luizinho"}; | |
private Random random = new Random(); | |
@Inject | |
private Apuracao apuracao; | |
/** | |
* De minuto em minuto, gera um array no formato: | |
* | |
* [ | |
* [Huguinho, X] | |
* [Zezinho, Y] | |
* [Luizinho, Z] | |
* ] | |
* (onde X,Y e Z são números aleatórios entre 0 e 100) | |
* | |
* E passa para o mecanismo de apuração | |
* | |
*/ | |
@Schedule(second = "*/10", minute = "*", hour = "*", info="Every 5 seconds", persistent=false) | |
public void gera(){ | |
System.out.println("Gerando dados para o websocket..."); | |
String[][] dados = new String[3][2]; | |
for(int i = 0; i< nomes.length; i++){ | |
dados[i] = new String[] {nomes[i], String.valueOf(random.nextInt(100))}; | |
} | |
apuracao.novoStatus(dados); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment