Skip to content
Snippets Groups Projects
Commit 65cb8511 authored by Jonáš Jelínek's avatar Jonáš Jelínek
Browse files

isolate account service (MS1) and class service (MS2)

parent 7931131c
No related branches found
No related tags found
No related merge requests found
Showing
with 213 additions and 714 deletions
......@@ -21,6 +21,12 @@
</properties>
<dependencies>
<!-- new-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- Web application -->
<!-- Will pull in web-related dependencies, including Jackson for JSON -->
<dependency>
......
......@@ -5,6 +5,7 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.client.RestTemplate;
@Configuration
public class AppConfig {
......@@ -13,5 +14,10 @@ public class AppConfig {
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
package ear.kos2.dao;
import ear.kos2.model.Location;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;
@Repository
public class LocationDao extends BaseDao<Location>{
protected LocationDao() {
super(Location.class);
}
public List<Location> findAllbyStreet(String street){
List<Location>result = new ArrayList<>();
for (Location c : this.findAll()) {
if(c.getStreet().equals(street)){
result.add(c);
}
}
if(result.isEmpty()){
throw new IllegalArgumentException("No locations exist on that street");
}
return result;
}
}
//package ear.kos2.dao;
//
//import ear.kos2.model.Location;
//import org.springframework.stereotype.Repository;
//
//import java.util.ArrayList;
//import java.util.List;
//
//@Repository
//public class LocationDao extends BaseDao<Location>{
// protected LocationDao() {
// super(Location.class);
// }
//
// public List<Location> findAllbyStreet(String street){
// List<Location>result = new ArrayList<>();
// for (Location c : this.findAll()) {
// if(c.getStreet().equals(street)){
// result.add(c);
// }
// }
// if(result.isEmpty()){
// throw new IllegalArgumentException("No locations exist on that street");
// }
// return result;
// }
//}
package ear.kos2.dao;
import ear.kos2.model.SClass;
import org.springframework.stereotype.Repository;
@Repository
public class SClassDao extends BaseDao<SClass>{
protected SClassDao() {
super(SClass.class);
}
}
//package ear.kos2.dao;
//
//import ear.kos2.model.SClass;
//import org.springframework.stereotype.Repository;
//
//@Repository
//public class SClassDao extends BaseDao<SClass>{
//
// protected SClassDao() {
// super(SClass.class);
// }
//}
package ear.kos2.dao;
import ear.kos2.model.Schedule;
import org.springframework.stereotype.Repository;
@Repository
public class ScheduleDao extends BaseDao<Schedule>{
protected ScheduleDao() {
super(Schedule.class);
}
}
//package ear.kos2.dao;
//
//import ear.kos2.model.Schedule;
//import org.springframework.stereotype.Repository;
//
//@Repository
//public class ScheduleDao extends BaseDao<Schedule>{
// protected ScheduleDao() {
// super(Schedule.class);
// }
//
//}
......@@ -15,7 +15,7 @@ public class TeacherAccountDao extends BaseDao<TeacherAccount>{
public List<Object[]> findAllObjects() {
try {
return em.createQuery("SELECT username, password FROM "
return em.createQuery("SELECT username, password, firstName, lastName FROM "
+ type.getSimpleName() + " e", Object[].class).getResultList();
} catch (RuntimeException e) {
throw new PersistenceException(e);
......
......@@ -24,9 +24,13 @@ public abstract class Account extends AbstractEntity {
@Basic
@Column(name = "last_name", nullable = false, length = 20)
protected String lastName;
@OneToOne(mappedBy = "owner")
@JoinTable(name = "schedule", joinColumns = @JoinColumn(name = "id"))
protected Schedule schedule;
// @OneToOne(mappedBy = "owner")
// @JoinTable(name = "schedule", joinColumns = @JoinColumn(name = "id"))
// protected Schedule schedule;
@Basic
@Column(name = "scheduleId", nullable = true, length = 20)
protected Integer scheduleId;
protected Boolean online;
protected Role role;
......@@ -39,8 +43,11 @@ public abstract class Account extends AbstractEntity {
return null;
}
public Schedule getSchedule() {
return this.schedule;
// public Schedule getSchedule() {
// return this.schedule;
// }
public Integer getSchedule() {
return this.scheduleId;
}
public void setOnline(boolean online) {
......
......@@ -23,9 +23,13 @@ public class Course extends AbstractEntity {
@ManyToMany
@JoinTable(name = "student_course", joinColumns = @JoinColumn(name = "id_course"), inverseJoinColumns = @JoinColumn(name = "id_student"))
private List<StudentAccount> students;
@OneToMany
@JoinTable(name = "class", joinColumns = @JoinColumn(name = "id"))
private List<SClass> classes;
// @OneToMany
// @JoinTable(name = "class", joinColumns = @JoinColumn(name = "id"))
// private List<SClass> classes;
@Basic
@Column(name = "class_ids", nullable = true)
private List<Integer> classIds;
public String getName() {
return name;
......@@ -58,7 +62,6 @@ public class Course extends AbstractEntity {
public void setTeachers(List<TeacherAccount> teachers) {
this.teachers = teachers;
}
public List<StudentAccount> getStudents() {
return students;
}
......@@ -67,17 +70,23 @@ public class Course extends AbstractEntity {
this.students = students;
}
public List<SClass> getClasses() {
return new ArrayList<>();
// public List<SClass> getClasses() {
// return new ArrayList<>();
// }
public List<Integer> getClasses() {
return classIds;
}
public void setClasses(List<SClass> classes) {
this.classes = classes;
// public void setClasses(List<SClass> classes) {
// this.classes = classes;
// }
public void setClasses(List<Integer> classes) {
this.classIds = classes;
}
@Override
public String toString(){
return "Course{ " + "name=" + name + ", credits=" + credits + ", capacity=" + capacity
+ ", teachers=" + teachers + ", classes=" + classes + "}";
+ ", teachers=" + teachers + ", classes=" + classIds + "}";
}
}
package ear.kos2.model;
import jakarta.persistence.*;
@Entity
@Table(name = "location", uniqueConstraints = {@UniqueConstraint(columnNames = {"street", "building", "room"})})
public class Location extends AbstractEntity {
@Basic
@Column(name = "street", nullable = false, length = 20)
private String street;
@Basic
@Column(name = "building", nullable = false, length = 20)
private String building;
@Basic
@Column(name = "room", nullable = false, length = 20)
private String room;
public void update(String street, String building, String room) {
if (street != null) {
this.street = street;
}
if (building != null) {
this.building = building;
}
if (room != null) {
this.room = room;
}
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getBuilding() {
return building;
}
public void setBuilding(String building) {
this.building = building;
}
public String getRoom() {
return room;
}
public void setRoom(String room) {
this.room = room;
}
@Override
public String toString(){
return "Location{ " + "street=" + street + ", building=" + building + ", room=" + room + "}";
}
}
package ear.kos2.model;
import jakarta.persistence.*;
import java.time.LocalTime;
import java.util.List;
@Entity
@Table(name = "class")
@SecondaryTable(name = "class_schedule")
public class SClass extends AbstractEntity {
// @Enumerated
// @Column(table = "class_schedule", name = "day", nullable = false)
// public Day day;
// @Basic
// @Column(table = "class_schedule", name = "start", nullable = false)
// public LocalTime start;
// @Basic
// @Column(table = "class_schedule", name = "end", nullable = false)
// public LocalTime end;
@Basic
@Column(name = "number", nullable = false, length = 20)
private String number;
@Enumerated
@Column(name = "type", nullable = false)
private ClassType type;
@Basic
@Column(name = "capacity", nullable = false)
private Integer capacity;
@ManyToOne
@JoinColumn(name = "course")
private Course course;
@ManyToMany
@JoinTable(name = "teacher_class", joinColumns = @JoinColumn(name = "id_class"), inverseJoinColumns = @JoinColumn(name = "id_teacher"))
private List<TeacherAccount> teachers;
@ManyToOne
@JoinColumn(name = "location")
private Location location;
public void addTeacher(TeacherAccount teacherAccount){
this.teachers.add(teacherAccount);
}
public SClass(){
}
public void setTime(Day day, LocalTime start, LocalTime end) {
// this.day = day;
// this.start = start;
// this.end = end;
}
/**
* enum for assigning lecture or exercise to a certain class <br>
* code == 0 if LECTURE <br>
* code == 1 if EXERCISE
*/
private enum ClassType{
LECTURE (0),
EXERXCISE (1);
private final int code;
ClassType(int i) {
this.code = i;
}
}
@Override
public String toString(){
return "Class{ " + "number=" + number + ", type=" + type + ", capacity=" + capacity
+ ", course=" + course + ", location=" + location + "}";
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public ClassType getType() {
return type;
}
public void setType(ClassType type) {
this.type = type;
}
public Integer getCapacity() {
return capacity;
}
public void setCapacity(Integer capacity) {
this.capacity = capacity;
}
public Course getCourse() {
return course;
}
public void setCourse(Course course) {
this.course = course;
}
public List<TeacherAccount> getTeachers() {
return teachers;
}
public void setTeachers(List<TeacherAccount> teachers) {
this.teachers = teachers;
}
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
}
package ear.kos2.model;
import jakarta.persistence.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@Entity
@Table(name = "schedule")
public class Schedule extends AbstractEntity {
@OneToOne
@JoinColumn(name = "account", nullable = true)
private Account owner;
@Basic
@Column(name = "semester", nullable = false, length = 20)
private String semester;
@ManyToMany
@JoinTable(name = "class_schedule",
joinColumns = @JoinColumn(name = "id_schedule"),
inverseJoinColumns = @JoinColumn(name = "id_class")
)
private List<SClass> classes;
public Schedule() {}
public Schedule(Account owner) {
this.owner = owner;
}
public void addClass(SClass c) {
this.classes.add(c);
}
public void removeClass(SClass c) {
classes.remove(c);
}
public List<SClass> getClasses() {
return this.classes;
}
public void add(SClass sclass) {
Objects.requireNonNull(sclass);
if (classes == null) {
classes = new ArrayList<>();
}
if (!classes.contains(sclass)) {
classes.add(sclass);
}
}
@Override
public String toString(){
return "Schedule{ " + "owner=" + owner + ", semester=" + semester + ", classes=" + classes + "}";
}
public Account getOwner() {
return owner;
}
public void setOwner(Account owner) {
this.owner = owner;
}
public String getSemester() {
return semester;
}
public void setSemester(String semester) {
this.semester = semester;
}
public void setClasses(List<SClass> classes) {
this.classes = classes;
}
}
......@@ -57,10 +57,12 @@ public class StudentAccount extends Account {
//
// schedule.get(i).add(sclass);
// }
public void addToSchedule(SClass sclass, int i){
Objects.requireNonNull(sclass);
schedule.add(sclass);
}
//todo replace with call to schedule service with class id
// public void addToSchedule(SClass sclass, int i){
// Objects.requireNonNull(sclass);
// schedule.add(sclass);
// }
@Override
public String toString(){
......
......@@ -11,15 +11,25 @@ public class TeacherAccount extends Account {
@Basic
@Column(name = "title", length = 20)
private String title;
@ManyToOne
@JoinColumn(name = "location")
private Location location;
// @ManyToOne
// @JoinColumn(name = "location")
// private Location location;
@Basic
@Column(name = "locationId", length = 20, nullable = true)
private Integer locationId;
@ManyToMany
@JoinTable(name = "teacher_course", joinColumns = @JoinColumn(name = "id_teacher"), inverseJoinColumns = @JoinColumn(name = "id_course"))
private List<Course> courses;
@ManyToMany
@JoinTable(name = "teacher_class", joinColumns = @JoinColumn(name = "id_teacher"), inverseJoinColumns = @JoinColumn(name = "id_class"))
private List<SClass> classes;
// @ManyToMany
// @JoinTable(name = "teacher_class", joinColumns = @JoinColumn(name = "id_teacher"), inverseJoinColumns = @JoinColumn(name = "id_class"))
// private List<SClass> classes;
@Basic
@Column(name = "class_ids", nullable = true)
private List<Integer> classIds;
public List<Course> getCourses() {
return courses;
......@@ -28,19 +38,18 @@ public class TeacherAccount extends Account {
public TeacherAccount(){
}
public void ChangeLocation(String street, String building, String room){
this.location.update(street, building, room);
}
@Override
public String toString(){
return "Student{ " + "name=" + getFirstName() + " " + getLastName() + ", title=" + title + ", location=" + location
return "Student{ " + "name=" + getFirstName() + " " + getLastName() + ", title=" + title + ", location=" + locationId
+ ", courses=" + courses + "}";
}
public void setLocation(Location location) {
this.location = location;
}
// public void setLocation(Location location) {
// this.location = location;
// }
public void setLocation(Integer location) {
this.locationId = location;
}
public String getTitle() {
return title;
}
......@@ -49,19 +58,28 @@ public class TeacherAccount extends Account {
this.title = title;
}
public Location getLocation() {
return location;
}
// public Location getLocation() {
// return location;
// }
public Integer getLocation() {
return locationId;
}
public void setCourses(List<Course> courses) {
this.courses = courses;
}
public List<SClass> getClasses() {
return classes;
}
// public List<SClass> getClasses() {
// return classes;
// }
public List<Integer> getClasses() {
return classIds;
}
public void setClasses(List<SClass> classes) {
this.classes = classes;
// public void setClasses(List<SClass> classes) {
// this.classes = classes;
// }
public void setClasses(List<Integer> classes) {
this.classIds = classes;
}
}
......@@ -21,8 +21,8 @@ import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/rest/account")
@PreAuthorize("hasAnyRole('ROLE_TEACHER')")
@RequestMapping("/account")
//@PreAuthorize("hasAnyRole('ROLE_TEACHER')")
//@PreAuthorize("permitAll()")
public class AccountController {
private static final Logger LOG = LoggerFactory.getLogger(AccountController.class);
......@@ -43,7 +43,7 @@ public class AccountController {
return accountService.findAllObjects();
}
@PreAuthorize("hasAnyRole('ROLE_TEACHER', 'ROLE_STUDENT')")
//@PreAuthorize("hasAnyRole('ROLE_TEACHER', 'ROLE_STUDENT')")
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, value = "/logout")
public ResponseEntity<Void> logout() {
try {
......@@ -58,7 +58,7 @@ public class AccountController {
}
}
@PreAuthorize("hasAnyRole('ROLE_TEACHER', 'ROLE_STUDENT', 'ROLE_GUEST')")
//@PreAuthorize("hasAnyRole('ROLE_TEACHER', 'ROLE_STUDENT', 'ROLE_GUEST')")
@GetMapping(value = "/current", produces = MediaType.APPLICATION_JSON_VALUE)
public String getCurrent(Authentication auth) {
assert auth.getPrincipal() instanceof UserDetails;
......
......@@ -3,7 +3,6 @@ package ear.kos2.rest;
import ear.kos2.exception.NotFoundException;
import ear.kos2.exception.ValidationException;
import ear.kos2.model.Course;
import ear.kos2.model.SClass;
import ear.kos2.model.StudentAccount;
import ear.kos2.rest.util.RestUtils;
import ear.kos2.service.CourseService;
......@@ -21,8 +20,8 @@ import java.util.List;
@RestController
@RequestMapping("/rest/courses")
@PreAuthorize("permitAll()")
@RequestMapping("/courses")
//@PreAuthorize("permitAll()")
public class CourseController {
private static final Logger LOG = LoggerFactory.getLogger(CourseController.class);
......@@ -38,7 +37,7 @@ public class CourseController {
return courseService.findAll();
}
@PreAuthorize("hasRole('ROLE_TEACHER')")
//@PreAuthorize("hasRole('ROLE_TEACHER')")
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Void> createCourse(@RequestBody Course course) {
courseService.persist(course);
......@@ -65,7 +64,7 @@ public class CourseController {
return p;
}
@PreAuthorize("hasRole('ROLE_TEACHER')")
//@PreAuthorize("hasRole('ROLE_TEACHER')")
@PutMapping(value = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.NO_CONTENT)
public void updateCourse(@PathVariable Integer id, @RequestBody Course course) {
......@@ -77,7 +76,7 @@ public class CourseController {
LOG.debug("Updated course {}.", course);
}
@PreAuthorize("hasRole('ROLE_TEACHER')")
//@PreAuthorize("hasRole('ROLE_TEACHER')")
@DeleteMapping(value = "/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void removeCourse(@PathVariable Integer id) {
......@@ -90,12 +89,12 @@ public class CourseController {
}
@GetMapping(value = "/{id}/classes", produces = MediaType.APPLICATION_JSON_VALUE)
public List<SClass> getClassesByCourseId(@PathVariable Integer id) {
public List<Integer> getClassesByCourseId(@PathVariable Integer id) {
final Course c = getCourse(id);
return courseService.getAllClasses(c);
}
@PreAuthorize("hasRole('ROLE_TEACHER')")
//@PreAuthorize("hasRole('ROLE_TEACHER')")
@GetMapping(value = "/{id}/students", produces = MediaType.APPLICATION_JSON_VALUE)
public List<StudentAccount> getStudentsByCourseId(@PathVariable Integer id) {
final Course c = getCourse(id);
......
package ear.kos2.rest;
import ear.kos2.exception.NotFoundException;
import ear.kos2.exception.ValidationException;
import ear.kos2.model.Location;
import ear.kos2.rest.util.RestUtils;
import ear.kos2.service.LocationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/rest/location")
@PreAuthorize("hasAnyRole('ROLE_TEACHER')")
public class LocationController {
private static final Logger LOG = LoggerFactory.getLogger(LocationController.class);
private final LocationService locationService;
@Autowired
public LocationController(LocationService locationService) {
this.locationService = locationService;
}
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public List<Location> getLocations() {
return locationService.findAll();
}
@PreAuthorize("hasRole('ROLE_TEACHER')")
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Void> createLocation(@RequestBody Location location) {
locationService.persist(location);
LOG.debug("Created location {}.", location);
final HttpHeaders headers = RestUtils.createLocationHeaderFromCurrentUri("/{id}", location.getId());
return new ResponseEntity<>(headers, HttpStatus.CREATED);
}
@GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public Location getLocation(@PathVariable Integer id) {
final Location p = locationService.find(id);
if (p == null) {
throw NotFoundException.create("Location", id);
}
return p;
}
@PreAuthorize("hasRole('ROLE_TEACHER')")
@PutMapping(value = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.NO_CONTENT)
public void updateLocation(@PathVariable Integer id, @RequestBody Location location) {
final Location original = getLocation(id);
if (!original.getId().equals(id)) {
throw new ValidationException("Location identifier in the data does not match the one in the request URL.");
}
original.setBuilding(location.getBuilding());
original.setRoom(location.getRoom());
original.setStreet(location.getStreet());
locationService.update(original);
LOG.debug("Updated location {}.", location);
}
@PreAuthorize("hasRole('ROLE_TEACHER')")
@DeleteMapping(value = "/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void removeLocation(@PathVariable Integer id) {
final Location toRemove = locationService.find(id);
if (toRemove == null) {
return;
}
locationService.remove(toRemove);
LOG.debug("Removed location {}.", toRemove);
}
}
package ear.kos2.rest;
import ear.kos2.exception.NotFoundException;
import ear.kos2.exception.ValidationException;
import ear.kos2.model.Account;
import ear.kos2.model.Role;
import ear.kos2.model.SClass;
import ear.kos2.model.TeacherAccount;
import ear.kos2.rest.util.RestUtils;
import ear.kos2.security.model.UserDetails;
import ear.kos2.service.SClassService;
import ear.kos2.service.TeacherAccountService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/rest/class")
@PreAuthorize("permitAll()")
public class SClassController {
private static final Logger LOG = LoggerFactory.getLogger(SClassController.class);
private final SClassService sclassService;
private final TeacherAccountService teacherAccountService;
@Autowired
public SClassController(SClassService sclassService, TeacherAccountService teacherAccountService) {
this.sclassService = sclassService;
this.teacherAccountService = teacherAccountService;
}
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public List<SClass> getClasses() {
return sclassService.findAll();
}
@PreAuthorize("hasRole('ROLE_TEACHER')")
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Void> createSClass(@RequestBody SClass sclass) {
sclassService.persist(sclass);
LOG.debug("Created sclass {}.", sclass);
final HttpHeaders headers = RestUtils.createLocationHeaderFromCurrentUri("/{id}", sclass.getId());
return new ResponseEntity<>(headers, HttpStatus.CREATED);
}
@GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public SClass getSClass(@PathVariable Integer id) {
final SClass p = sclassService.find(id);
if (p == null) {
throw NotFoundException.create("SClass", id);
}
return p;
}
@PreAuthorize("hasRole('ROLE_TEACHER')")
@PutMapping(value = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.NO_CONTENT)
public void updateSClass(@PathVariable Integer id, @RequestBody SClass sclass) {
final SClass original = getSClass(id);
if (!original.getId().equals(sclass.getId())) {
throw new ValidationException("SClass identifier in the data does not match the one in the request URL.");
}
sclassService.update(sclass);
LOG.debug("Updated sclass {}.", sclass);
}
@PreAuthorize("hasRole('ROLE_TEACHER')")
@PostMapping(value = "/{id}/addTeacher", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Void> joinClassAsTeacher(Authentication auth, @PathVariable Integer id) {
try {
//get current user logic
assert auth.getPrincipal() instanceof UserDetails;
final Account user = ((UserDetails) auth.getPrincipal()).getUser();
//verify user is a teacher role
if(user.getRole() != Role.TEACHER){
throw new AccessDeniedException("Cannot join as a teacher if not a teacher");
}
//retrieve account
TeacherAccount current = teacherAccountService.find(user.getId());
//add teacher to a SClass logic
SClass temp = sclassService.find(id);
temp.addTeacher(current);
sclassService.update(temp);
final HttpHeaders headers = RestUtils.createLocationHeaderFromCurrentUri("/{id}", id);
return new ResponseEntity<>(headers, HttpStatus.ACCEPTED);
} catch (Exception e) {
LOG.debug("Attempted to retrieve SClass with id {}.", id);
throw new NotFoundException("Teacher account or SClass not found");
}
}
@PreAuthorize("hasRole('ROLE_TEACHER')")
@DeleteMapping(value = "/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void removeSClass(@PathVariable Integer id) {
final SClass toRemove = sclassService.find(id);
if (toRemove == null) {
return;
}
sclassService.remove(toRemove);
LOG.debug("Removed sclass {}.", toRemove);
}
}
package ear.kos2.rest;
import ear.kos2.exception.NotFoundException;
import ear.kos2.exception.ValidationException;
import ear.kos2.model.Schedule;
import ear.kos2.rest.util.RestUtils;
import ear.kos2.service.ScheduleService;
import ear.kos2.service.StudentAccountService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/rest/schedule")
@PreAuthorize("hasAnyRole('ROLE_TEACHER', 'ROLE_STUDENT', 'ROLE_GUEST')")
public class ScheduleController {
private static final Logger LOG = LoggerFactory.getLogger(CourseController.class);
private final ScheduleService scheduleService;
private final StudentAccountService studentAccountService;
@Autowired
public ScheduleController(ScheduleService scheduleService, StudentAccountService studentAccountService) {
this.scheduleService = scheduleService;
this.studentAccountService = studentAccountService;
}
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public List<Schedule> getSchedules() {
return scheduleService.findAll();
}
@PreAuthorize("hasRole('ROLE_TEACHER')")
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, path = "/create/{idd}")
public ResponseEntity<Void> createSchedule(@PathVariable Integer idd, @RequestBody Schedule schedule) {
schedule.setOwner(studentAccountService.findStudent(idd));
scheduleService.persist(schedule);
LOG.debug("Created schedule {}.", schedule);
final HttpHeaders headers = RestUtils.createLocationHeaderFromCurrentUri("/{id}", schedule.getId());
return new ResponseEntity<>(headers, HttpStatus.CREATED);
}
@PreAuthorize("hasRole('ROLE_TEACHER')")
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, path = "/create")
public ResponseEntity<Void> createSchedule(@RequestBody Schedule schedule) {
scheduleService.persist(schedule);
LOG.debug("Created schedule {}.", schedule);
final HttpHeaders headers = RestUtils.createLocationHeaderFromCurrentUri("/{id}", schedule.getId());
return new ResponseEntity<>(headers, HttpStatus.CREATED);
}
@GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public Schedule getSchedule(@PathVariable Integer id) {
final Schedule p = scheduleService.find(id);
if (p == null) {
throw NotFoundException.create("Schedule", id);
}
return p;
}
@PreAuthorize("hasRole('ROLE_TEACHER')")
@PutMapping(value = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.NO_CONTENT)
public void updateSchedule(@PathVariable Integer id, @RequestBody Schedule schedule) {
final Schedule original = getSchedule(id);
if (!original.getId().equals(schedule.getId())) {
throw new ValidationException("Schedule identifier in the data does not match the one in the request URL.");
}
scheduleService.update(schedule);
LOG.debug("Updated schedule {}.", schedule);
}
@PreAuthorize("hasRole('ROLE_TEACHER')")
@DeleteMapping(value = "/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void removeSchedule(@PathVariable Integer id) {
final Schedule toRemove = scheduleService.find(id);
if (toRemove == null) {
return;
}
scheduleService.remove(toRemove);
LOG.debug("Removed schedule {}.", toRemove);
}
}
......@@ -2,13 +2,9 @@ package ear.kos2.rest;
import ear.kos2.exception.NotFoundException;
import ear.kos2.model.Course;
import ear.kos2.model.SClass;
import ear.kos2.model.Schedule;
import ear.kos2.model.StudentAccount;
import ear.kos2.rest.util.RestUtils;
import ear.kos2.service.CourseService;
import ear.kos2.service.SClassService;
import ear.kos2.service.ScheduleService;
import ear.kos2.service.StudentAccountService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
......@@ -24,28 +20,22 @@ import java.util.List;
@RestController
@RequestMapping("/rest/student")
@PreAuthorize("permitAll()")
@RequestMapping("/student")
//@PreAuthorize("permitAll()")
public class StudentAccountController {
private static final Logger LOG = LoggerFactory.getLogger(StudentAccountController.class);
private final StudentAccountService studentAccountService;
private final CourseService courseService;
private final SClassService classService;
private final ScheduleService scheduleService;
@Autowired
public StudentAccountController(StudentAccountService studentAccountService,
CourseService courseService,
SClassService classService,
ScheduleService scheduleService)
{
this.studentAccountService = studentAccountService;
this.courseService = courseService;
this.classService = classService;
this.scheduleService = scheduleService;
}
@Autowired
public StudentAccountController(StudentAccountService studentAccountService,
CourseService courseService)
{
this.studentAccountService = studentAccountService;
this.courseService = courseService;
}
@PreAuthorize("hasRole('ROLE_TEACHER')")
//@PreAuthorize("hasRole('ROLE_TEACHER')")
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, path = "/create")
public ResponseEntity<Void> createStudent(@RequestBody StudentAccount student) {
studentAccountService.persist(student);
......@@ -67,7 +57,7 @@ public class StudentAccountController {
*
* @param user Student data
*/
@PreAuthorize("isAnonymous()")
//@PreAuthorize("isAnonymous()")
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Void> login(@RequestBody StudentAccount user) {
try {
......@@ -82,11 +72,12 @@ public class StudentAccountController {
}
}
@PreAuthorize("hasAnyRole('ROLE_TEACHER', 'ROLE_STUDENT')")
@GetMapping(value = "/{id}/schedule", produces = MediaType.APPLICATION_JSON_VALUE)
public Schedule getScheduleByUserId(@PathVariable Integer id) {
return studentAccountService.getScheduleById(id);
}
//@PreAuthorize("hasAnyRole('ROLE_TEACHER', 'ROLE_STUDENT')")
//todo replace with call to schedule service with account id
// @GetMapping(value = "/{id}/schedule", produces = MediaType.APPLICATION_JSON_VALUE)
// public Schedule getScheduleByUserId(@PathVariable Integer id) {
// return studentAccountService.getScheduleById(id);
// }
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
......@@ -94,7 +85,7 @@ public class StudentAccountController {
return studentAccountService.findAllObjects();
}
@PreAuthorize("hasAnyRole('ROLE_TEACHER', 'ROLE_STUDENT')")
//@PreAuthorize("hasAnyRole('ROLE_TEACHER', 'ROLE_STUDENT')")
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE,
value = "/{id}/join/course/{courseId}")
public ResponseEntity<Void> joinCourse(@PathVariable Integer id, @PathVariable Integer courseId) {
......@@ -146,39 +137,48 @@ public class StudentAccountController {
}
}
@PreAuthorize("hasAnyRole('ROLE_TEACHER', 'ROLE_STUDENT')")
//@PreAuthorize("hasAnyRole('ROLE_TEACHER', 'ROLE_STUDENT')")
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, value = "/{id}/join/class/{classId}")
public ResponseEntity<Void> joinClass(@PathVariable Integer id, @PathVariable Integer classId) {
SClass sclass = null;
// SClass sclass = null;
StudentAccount user = null;
try{
sclass = classService.find(classId);
//todo
//fetch class from 2nd service, via classId
//fetch course id
int courseId = 0;
int sclassId = 0;
// sclass = classService.find(classId);
user = studentAccountService.findStudent(id);
Course course = courseService.find(courseId);
//check if user has joined the corresponding course
if(!courseService.getAllStudents(sclass.getCourse()).contains(user)){
if(!courseService.getAllStudents(course).contains(user)){
LOG.debug("Cannot join a class without joining course first.");
final HttpHeaders headers = RestUtils.createLocationHeaderFromCurrentUri("/{}", user.getId());
return new ResponseEntity<>(headers, HttpStatus.FORBIDDEN);
}
Schedule tempSchedule = user.getSchedule();
List<SClass> tempClasses = tempSchedule.getClasses();
Integer tempSchedule = user.getSchedule();
List<Integer> classesFromSchedule = null;
//fetch class ids from schedule
// List<Integer> tempClasses = tempSchedule.getClasses();
//check if class is already present in schedule
if(tempClasses.contains(sclass)){
if(classesFromSchedule.contains(sclassId)){
LOG.debug("User is already in the class.");
final HttpHeaders headers = RestUtils.createLocationHeaderFromCurrentUri("/{}", user.getId());
return new ResponseEntity<>(headers, HttpStatus.FOUND);
}
tempClasses.add(sclass);
tempSchedule.setClasses(tempClasses);
classesFromSchedule.add(sclassId);
//todo replace with call to schedule service adding classes to schedule
// tempSchedule.setClasses(classesFromSchedule);
scheduleService.update(tempSchedule);
// scheduleService.update(tempSchedule);
studentAccountService.update(user);
LOG.debug("User {} successfully joined class {} in.", user, sclass);
LOG.debug("User {} successfully joined class {} in.", user, sclassId);
final HttpHeaders headers = RestUtils.createLocationHeaderFromCurrentUri("/{}", user.getId());
return new ResponseEntity<>(headers, HttpStatus.ACCEPTED);
} catch (Exception e2) {
......@@ -188,39 +188,44 @@ public class StudentAccountController {
}
}
@PreAuthorize("hasAnyRole('ROLE_TEACHER', 'ROLE_STUDENT')")
//@PreAuthorize("hasAnyRole('ROLE_TEACHER', 'ROLE_STUDENT')")
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, value = "/{id}/leave/class/{classId}")
public ResponseEntity<Void> leaveClass(@PathVariable Integer id, @PathVariable Integer classId) {
SClass sclass = null;
// SClass sclass = null;
Integer sclassId = null;
StudentAccount user = null;
try{
sclass = classService.find(classId);
//fetch course if from class service
Integer courseId = 0;
// sclass = classService.find(classId);
user = studentAccountService.findStudent(id);
Course course = courseService.find(courseId);
//check if user has joined the corresponding course
if(!courseService.getAllStudents(sclass.getCourse()).contains(user)){
if(!courseService.getAllStudents(course).contains(user)){
LOG.debug("Cannot leave a class of a course user is not in.");
final HttpHeaders headers = RestUtils.createLocationHeaderFromCurrentUri("/{}", user.getId());
return new ResponseEntity<>(headers, HttpStatus.FORBIDDEN);
}
Schedule tempSchedule = user.getSchedule();
List<SClass> tempClasses = tempSchedule.getClasses();
// Schedule tempSchedule = user.getSchedule();
// List<SClass> tempClasses = tempSchedule.getClasses();
//case where the class doesn't exist in schedule
if(!tempClasses.contains(sclass)){
LOG.debug("User is not in the class.");
final HttpHeaders headers = RestUtils.createLocationHeaderFromCurrentUri("/{}", user.getId());
return new ResponseEntity<>(headers, HttpStatus.FORBIDDEN);
}
tempClasses.remove(sclass);
tempSchedule.setClasses(tempClasses);
scheduleService.update(tempSchedule);
// if(!tempClasses.contains(sclass)){
// LOG.debug("User is not in the class.");
// final HttpHeaders headers = RestUtils.createLocationHeaderFromCurrentUri("/{}", user.getId());
// return new ResponseEntity<>(headers, HttpStatus.FORBIDDEN);
// }
// tempClasses.remove(sclass);
// tempSchedule.setClasses(tempClasses);
// scheduleService.update(tempSchedule);
studentAccountService.update(user);
LOG.debug("User {} successfully joined class {} in.", user, sclass);
LOG.debug("User {} successfully joined class {} in.", user, sclassId);
final HttpHeaders headers = RestUtils.createLocationHeaderFromCurrentUri("/{}", user.getId());
return new ResponseEntity<>(headers, HttpStatus.ACCEPTED);
} catch (Exception e2) {
......
......@@ -19,9 +19,9 @@ import java.util.List;
@RestController
@RequestMapping("/rest/teacher")
@RequestMapping("/teacher")
// PreAuthorize on class applies to all endpoints it declares
@PreAuthorize("permitAll()")
//@PreAuthorize("permitAll()")
public class TeacherAccountController {
private static final Logger LOG = LoggerFactory.getLogger(TeacherAccountController.class);
private final TeacherAccountService teacherAccountService;
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment