Java EE 7 WebSocket example

1. Createa a Java EE Web application called MyWebSocket for example.
2. In index.html:

<!DOCTYPE html>
<html>
    <head>
        <title>Start Page</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script language="javascript">
            var ws;
            function connect() {
                ws = new WebSocket("ws://localhost:8080/MyWebSocket/sockOne");
                ws.onmessage = onMessage;
            }
            function onMessage(evt) {
                var dataarr = evt.data;
                document.getElementById("valueElement").innerHTML = dataarr;
            }
            window.addEventListener("load", connect, false);
        </script>
    </head>
    <body>
        <h1>Hello World!</h1>
        <b>Value: </b>
        <b id="valueElement">no data yet</b>
    </body>
</html>

2. Create a class Called WebSocketEndpoint. Here the most important annotations are @ServerEndpoint, @OnOpen, @OnClose and @OnError, in these methods you put whatever you want to get executed when these events happen:

package com.vvirlan.websocket;

import java.io.IOException;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

/**
 *
 * @author vvirlan
 */
@ServerEndpoint("/sockOne")
public class WebSocketEndpoint {

    private static final Logger LOGGER = Logger.getLogger("WebSocketEndpoint");
    private static Queue<Session> sessionQueue = new ConcurrentLinkedQueue<>();

    public static void send(double number) {
        String toSend = String.format("%f", number);
        try {
            for (Session session : sessionQueue) {
                session.getBasicRemote().sendText(toSend);
                LOGGER.log(Level.INFO, "Sent: {0}", toSend);
            }
        } catch (IOException e) {
            LOGGER.log(Level.SEVERE, e.toString());
        }
    }

    @OnOpen
    public void openConnection(Session session) {
        sessionQueue.add(session);
        LOGGER.log(Level.INFO, "Connection opened");
    }

    @OnClose
    public void closeConnection(Session session) {
        sessionQueue.remove(session);
        LOGGER.log(Level.INFO, "Connection closed");
    }

    @OnError
    public void error(Session session, Throwable th) {
        sessionQueue.remove(session);
        LOGGER.log(Level.WARNING, "Connection errorred");
        LOGGER.log(Level.WARNING, th.toString());

    }
}

3. The bean which will produce our fake data. It gets injected a TimerService as a @Resource and when @Timeout happens it invokes the send method of our endpoint:

package com.vvirlan.websocket;

import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.Timeout;
import javax.ejb.TimerConfig;
import javax.ejb.TimerService;

/**
 *
 * @author vvirlan
 * Generates a double every second and calls the endpoint for updating the clients
 */
@Startup
@Singleton
public class GeneratorBean {
    @Resource TimerService timerService;
    private Random random;
    private volatile double number = 777.0;
    private static final Logger logger = Logger.getLogger("GeneratorBean");
    
    @PostConstruct
    public void init() {
        logger.log(Level.INFO, "Initializing EJB");
        random = new Random();
        timerService.createIntervalTimer(1000, 1000, new TimerConfig());
    }
    
    @Timeout
    public void timeout() {
        number = 1.5 * (random.nextInt(100));
        WebSocketEndpoint.send(number);
    }
}

JSF simple ajax example

Here is a simple AJAX example in JSF (run on Glassfish).
Just to note: for sending the value to the bean you use the execute attribute of f:ajax, and for displaying the output from the beans’s getter, you use the render attribute.

1. pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.mycompany</groupId>
    <artifactId>ajaxtest</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>ajaxtest</name>

    <properties>
        <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    
    <dependencies>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <compilerArguments>
                        <endorseddirs>${endorsed.dir}</endorseddirs>
                    </compilerArguments>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.6</version>
                <executions>
                    <execution>
                        <phase>validate</phase>
                        <goals>
                            <goal>copy</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${endorsed.dir}</outputDirectory>
                            <silent>true</silent>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>javax</groupId>
                                    <artifactId>javaee-endorsed-api</artifactId>
                                    <version>7.0</version>
                                    <type>jar</type>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

2. The xhtml page:

<?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://xmlns.jcp.org/jsf/html"
      xmlns:f="http://xmlns.jcp.org/jsf/core">
    <h:head>
        <title>Facelet Title</title>
    </h:head>
    <h:body>
        Hello from Facelets
        
        <h:form>
            <h:inputText id="msg" value="#{myBean.text}"/>
        <h:commandButton id="submit" value="Submit">
            <f:ajax event="click"  execute="msg" render="outText"/>
        </h:commandButton>
            <h:outputText value="The message: #{myBean.text}" id="outText">
            </h:outputText>
            
            </h:form>
        
    </h:body>
