com.josue.ws.web.server.MessageDispatcher.java Source code

Java tutorial

Introduction

Here is the source code for com.josue.ws.web.server.MessageDispatcher.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.josue.ws.web.server;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.josue.shared.online.NetworkConnection;
import com.josue.shared.online.NetworkPackage;
import com.josue.shared.online.NetworkPlayer;

import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.websocket.CloseReason;
import javax.websocket.Session;
import java.io.IOException;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author Josue
 */
@ApplicationScoped
public class MessageDispatcher {

    private static final Logger logger = Logger.getLogger(MessageDispatcher.class.getName());

    @Inject
    SessionStore store;

    private ObjectMapper mapper;

    @PostConstruct
    public void init() {
        mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);
        mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }

    public void proccessMessage(String map, Session session, String message) {
        if (message == null || message.isEmpty()) {
            logger.warning("Empty message payload");
        }

        try {
            NetworkPackage networkPackage = mapper.readValue(message, NetworkPackage.class);

            MessageRequestWrapper wrapper = new MessageRequestWrapper(message, networkPackage, session, map);

            if (null != networkPackage.getType()) {
                switch (networkPackage.getType()) {
                case CONNECTION:
                    proccessConnectionMessage(wrapper);
                    break;
                case MESSAGE:
                    proccessOnlineMessage(wrapper);
                    break;
                case WORLD:
                    proccessWorldMessage(wrapper);
                    break;
                case PLAYER:
                    proccessPlayerMessage(wrapper);
                    break;
                default:
                    logger.log(Level.WARNING, "Invalid message payload: {0}", message);
                    break;
                }
            }
        } catch (IOException ex) {
            logger.log(Level.SEVERE, "Error while deserializang message", ex);
        }
    }

    private void proccessConnectionMessage(MessageRequestWrapper wrapper) throws IOException {
        NetworkConnection connection = wrapper.getResource();

        if (connection.getState() != null) {
            switch (connection.getState()) {
            case AFK:
                break;
            case CONNECTED_PLAYER:
                store.put(wrapper.getMap(), wrapper.getSession(), connection.getPlayer());
                sendAllExceptSender(wrapper);
                sendConnectedUsers(wrapper);
                break;
            case DISCONNECTED:
                wrapper.getSession().close(new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE,
                        "Player " + wrapper.getSession().getId() + " disconnected"));
                sendAllExceptSender(wrapper);
                break;
            default:
                logger.log(Level.WARNING, "Invalid connection status: {0}", connection.getState());
                break;
            }
        }

    }

    private void proccessOnlineMessage(MessageRequestWrapper wrapper) {
        sendAllExceptSender(wrapper);
    }

    private void proccessWorldMessage(MessageRequestWrapper wrapper) {

    }

    private void proccessPlayerMessage(MessageRequestWrapper wrapper) {
        //update player position in the server
        store.put(wrapper.getMap(), wrapper.getSession(), wrapper.<NetworkPlayer>getResource());

        sendAllExceptSender(wrapper);
    }

    private void sendConnectedUsers(MessageRequestWrapper wrapper) {
        try {
            NetworkConnection connectingPlayer = wrapper.getResource();

            Iterator<NetworkPlayer> it = store.getPlayers(wrapper.getMap());

            while (it.hasNext()) {
                NetworkPlayer connected = it.next();
                if (!connected.getUuid().equals(connectingPlayer.getPlayer().getUuid())) { //not the actual player
                    NetworkConnection conectedPlayersResponse = new NetworkConnection(
                            NetworkConnection.ConnectionState.CONNECTED_PLAYER, connected);
                    String jsonResp = mapper.writeValueAsString(conectedPlayersResponse);
                    wrapper.getSession().getAsyncRemote().sendText(jsonResp);
                }
            }
        } catch (Exception e) {
            logger.severe("Error while sending connected players");
        }
    }

    private void sendWelcomePackage(MessageRequestWrapper wrapper) {
        try {
            NetworkConnection connectingPlayer = wrapper.getResource();

            Iterator<NetworkPlayer> it = store.getPlayers(wrapper.getMap());

            while (it.hasNext()) {
                NetworkPlayer connected = it.next();
                if (!connected.getUuid().equals(connectingPlayer.getPlayer().getUuid())) { //not the actual player
                    NetworkConnection conectedPlayersResponse = new NetworkConnection(
                            NetworkConnection.ConnectionState.WELCOME, connected);
                    String jsonResp = mapper.writeValueAsString(conectedPlayersResponse);
                    wrapper.getSession().getAsyncRemote().sendText(jsonResp);
                }
            }
        } catch (Exception e) {
            logger.severe("Error while sending connected players");
        }
    }

    private void sendAllExceptSender(MessageRequestWrapper wrapper) {
        Iterator<Session> sessions = store.getSessions(wrapper.getMap());
        while (sessions.hasNext()) {
            Session onlineSession = sessions.next();
            if (!onlineSession.equals(wrapper.getSession())) {
                onlineSession.getAsyncRemote().sendText(wrapper.getOriginalMessage());
            }
        }
    }

}