Singleton EJB - Initiates the connection to a web socket server
This file contains 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 blog.abhirockzz.wordpress.com; | |
import java.io.IOException; | |
import java.net.URI; | |
import java.net.URISyntaxException; | |
import java.util.logging.Level; | |
import java.util.logging.Logger; | |
import javax.annotation.PostConstruct; | |
import javax.annotation.PreDestroy; | |
import javax.ejb.Singleton; | |
import javax.ejb.Startup; | |
import javax.inject.Inject; | |
import javax.websocket.ContainerProvider; | |
import javax.websocket.DeploymentException; | |
import javax.websocket.MessageHandler; | |
import javax.websocket.Session; | |
import javax.websocket.WebSocketContainer; | |
@Singleton | |
@Startup | |
public class StockServiceBootstrapBean { | |
private final String WS_SERVER_URL = "ws://api.stocks/ticker"; //fictitious | |
private Session session = null; | |
@Inject | |
StockInfoPersistenceService tickRepo; | |
@PostConstruct | |
public void bootstrap() { | |
WebSocketContainer webSocketContainer = null; | |
try { | |
webSocketContainer = ContainerProvider.getWebSocketContainer(); | |
session = webSocketContainer.connectToServer(StockTickerClient.class, new URI(WS_SERVER_URL)); | |
System.out.println("Connected to WS endpoint " + WS_SERVER_URL); | |
session.addMessageHandler(new MessageHandler.Whole<String>() { | |
@Override | |
public void onMessage(String msg) { | |
tickRepo.save(msg.split(":")[0], msg.split(":")[1]); | |
} | |
}); | |
} catch (DeploymentException | IOException | URISyntaxException ex) { | |
Logger.getLogger(StockServiceBootstrapBean.class.getName()).log(Level.SEVERE, null, ex); | |
} | |
} | |
@PreDestroy | |
public void destroy() { | |
close(); | |
} | |
private void close() { | |
try { | |
session.close(); | |
System.out.println("CLOSED Connection to WS endpoint " + WS_SERVER_URL); | |
} catch (IOException ex) { | |
Logger.getLogger(StockServiceBootstrapBean.class.getName()).log(Level.SEVERE, null, ex); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment