com.lrazvan.server.connection.ApplicationServer.java Source code

Java tutorial

Introduction

Here is the source code for com.lrazvan.server.connection.ApplicationServer.java

Source

package com.lrazvan.server.connection;
// This file contains material supporting section 3.7 of the textbook:

// "Object Oriented Software Engineering" and is issued under the open-source
// license found at www.lloseng.com 

import com.lrazvan.common.Commons;
import com.lrazvan.server.business.api.Api;
import com.lrazvan.server.business.dto.ConsultationDTO;
import com.lrazvan.server.business.dto.DoctorDTO;
import com.lrazvan.server.business.dto.PatientDTO;
import com.lrazvan.server.business.dto.SecretaryDTO;
import com.lrazvan.server.data.entity.Patient;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.List;

/**
 * This class overrides some of the methods in the abstract
 * superclass in order to give more functionality to the server.
 *
 * @author Dr Timothy C. Lethbridge
 * @author Dr Robert Laganière
 * @author François Bélanger
 * @author Paul Holden
 * @version July 2000
 */
@Service
public class ApplicationServer extends AbstractServer {
    //Class variables *************************************************

    /**
     * The default port to listen on.
     */

    @Autowired
    private Api api;

    //Constructors ****************************************************

    public ApplicationServer() {
        super(Commons.DEFAULT_PORT);
    }

    /**
     * Constructs an instance of the echo server.
     *
     * @param port The port number to connect on.
     */
    public ApplicationServer(int port) {
        super(port);
    }

    //Instance methods ************************************************

