1. java
  2. android
  3. c#
  4. .net
  5. javascript
  6. php
  7. jquery
  8. html
  9. sql

Primefaces Push (Chat)

Boa noite, gostaria de saber se alguém já conseguiu fazer funcionar o chat do primefaces? Estou tentando mas está dando vários erros, e não estou sabendo arrumar.

Coloquei todos os métodos importantes que podem ter algum erro, se alguém puder dar uma olhada agradeceria muito pois estou começando a programar com primefaces e é bastante coisa para aprender e entender...

Segue abaixo os métodos:

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">

    <context-param>
        <param-name>com.sun.faces.verifyObjects</param-name>
        <param-value>false</param-value>
    </context-param>
    <context-param>
        <param-name>com.sun.faces.validateXml</param-name>
        <param-value>true</param-value>
    </context-param>
    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Development</param-value>
    </context-param>
    <!-- FILTER -->
    <filter>
        <filter-name>FilterSecurity</filter-name>
        <filter-class>servlet.FilterSecurity</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>FilterSecurity</filter-name>
        <url-pattern>/users/*</url-pattern>
    </filter-mapping>
    <!-- FILTER -->
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet>
        <servlet-name>Push Servlet</servlet-name>
        <servlet-class>org.primefaces.push.PushServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Push Servlet</servlet-name>
        <url-pattern>/users/*</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.xhtml</welcome-file>
    </welcome-file-list>
</web-app>

faces-config.xml

<?xml version='1.0' encoding='UTF-8'?>
<faces-config version="2.0"
              xmlns="http://java.sun.com/xml/ns/javaee"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd">
    <navigation-rule>
        <from-view-id>/index.xhtml</from-view-id>
        <navigation-case>
            <from-outcome>success</from-outcome>
            <to-view-id>/users/home.xhtml</to-view-id>
        </navigation-case>
        <navigation-case>
            <from-outcome>failure</from-outcome>
            <to-view-id>/index.xhtml</to-view-id>
        </navigation-case>
    </navigation-rule>

    <managed-bean>
        <managed-bean-name>autenticacao</managed-bean-name>
        <managed-bean-class>login.Login</managed-bean-class>
        <managed-bean-scope>request</managed-bean-scope>
    </managed-bean>
    <factory>
        <exception-handler-factory>
            Utils.CustomExceptionHandlerFactory
        </exception-handler-factory>
    </factory>
</faces-config>

método de login:

    public String checkLogin() throws Exception {

        FacesContext fc = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) fc.getExternalContext().getSession(false);
        if (entlogin.getNome() != null && entlogin.getNome().equals("faces")
                && entlogin.getSenha() != null && entlogin.getSenha().equals("123")) {
            session.setAttribute("NOME", entlogin.getNome());
            return "success";
        } else {
            addMessage("Informações incorretas!!!");
            return "failure";
        }
    }

filterSecurit.java

public class FilterSecurity implements Filter {

    private FilterConfig filterConfig = null;

    public FilterSecurity() {
    }

    private void doBeforeProcessing(ServletRequest request, ServletResponse response)
            throws IOException, ServletException {
        if (debug) {
            log("FilterSecurity:DoBeforeProcessing");
        }
    }

    private void doAfterProcessing(ServletRequest request, ServletResponse response)
            throws IOException, ServletException {
        if (debug) {
            log("FilterSecurity:DoAfterProcessing");
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain)
            throws IOException, ServletException {
        if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
            HttpServletRequest req = (HttpServletRequest) request;
            HttpServletResponse res = (HttpServletResponse) response;
            HttpSession session = req.getSession();

            String sess = (String) session.getAttribute("NOME");
            if (sess == null) {
                res.sendRedirect("/sinomp/");
            } else {
                chain.doFilter(request, response);
            }
        }
    }

    /**
     * Return the filter configuration object for this filter.
     *
     * @return
     */
    public FilterConfig getFilterConfig() {
        return (this.filterConfig);
    }

    /**
     * Set the filter configuration object for this filter.
     *
     * @param filterConfig The filter configuration object
     */
    public void setFilterConfig(FilterConfig filterConfig) {

        this.filterConfig = filterConfig;
    }

    @Override
    public void destroy() {

    }

    @Override
    public void init(FilterConfig filterConfig) {

        this.filterConfig = filterConfig;
        if (filterConfig != null) {
            if (debug) {
                log("FilterSecurity:Initializing filter");
            }
        }
    }

    /**
     * Return a String representation of this object.
     */
    @Override
    public String toString() {

        if (filterConfig == null) {
            return ("FilterSecurity()");
        }
        StringBuffer sb = new StringBuffer("FilterSecurity(");
        sb.append(filterConfig);
        sb.append(")");
        return (sb.toString());

    }

    private void sendProcessingError(Throwable t, ServletResponse response) {

        String stackTrace = getStackTrace(t);

        if (stackTrace != null && !stackTrace.equals("")) {

            try {

                response.setContentType("text/html");
                try (PrintStream ps = new PrintStream(response.getOutputStream());
                        PrintWriter pw = new PrintWriter(ps)) {
                    pw.print("<html>\n<head>\n<title>Error</title>\n</head>\n<body>\n"); //NOI18N

                    // PENDING! Localize this for next official release
                    pw.print("<h1>The resource did not process correctly</h1>\n<pre>\n");
                    pw.print(stackTrace);
                    pw.print("</pre></body>\n</html>"); //NOI18N
                }
                response.getOutputStream().close();
            } catch (Exception ex) {
            }
        } else {
            try {
                try (PrintStream ps = new PrintStream(response.getOutputStream())) {
                    t.printStackTrace(ps);
                }
                response.getOutputStream().close();
            } catch (Exception ex) {
            }
        }
    }

    public static String getStackTrace(Throwable t) {

        String stackTrace = null;

        try {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            t.printStackTrace(pw);
            pw.close();
            sw.close();
            stackTrace = sw.getBuffer().toString();
        } catch (Exception ex) {
        }
        return stackTrace;
    }

    public void log(String msg) {
        filterConfig.getServletContext().log(msg);
    }

    private static final boolean debug = true;
}

aqui é a parte do CHAT tal qual copiei do site do Primefaces:

<h:form id="form">
                <p:remoteCommand name="updateList" update="users" process="@this" />

                <p:fieldset id="container" legend="Sinomp chat" toggleable="false">

                    <h:panelGroup rendered="#{chatView.loggedIn}">
                        <h:panelGrid columns="2" columnClasses="publicColumn,usersColumn" style="width:100%">
                            <p:outputPanel id="public" layout="block" styleClass="ui-corner-all ui-widget-content chatlogs" />

                            <p:dataList id="users" var="user" value="#{chatUsers.users}" styleClass="usersList">
                                <f:facet name="header">
                                    Users
                                </f:facet>

                                <p:commandButton title="Chat" icon="ui-icon-comment" oncomplete="PF('pChat').show()" update=":FCentro:form:privateChatContainer">
                                    <f:setPropertyActionListener value="#{user}" target="#{chatView.privateUser}" />
                                </p:commandButton>
                                #{user}
                            </p:dataList>
                        </h:panelGrid>

                        <p:separator />

                        <p:inputText value="#{chatView.globalMessage}" styleClass="messageInput" />
                        <p:spacer width="5" />
                        <p:commandButton value="Send" actionListener="#{chatView.sendGlobal}" oncomplete="$('.messageInput').val('').focus()" />
                        <p:spacer width="5" />
                        <p:commandButton value="Disconnect" actionListener="#{chatView.disconnect}" global="false" update="container" />
                    </h:panelGroup>

                    <h:panelGroup rendered="#{not chatView.loggedIn}" >
                        Username: <p:inputText value="#{chatView.username}"/>

                        <p:spacer width="5" />
                        <p:commandButton value="Login" actionListener="#{chatView.login}" update="container"
                                         icon="ui-icon-person" />
                    </h:panelGroup>

                </p:fieldset>

                <p:dialog widgetVar="pChat" header="Private Chat" appendTo="@(body)" modal="true">
                    <h:panelGrid id="privateChatContainer" columns="2" columnClasses="vtop,vtop">
                        <p:outputLabel for="pChatInput" value="To: #{chatView.privateUser}" />
                        <p:inputTextarea id="pChatInput" value="#{chatView.privateMessage}" rows="5" cols="30" />

                        <p:spacer />
                        <p:commandButton value="Send" actionListener="#{chatView.sendPrivate}" oncomplete="PF('pChat').hide()" />
                    </h:panelGrid>
                </p:dialog>
            </h:form>

método chatview.java

public class ChatView implements Serializable {
    private static final long serialVersionUID = 8229709094851596118L;

//    private final PushContext pushContext = PushContextFactory.getDefault().getPushContext();

    private final EventBus eventBus = EventBusFactory.getDefault().eventBus();

    @ManagedProperty("#{chatUsers}")
    private ChatUsers users;

    private String privateMessage;

    private String globalMessage;

    private String username;

    private boolean loggedIn;

    private String privateUser;

    private final static String CHANNEL = "/{room}/";

    public ChatUsers getUsers() {
        return users;
    }

    public void setUsers(ChatUsers users) {
        this.users = users;
    }

    public String getPrivateUser() {
        return privateUser;
    }

    public void setPrivateUser(String privateUser) {
        this.privateUser = privateUser;
    }

    public String getGlobalMessage() {
        return globalMessage;
    }

    public void setGlobalMessage(String globalMessage) {
        this.globalMessage = globalMessage;
    }

    public String getPrivateMessage() {
        return privateMessage;
    }

    public void setPrivateMessage(String privateMessage) {
        this.privateMessage = privateMessage;
    }

    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }

    public boolean isLoggedIn() {
        return loggedIn;
    }
    public void setLoggedIn(boolean loggedIn) {
        this.loggedIn = loggedIn;
    }

    public void sendGlobal() {
        eventBus.publish(CHANNEL + "*", username + ": " + globalMessage);

        globalMessage = null;
    }

    public void sendPrivate() {
        eventBus.publish(CHANNEL + privateUser, "[PM] " + username + ": " + privateMessage);

        privateMessage = null;
    }

    public void login() {
        RequestContext requestContext = RequestContext.getCurrentInstance();

        if(users.contains(username)) {
            loggedIn = false;
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Username taken", "Try with another username."));
            requestContext.update("growl");
        }
        else {
            users.add(username);
            requestContext.execute("PF('subscriber').connect('/" + username + "')");
            loggedIn = true;
        }
    }

    public void disconnect() {
        //remove user and update ui
        users.remove(username);
        RequestContext.getCurrentInstance().update("form:users");

        //push leave information
        eventBus.publish(CHANNEL + "*", username + " left the channel.");

        //reset state
        loggedIn = false;
        username = null;
    }

método chatResourses.java - nesse método comentei o @Inject pois não é reconhecido, pode ser aqui o erro

@PushEndpoint("/{room}/{user}")
@Singleton
public class ChatResource {

    private final Logger logger = LoggerFactory.getLogger(ChatResource.class);

    @PathParam("room")
    private String room;

    @PathParam("user")
    private String username;

//    @Inject // AQUI ESSE INJECT NAO É RECONHECIDO, por isso comentei.. pode ser aqui o erro
    private ServletContext ctx;

    @OnOpen
    public void onOpen(RemoteEndpoint r, EventBus eventBus) {
        logger.info("OnOpen {}", r);

        eventBus.publish(room + "/*", new Message(String.format("%s has entered the room '%s'",  username, room), true));
    }

    @OnClose
    public void onClose(RemoteEndpoint r, EventBus eventBus) {
        ChatUsers users= (ChatUsers) ctx.getAttribute("chatUsers");
        users.remove(username);

        eventBus.publish(room + "/*", new Message(String.format("%s has left the room", username), true));
    }

    @OnMessage(decoders = {MessageDecoder.class}, encoders = {MessageEncoder.class})
    public Message onMessage(Message message) {
        return message;
    }

}
  1. Você vai ver essas setas em qualquer página de pergunta. Com elas, você pode dizer se uma pergunta ou uma resposta foram relevantes ou não.
  2. Edite sua pergunta ou resposta caso queira alterar ou adicionar detalhes.
  3. Caso haja alguma dúvida sobre a pergunta, adicione um comentário. O espaço de respostas deve ser utilizado apenas para responder a pergunta.
  4. Se o autor da pergunta marcar uma resposta como solucionada, esta marca aparecerá.
  5. Clique aqui para mais detalhes sobre o funcionamento do GUJ!

0 resposta

Não é a resposta que estava procurando? Procure outras perguntas com as tags primefaces jsf servlets webservices web.xml ou faça a sua própria pergunta.