</html>

3. The Bean:

package com.mycompany.ajaxtest;

import java.io.Serializable;
import javax.enterprise.inject.Model;

/**
 *
 * @author vvirlan
 */
@Model
public class MyBean implements Serializable {
    
    private String text = "defaullt";
    
    
    public void message() {
        System.out.println("The message "+text);
        
    }

    public String getText() {
        System.out.println("getText message "+text);
        return text;
    }

    public void setText(String text) {
        System.out.println("setText message "+text);
        this.text = text;
    }
}

[java] check password against DB

To check the password against the database encoded value is simple, but it is not supported out of the box. You’ll have to convert the generated hash into hex format

		byte[] encoded = md.digest();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < encoded.length; i++) {
			sb.append(Integer.toString((encoded[i] & 0xff) + 0x100, 16).substring(1));
		}

Here’s a complete example:

public boolean validate(String username, String password) {
		final Query query = em.createQuery("SELECT u FROM User u WHERE u.username = :username");
		query.setParameter("username", username);

		List<User> foundUsers = (List<User>) query.getResultList();
		if (foundUsers == null || foundUsers.isEmpty()) {
			return false;
		}
		User foundUser = foundUsers.get(0);
		MessageDigest md = null;
		try {
			md = MessageDigest.getInstance("SHA");
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		md.update(password.getBytes());
		byte[] encoded = md.digest();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < encoded.length; i++) {
			sb.append(Integer.toString((encoded[i] & 0xff) + 0x100, 16).substring(1));
		}

		if (sb.toString().equals(foundUser.getPassword())) {
			return true;
		}

		return false;
	}

web.xml examples for all versions of Servlet

1. Servlet 3.1

<web-app 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"
         version="3.1">
</web-app>

2. Servlet 3.0

<web-app 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-app_3_0.xsd"
	      version="3.0">
</web-app>

3. Servlet 2.5

<web-app 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-app_2_5.xsd"
	      version="2.5">
</web-app>

4. Servlet 2.4

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
	      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	      xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	      http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
	      version="2.4">

  <display-name>Servlet 2.4 Web Application</display-name>
</web-app>

5. Servlet 2.3

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Servlet 2.3 Web Application</display-name>
</web-app>

[Starter] EJB Session Bean based Web Server and Servlet client

EJB Session Bean based Web Server and Servlet client in Netbeans

1. Create a Class Library project which will hold your Remote EJB interfaces

1

2. Create new interface called WsHello

package com.vvirlan.ejb;
import javax.ejb.Remote;
@Remote
public interface WsHello {
    public String sayHello(String name);
}

3. Create a new Project of type EJB Module
3
4. Create a new class in the EJB Module this class will implement your interface defined in the Class Library you defined earlier

package com.vvirlan.ejb;

import javax.ejb.Stateless;
import javax.jws.WebMethod;
import javax.jws.WebService;
@Stateless
@WebService
public class WsHelloImpl implements WsHello {
    private String msg = "Hello! ";
    @WebMethod
    public String sayHello(String name) {
        return msg + name;
    }
}

5. Create a Web Application and a new Servlet in it. Here you add the annotation @EJB to autowire your interface.

package com.vvirlan.servlet;

import com.vvirlan.ejb.HelloServiceBean;
import com.vvirlan.ejb.WsHello;
import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class WsServlet extends HttpServlet {

    @EJB
    private WsHello hello;
  
    
    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String result = hello.sayHello("Vlad");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet WsServlet</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet WsServlet at " + request.getContextPath() + "</h1>");
            out.println("<h1>Servlet WsServlet at " + result + "</h1>");
            out.println("</body>");
            out.println("</html>");
        }
    }
}

6. Add the Class Library as a dependency in your web application project. Now all errors should solve by themselves.

2

JSF – Add OmniFaces to your project

1. In pom.xml


<dependency>
            <groupId>org.omnifaces</groupId>
            <artifactId>omnifaces</artifactId>
            <version>2.0</version>
 </dependency>

2. You should put your xhtml pages under:

src/main/webapp/WEB-INF/faces-views

3. In your bean for example. Here strange is a xhtml file under the folder stated in point 2:

 ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
 ec.redirect(ec.getRequestContextPath() + "strange");