我已经让Primefaces成功地为全局路径工作,但是我在使参数化路径工作时遇到了一些困难。我们的想法是将FacesMessages推送给个人用户。
所以我的index.xhtml:
<p:socket onMessage="handlePush" channel="/#{parliamentManager.user}" autoConnect="true" widgetVar="subscriber"/>
在ParliamentManager中,我得到用户并连接到频道:
@PostConstruct
public void postInit() {
logger.log(Level.INFO,"Session started");
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
Map<String, Object> sessionMap = externalContext.getSessionMap();
user = (User) sessionMap.get("user");
logger.log(Level.INFO, "user trader is: {0}",
new Object[]{user.getTrader().getTraderId().toString()});
RequestContext requestContext = RequestContext.getCurrentInstance();
requestContext.execute("alert('PostConstruct')");
requestContext.execute("PF('subscriber').connect('/" + user + "')");
}
在我的RequestScoped有状态bean中,验证发生时我尝试推送消息(现在使用硬编码用户):
if((book.getPrice() * bidOrder.getAmount()) > bidOrder.getTrader().getBalance())
{
EventBus eventBus = EventBusFactory.getDefault().eventBus();
eventBus.publish("jimmy" , new FacesMessage("Error", "You have " + bidOrder.getTrader().getBalance()
+ " and are trying to buy " + book.getPrice()*bidOrder.getAmount()));
return;
}
但是我的PushResource onMessage永远不会被触发。我怀疑我在pushresource中的某个地方使用了错误的语法参数或在eventBus.publish消息中,虽然我不确定它应该是什么:
PushResource:
@PushEndpoint("{user}")
@Singleton
public class PushResource
{
private static final Logger logger = Logger.getLogger("politse.web.PushResource");
@PathParam("user")
private String user;
@OnMessage(decoders = JSONDecoder.class, encoders = JSONEncoder.class)
public void onMessage(RemoteEndpoint r, EventBus eventBus) {
logger.log(Level.INFO, "PushResource.onMessage user: {0}",
new Object[]{user});
}
}
答案 0 :(得分:0)
在没有&#34; /&#34的eventBus.publish用户中;可能就是这个问题
答案 1 :(得分:0)
我在初始代码中犯了一些错误,当我将onOpen添加到我的资源对象并记录了通道名称时,这些错误变得很明显。首先,我的套接字通道变量指向用户实体对象而不是用户ID。所以我在ParliamentManager中创建了userId作为String属性。这创建了一个正确命名的频道。
<p:socket onMessage="handlePush" channel="/#{parliamentManager.userId}" autoConnect="true" widgetVar="subscriber"/>
如果autoConnect = true,我也不需要连接到频道,所以我从ParliamentManager @PostConstruct中删除了它。我的编码器也错了,我把它改为正确接受了FacesMessage。
@PushEndpoint("{user}")
@Singleton
public class PushResource
{
private static final Logger logger = Logger.getLogger("politse.web.PushResource");
@PathParam("user")
private String user;
@OnOpen
public void onOpen(RemoteEndpoint r, EventBus eventBus) {
logger.log(Level.INFO, "PushResource.onOpen endpoint: {0}",
new Object[]{r});
}
@OnClose
public void onClose(RemoteEndpoint r, EventBus eventBus) {
logger.log(Level.INFO, "PushResource.onClose endpoint: {0}",
new Object[]{r});
}
@OnMessage(encoders = {JSONEncoder.class})
public FacesMessage onMessage(FacesMessage message) {
logger.log(Level.INFO, "PushResource.onMessage facesMessage");
return message;
}
}
EventBus发布代码实际上是正确的,不需要额外的斜杠。