hu.bme.iit.quiz.endpoint.IndexEndpoint.java Source code

Java tutorial

Introduction

Here is the source code for hu.bme.iit.quiz.endpoint.IndexEndpoint.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 hu.bme.iit.quiz.endpoint;

import hu.bme.iit.quiz.model.Quiz;
import hu.bme.iit.quiz.model.QuizPresentation;
import hu.bme.iit.quiz.model.User;
import hu.bme.iit.quiz.util.EndpointUtil;
import hu.bme.iit.quiz.util.HibernateUtil;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.inject.Singleton;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.json.JSONStringer;

@ServerEndpoint("/indexendpoint")
@Singleton
public class IndexEndpoint {

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

    private static Set<Session> peers = Collections.synchronizedSet(new HashSet<Session>());

    // <userkey, quizkey> pattern: a user only can have one quiz in active phase
    private static Map<String, QuizPresentation> quizzesInGatheringPhase = Collections
            .synchronizedMap(new HashMap<String, QuizPresentation>());

    @OnMessage
    public String onMessage(String jMessage, Session session) {
        logger.debug("onMessage websocket event: " + jMessage);
        JSONObject message = new JSONObject(jMessage);
        try {
            logger.debug("type: " + message.getString("type"));
            switch (message.getString("type")) {
            case "STARTLOBBY":
                startGatheringQuiz(message.getString("userkey"), message.getString("quizkey"));
                break;
            default:
                logger.warn("Websocket SWITCH drive in default case.");
                break;
            }
        } catch (Exception e) {
            logger.error(e);
        }

        return null;
    }

    @OnOpen
    public void onOpen(Session peer) {
        peers.add(peer);
        logger.debug("Peer connected: " + peer.getId() + "; Total peer number: " + peers.size() + "; Quizzes: "
                + quizzesInGatheringPhase.size());
        EndpointUtil.sendUpdateToPeer(peer, createGatheringQuizzesUpdateString());

    }

    @OnClose
    public void onClose(Session peer) {
        logger.debug("Peer disconnected :: " + peer.getId());
        //        String deleted = quizzesInGatheringPhase.remove(users.get(peer));
        //        users.remove(peer);
        peers.remove(peer);
        //        if(deleted != null)
        //            sendUpdate();
    }

    @OnError
    public void onError(Throwable t) {
    }

    private String createGatheringQuizzesUpdateString() {
        JSONStringer creator = new JSONStringer();
        creator.object().key("type").value("QUIZZESUPDATE").key("quizzes").array();
        for (String key : quizzesInGatheringPhase.keySet()) {
            QuizPresentation quizPresentation = quizzesInGatheringPhase.get(key);
            creator.object().key("username").value(quizPresentation.getOwner().getLogin()).key("quizname")
                    .value(quizPresentation.getQuiz().getName()).key("presenationID")
                    .value(quizPresentation.getId()).key("started").value(quizPresentation.getStarted())
                    .endObject();
        }
        creator.endArray().endObject();
        return creator.toString();
    }

    private void startGatheringQuiz(String userkey, String quizkey) {
        logger.debug("startGatheringQuiz websocket event: ");
        quizzesInGatheringPhase.put(userkey, EndpointUtil.getQuizPresentationByKeys(userkey, quizkey));
        EndpointUtil.sendUpdateToAll(peers, createGatheringQuizzesUpdateString());
    }

}