    /**
     * This method handles any messages received from the client.
     *
     * @param msg    The message received from the client.
     * @param client The connection from which the message originated.
     */
    public void handleMessageFromClient(Object msg, ConnectionToClient client) {
        JSONObject jsonObject = new JSONObject((String) msg);
        String subject = jsonObject.getString("Subject");
        System.out.println("Message received: " + subject + " from " + client);

        JSONObject response;

        switch (subject) {
        case "GetAllPatients":
            List<PatientDTO> patientDTOList = api.findAllPatients();
            response = new JSONObject();
            response.put("Subject", "PatientList");
            response.put("Body", patientDTOList);
            try {
                client.sendToClient(response.toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
            break;
        case "GetPatientConsultations":
            PatientDTO patientDTO = Commons.jsonObjectToPatientDTO(jsonObject.getJSONObject("patientDTO"));
            List<ConsultationDTO> consultationDTOList = api.getPatientConsultations(patientDTO);
            response = new JSONObject();
            response.put("Subject", "PatientConsultationList");
            response.put("ConsultationList", consultationDTOList);
            try {
                client.sendToClient(response.toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
            break;
        case "GetScheduledConsultations":
            String doctorUsername = jsonObject.getString("doctorUsername");
            consultationDTOList = api.getScheduledConsultations(doctorUsername);
            response = new JSONObject();
            response.put("Subject", "PatientConsultationList");
            response.put("ConsultationList", consultationDTOList);
            try {
                client.sendToClient(response.toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
            break;
        case "GetDoctorPatients":
            doctorUsername = jsonObject.getString("doctorUsername");
            patientDTOList = api.getDoctorPatients(doctorUsername);
            response = new JSONObject();
            response.put("Subject", "DoctorPatientList");
            response.put("patientList", patientDTOList);
            try {
                client.sendToClient(response.toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
            break;
        case "GetAllSecretaries":
            List<SecretaryDTO> secretaryDTOList = api.getAllSecretaries();
            response = new JSONObject();
            response.put("Subject", "SecretaryList");
            response.put("SecretaryList", secretaryDTOList);
            try {
                client.sendToClient(response.toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
            break;
        case "GetAllDoctors":
            List<DoctorDTO> doctorDTOList = api.getAllDoctors();
            response = new JSONObject();
            response.put("Subject", "DoctorList");
            response.put("DoctorList", doctorDTOList);
            try {
                client.sendToClient(response.toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
            break;
        case "GetAvailableDoctors":
            Timestamp date = Timestamp.valueOf(jsonObject.getString("date"));
            doctorDTOList = api.getAvailableDoctors(date);
            response = new JSONObject();
            response.put("Subject", "AvailableDoctors");
            response.put("DoctorList", doctorDTOList);
            try {
                client.sendToClient(response.toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
            break;
        case "SaveConsultation":
            ConsultationDTO consultationDTO = Commons
                    .jsonObjectToConsultationDTO(jsonObject.getJSONObject("consultationDTO"));
            api.saveConsultation(consultationDTO);
            break;
        case "SavePatient":
            patientDTO = Commons.jsonObjectToPatientDTO(jsonObject.getJSONObject("patientDTO"));
            api.savePatientDTO(patientDTO);
            break;
        case "SaveSecretary":
            SecretaryDTO secretaryDTO = Commons.jsonObjectToSecretaryDTO(jsonObject.getJSONObject("secretaryDTO"));
            api.saveSecretaryDTO(secretaryDTO);
            break;
        case "DeleteSecretary":
            secretaryDTO = Commons.jsonObjectToSecretaryDTO(jsonObject.getJSONObject("secretaryDTO"));
            api.deleteSecretaryDTO(secretaryDTO);
            break;
        case "DeleteConsultation":
            consultationDTO = Commons.jsonObjectToConsultationDTO(jsonObject.getJSONObject("consultationDTO"));
            api.deleteConsultation(consultationDTO);
            break;
        case "SaveDoctor":
            DoctorDTO doctorDTO = Commons.jsonObjectToDoctorDTO(jsonObject.getJSONObject("doctorDTO"));
            api.saveDoctorDTO(doctorDTO);
            break;
        case "DeleteDoctor":
            doctorDTO = Commons.jsonObjectToDoctorDTO(jsonObject.getJSONObject("doctorDTO"));
            api.deleteDoctorDTO(doctorDTO);
            break;
        case "Authenticate":
            String role = jsonObject.getString("role");
            String username = jsonObject.getString("username");
            String password = jsonObject.getString("password");
            Boolean authenticated = false;

            switch (role) {
            case Commons.SECRETARY_ROLE:
                authenticated = api.authenticateSecretary(username, password);
                break;
            case Commons.DOCTOR_ROLE:
                authenticated = api.authenticateDoctor(username, password);
                break;
            case Commons.ADMIN_ROLE:
                authenticated = api.authenticateAdmin(username, password);
                break;
            }

            response = new JSONObject();
            response.put("Subject", "Authenticate Result");
            response.put("result", authenticated.toString());
            response.put("username", username);
            response.put("role", role);
            try {
                client.sendToClient(response.toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
            break;
        default:
            System.out.println("Unknown command: " + subject);
        }

        //this.sendToAllClients(msg);
    }

    /**
     * This method overrides the one in the superclass.  Called
     * when the server starts listening for connections.
     */
    protected void serverStarted() {
        System.out.println("Server listening for connections on port " + getPort());
    }

    /**
     * This method overrides the one in the superclass.  Called
     * when the server stops listening for connections.
     */
    protected void serverStopped() {
        System.out.println("Server has stopped listening for connections.");
    }

    protected void clientConnected(ConnectionToClient client) {
        System.out.println("The client: " + client + " has connected! ");
    }

    synchronized protected void clientDisconnected(ConnectionToClient client) {
        System.out.println("The client: " + client + " has disconnected! ");
    }

    synchronized protected void clientException(ConnectionToClient client, Throwable exception) {
        System.out
                .println("The client: " + client + " has terminated with the exception: " + exception.getMessage());
        exception.printStackTrace();
    }
    //Class methods ***************************************************

    /**
     * This method is responsible for the creation of
     * the server instance (there is no UI in this phase).
     *
     * @ arg0  The port number to listen on.  Defaults to 5555
     * if no argument is entered.
     */
    public static void main(String[] args) {
        int port = 0; //Port to listen on

        try {
            port = Integer.parseInt(args[0]); //Get port from command line
        } catch (Throwable t) {
            port = Commons.DEFAULT_PORT; //Set port to 5555
        }

        ApplicationServer sv = new ApplicationServer(port);

        try {
            sv.listen(); //Start listening for connections
        } catch (Exception ex) {
            System.out.println("ERROR - Could not listen for clients!");
        }
    }
}
//End of ApplicationServer class