@Transacional Spring + Hibernate

@Service
@Transactional(rollbackFor = Throwable.class)
public class VeiculoService {

@Autowired
private VeiculoRepository veiculoRepository;

public Veiculo findOne(Long id) throws VeiculoNaoEncontratoException {

Veiculo veiculo = veiculoRepository.findOne(id);

if (veiculo == null) {
throw new VeiculoNaoEncontratoException("Veículo não encontrado!");
}

return veiculo;
}
}

By default the annotation @Transactional on Spring Framework will rollback exeptions from the type RuntimeException but sometimes we need to create our own exceptions or we need rollback to any exception in our application.

@Transactional(rollbackFor=Throwable.class)

I put the property “rollbackFor” in @Transactional annotation for Throwable.class. This way any excetion in my application will to cause rollback on all my transactions. Ensuring the ACID in my operation.

Tomcat 5.57 + Websockets + Javascript HTML5

WebSocket is a protocol to provide a bidirecional channel over TCP protocol. Its used usually when we need to have a open channel between client and server where the server can send data to client and the client can send data to server.

WebSocket can be used by whatever client or application server. The unique relationship with the HTTP is that its handshake is interpreted by HTTP servers like a upgrade request.

I will show a example how to implement WebSocket on Tomcat Application Server

The WebSocket API for Tomcat Server is available from its 7.47 version.
(The version 7.47 has a bug when the client closes the connection. Its better you to download a version after 7.47 like 7.50 for example)

Hands On 😉

package com.titorec.blog;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.websocket.CloseReason;
import javax.websocket.EncodeException;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import com.google.gson.Gson;
import com.titorec.blog.model.WebSocketMessage;
import com.titorec.blog.model.enumerator.WebSocketMessageType;

@ServerEndpoint(value = "/protected/wsocket")
public class WebSocketServlet {

private static List sessionList = new ArrayList();

public WebSocketServlet() {

}

@OnOpen
public void onOpen(Session session, EndpointConfig endpointconfig)
throws IOException {
Long idusuario = Long
.parseLong(session.getQueryString().split("&")[0]
.split("=")[1]);

session.getUserProperties().put("idusuario", idusuario);

sessionList.add(session);
}

@OnClose
public void onClose(Session session, CloseReason closeReason) {
sessionList.remove(session);
}

public static void enviarMensagemParaUsuario(Long idusuario,
WebSocketMessageType webSocketType, String msg) throws IOException,
EncodeException {
for (Session currentSession : sessionList) {
Long currentIdusuario = (Long) currentSession.getUserProperties()
.get("idusuario");

if (currentIdusuario.compareTo(idusuario) == 0) {
WebSocketMessage webSocketMessage = new WebSocketMessage();

webSocketMessage.setTipo(webSocketType.getValue());
webSocketMessage.setConteudo(msg);

synchronized (currentSession.getAsyncRemote()) {
currentSession.getAsyncRemote().sendText(
new Gson().toJson(webSocketMessage));
}
}
}
}

@OnError
public void onError(Session session, Throwable thr) {

}

public static void enviarMensagemParaTodos(
WebSocketMessageType webSocketType, String msg) throws IOException,
EncodeException {
for (Session currentSession : sessionList) {
WebSocketMessage webSocketMessage = new WebSocketMessage();

webSocketMessage.setTipo(webSocketType.getValue());
webSocketMessage.setConteudo(msg);

synchronized (currentSession.getAsyncRemote()) {
currentSession.getAsyncRemote().sendText(
new Gson().toJson(webSocketMessage));
}
}
}
}

public class WebSocketMessage {
private String tipo;
private String conteudo;

public String getTipo() {
return tipo;
}

public void setTipo(String tipo) {
this.tipo = tipo;
}

public String getConteudo() {
return conteudo;
}

public void setConteudo(String conteudo) {
this.conteudo = conteudo;
}

}

This URL identify the channel for connections
@ServerEndpoint(value=”/protected/wsocket”)

The annotation @OnOpen is used to map the method that will be executed when a user connect to the server.

The annotation @OnClose is used to get the moment when a user closes the connection.

The annotation @OnError is used to get when the connection is broken

I have created a presence list where I hold users that are connected on the server. furthermore I have created two methods to send messages for the clients.

Now we need to create our javascript file to connect on the server and receive messages sent.

websocket = new WebSocket("ws://" + document.location.host + "/meuprojeto/protected/wsocket?idUsuario=50");

websocket.onmessage = function onMessageReceived(evt) {

var notificacao = JSON.parse(evt.data);

if (notificacao.tipo == INFO){
console.log("notification info!");
}
else if (notificacao.tipo == ERROR){
console.log("notification erro!");
}
else if (notificacao.tipo == SUCCESS){
console.log("notification success!");
}
}

websocket.onopen = function(evt){
console.log("[ Connection open. ]")
}

websocket.onclose = function(evt){
console.log("[ Connection closed. ]")
}

websocket.onerror = function(evt){
console.log("[ Error. ]")
}