Java tutorial
/* * * Copyright 2014 Jules White * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.d53.syman.web.controller; import com.google.common.collect.Lists; import net.d53.syman.web.auth.APIAuthenticationToken; import net.d53.syman.web.client.PatientServiceApi; import net.d53.syman.web.model.*; import net.d53.syman.web.repository.PatientRepository; import net.d53.syman.web.repository.PhysicianRepository; import org.apache.commons.lang3.builder.ToStringBuilder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.handler.annotation.SendTo; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.context.SecurityContextRepository; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.security.Principal; import java.util.Collection; import java.util.List; import java.util.Set; import org.apache.log4j.Logger; @Controller public class PatientController { private static final Logger LOGGER = Logger.getLogger(PatientController.class); /** * You will need to create one or more Spring controllers to fulfill the * requirements of the assignment. If you use this file, please rename it * to something other than "AnEmptyController" * <p> * <p> * ________ ________ ________ ________ ___ ___ ___ ________ ___ __ * |\ ____\|\ __ \|\ __ \|\ ___ \ |\ \ |\ \|\ \|\ ____\|\ \|\ \ * \ \ \___|\ \ \|\ \ \ \|\ \ \ \_|\ \ \ \ \ \ \ \\\ \ \ \___|\ \ \/ /|_ * \ \ \ __\ \ \\\ \ \ \\\ \ \ \ \\ \ \ \ \ \ \ \\\ \ \ \ \ \ ___ \ * \ \ \|\ \ \ \\\ \ \ \\\ \ \ \_\\ \ \ \ \____\ \ \\\ \ \ \____\ \ \\ \ \ * \ \_______\ \_______\ \_______\ \_______\ \ \_______\ \_______\ \_______\ \__\\ \__\ * \|_______|\|_______|\|_______|\|_______| \|_______|\|_______|\|_______|\|__| \|__| */ // The patientRepository that we are going to store our Patients // in. We don't explicitly construct a patientRepository, but // instead mark this object as a dependency that needs to be // injected by Spring. Our Application class has a method // annotated with @Bean that determines what object will end // up being injected into this member variable. // // Also notice that we don't even need a setter for Spring to // do the injection. // @Autowired private PhysicianRepository physicianRepository; @Autowired private PatientRepository patientRepository; @Autowired private AuthenticationManager authenticationManager; @Autowired private SecurityContextRepository securityContextRepository; @PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_DBA')") @RequestMapping(value = PatientServiceApi.PATIENT_SERVICE_PATH, method = RequestMethod.POST) public @ResponseBody Patient savePatient(@RequestBody Patient patient) { patientRepository.save(patient); return patient; } @RequestMapping(value = PatientServiceApi.PATIENT_SERVICE_PATH + "/{id}", method = RequestMethod.GET) public @ResponseBody Patient getPatient(@PathVariable("id") Long id, HttpServletResponse response) { LOGGER.info("Getting patient with id " + id); Patient p = patientRepository.findOne(id); if (p != null) { return p; } else { response.setStatus(HttpStatus.NOT_FOUND.value()); return null; } } // Receives GET requests to /Patient and returns the current // list of Patients in memory. Spring automatically converts // the list of Patients to JSON because of the @ResponseBody // annotation. @RequestMapping(value = PatientServiceApi.PATIENT_SERVICE_PATH, method = RequestMethod.GET) public @ResponseBody Collection<Patient> getPatientList() { return Lists.newArrayList(patientRepository.findAll()); } @RequestMapping(value = PatientServiceApi.PATIENT_SERVICE_PATH + "/doctor/{docId}", method = RequestMethod.GET) public @ResponseBody Collection<Patient> getPatientListForDoctor(@PathVariable("docId") Long id, HttpServletResponse response) { Physician p = physicianRepository.findOne(id); if (p != null) { Collection<Patient> ps = p.getPatients(); return ps; } else { response.setStatus(HttpStatus.NOT_FOUND.value()); return null; } } // Receives GET requests to /Patient/find and returns all Patients // that have a title (e.g., Patient.name) matching the "title" request // parameter value that is passed by the client @RequestMapping(value = PatientServiceApi.PATIENT_SSN_SEARCH_PATH, method = RequestMethod.GET) public @ResponseBody Collection<Patient> findByTitle(@RequestParam(PatientServiceApi.SSN_PARAM) String ssn) { return patientRepository.findBySsn(ssn); } // // Receives GET requests to /Patient/find and returns all Patients // // that have a title (e.g., Patient.name) matching the "title" request // // parameter value that is passed by the client // @RequestMapping(value=PatientServiceApi.Patient_DURATION_SEARCH_PATH, method=RequestMethod.GET) // public @ResponseBody Collection<Patient> findByDurationLessThan(@RequestParam(PatientServiceApi.DURATION_PARAMETER) long duration){ // return patientRepository.findByDurationLessThan(duration); // } @RequestMapping(value = PatientServiceApi.PATIENT_SERVICE_PATH + "/{id}/checkin", method = RequestMethod.POST) @PreAuthorize("hasFunction(ROLE_PHYSICIAN)") public @ResponseBody void likePatient(@PathVariable("id") Long id, @RequestBody CheckIn checkIn, HttpServletResponse response) { Patient patient = patientRepository.findOne(id); if (patient != null) { patient.getCheckInList().add(checkIn); } else { response.setStatus(HttpStatus.NOT_FOUND.value()); } } @RequestMapping(value = "/api/patient/{id}/prescription", method = RequestMethod.GET) public @ResponseBody Set<CheckInPrescription> getPrescriptionsForPatient(@PathVariable Long id, HttpServletResponse response) { LOGGER.info("Getting patient with id " + id); Patient patient = patientRepository.findOne(id); if (patient != null) { return patient.getPrescriptions(); } else { response.setStatus(HttpStatus.NOT_FOUND.value()); return null; } } @PreAuthorize("hasRole('ROLE_PATIENT')") @RequestMapping(value = "/api/patient/{id}/question", method = RequestMethod.GET) public @ResponseBody Set<CheckInQuestion> getQuestionsForPatient(@PathVariable Long id, HttpServletResponse response) { LOGGER.info("Getting patient with id " + id); Patient patient = patientRepository.findOne(id); if (patient != null) { return patient.getQuestions(); } else { response.setStatus(HttpStatus.NOT_FOUND.value()); return null; } } @PreAuthorize("hasRole('ROLE_PATIENT') or hasRole('ROLE_PHYSICIAN') ") @RequestMapping(value = "/api/patient/{id}/checkin", method = RequestMethod.POST) public @ResponseBody Model postCheckIn(@RequestBody Long id, @RequestBody CheckIn checkIn, HttpServletResponse response) { LOGGER.info("Getting patient with id " + id); Patient patient = patientRepository.findOne(id); if (patient != null) { patient.getCheckInList().add(checkIn); return null; } else { response.setStatus(HttpStatus.NOT_FOUND.value()); return null; } } @PreAuthorize("hasRole('ROLE_PATIENT')") @RequestMapping(value = "/api/patient/{id}/checkin", method = RequestMethod.GET) public @ResponseBody Collection<CheckIn> getCheckIns(@PathVariable Long id, HttpServletResponse response) { LOGGER.info("Getting patient with id " + id); Patient patient = patientRepository.findOne(id); if (patient != null) { return patient.getCheckInList(); } else { response.setStatus(HttpStatus.NOT_FOUND.value()); return null; } } @PreAuthorize("hasRole('ROLE_PATIENT')") @MessageMapping("/api/push/") @SendTo("/topic/greetings") List<CheckInPrescription> getPrescriptionUpdateOverWebsocket(@RequestBody Long id, @RequestBody CheckIn checkIn, HttpServletResponse response) { LOGGER.info("Getting patient with id " + id); Patient patient = patientRepository.findOne(id); if (patient != null) { patient.getCheckInList().add(checkIn); return null; } else { response.setStatus(HttpStatus.NOT_FOUND.value()); return null; } } @RequestMapping(value = "/api/patient", method = RequestMethod.GET) public @ResponseBody Patient getOwnData(Principal p) { Patient patient = patientRepository.findByUsername(p.getName()); return patient; } @RequestMapping(value = "/api/auth", method = RequestMethod.POST) @ResponseBody public String APIauthenticate(@RequestParam String username, @RequestParam String password, HttpServletRequest request, HttpServletResponse response) { String token = null; UsernamePasswordAuthenticationToken authenticationRequest = new UsernamePasswordAuthenticationToken( username, password); authenticationRequest.setDetails(APIAuthenticationToken.API_TOKEN_IDENTIFIER); try { APIAuthenticationToken res = (APIAuthenticationToken) authenticationManager .authenticate(authenticationRequest); LOGGER.info(ToStringBuilder.reflectionToString(res)); if (res != null) { token = res.getCredentials().toString(); LOGGER.info("Generated token " + token); SecurityContext context = SecurityContextHolder.getContext(); context.setAuthentication(res); this.securityContextRepository.saveContext(context, request, response); } else { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); } } catch (AuthenticationException e) { LOGGER.info("Authentication error: " + e.getMessage()); SecurityContextHolder.clearContext(); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); } return token; } // @RequestMapping(value=PatientServiceApi.Patient_SVC_PATH + "/{id}/unlike", method=RequestMethod.POST) // public @ResponseBody void unlikePatient(@PathVariable("id") Long id, Principal principal, HttpServletResponse response){ // Patient Patient = patientRepository.findOne(id); // if(Patient != null){ // Set<String> usersLikeThisPatient = Patient.getUsersLikePatient(); // if(usersLikeThisPatient.contains(principal.getName())){ // usersLikeThisPatient.remove(principal.getName()); // response.setStatus(HttpStatus.OK.value()); // patientRepository.save(Patient); // } else { // response.setStatus(HttpStatus.BAD_REQUEST.value()); // } // } else { // response.setStatus(HttpStatus.NOT_FOUND.value()); // } // } // // @RequestMapping(value=PatientServiceApi.Patient_SVC_PATH+"/{id}/likedby", method=RequestMethod.GET) // public @ResponseBody Collection<String> getLikedBy(@PathVariable("id") Long id, HttpServletResponse response){ // Patient Patient = patientRepository.findOne(id); // if(Patient != null){ // return Patient.getUsersLikePatient(); // } else { // response.setStatus(HttpStatus.NOT_FOUND.value()); // return null; // } // } }