Merge pull request 'restrictions' (#42) from restrictions into master

Reviewed-on: http://git.plannaplan.pl/filipizydorczyk/backend/pulls/42
This commit is contained in:
Marcin Woźniak 2021-01-17 12:30:25 +01:00
commit c4ec88e691
74 changed files with 1202 additions and 238 deletions

View File

@ -0,0 +1,6 @@
/**
* Provides the classes necessary to obtain usos authentication with Oauth1
*
* @since 1.0
*/
package com.plannaplan.api;

View File

@ -18,10 +18,23 @@ public class FileReader {
private InputStream fileInputStream; private InputStream fileInputStream;
/**
* @param fileInputStream stream of stadarized file contains courses and gropups
* to import. File needs to be .xlsx file that has
* fields: zaj_cyk_id, typ, sym, nazwa, gr_nr, Mc, dzien,
* godz_od, sala, tytul, nazwisko, imie. Order doesn't
* have impact on import. Any change name of given field
* can be performed in FileToDatabaseMigrator class
*/
public FileReader(InputStream fileInputStream) { public FileReader(InputStream fileInputStream) {
this.fileInputStream = fileInputStream; this.fileInputStream = fileInputStream;
} }
/**
* read data rom file
*
* @return instance of class FileData
*/
public FileData read() { public FileData read() {
FileData result = null; FileData result = null;

View File

@ -16,7 +16,8 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
/** /**
* FileToDatabaseMigrator is used for migrate data from file (it reads line by line) and push it into database * FileToDatabaseMigrator is used for migrate data from file (it reads line by
* line) and push it into database
*/ */
@Component @Component
public class FileToDatabaseMigrator { public class FileToDatabaseMigrator {
@ -32,7 +33,7 @@ public class FileToDatabaseMigrator {
private static final String GROUP_TIME_STRING = "godz_od"; private static final String GROUP_TIME_STRING = "godz_od";
private static final String ROOM_STRING = "sala"; private static final String ROOM_STRING = "sala";
private static final String CAPACITY_STRING = "Mc"; private static final String CAPACITY_STRING = "Mc";
private static final String TYPE_GROUP= "typ"; private static final String TYPE_GROUP = "typ";
private static final String ZAJ_CYK_ID = "zaj_cyk_id"; private static final String ZAJ_CYK_ID = "zaj_cyk_id";
private static final String GR_NR = "gr_nr"; private static final String GR_NR = "gr_nr";
@ -47,6 +48,11 @@ public class FileToDatabaseMigrator {
public FileToDatabaseMigrator() { public FileToDatabaseMigrator() {
} }
/**
* insert data to database
*
* @param data FileData imported from file
*/
public void migrate(FileData data) { public void migrate(FileData data) {
Iterator<Row> rows = data.getRows(); Iterator<Row> rows = data.getRows();
int courseNameIndex = data.getIndexOf(FileToDatabaseMigrator.COURSE_NAME_STRING); int courseNameIndex = data.getIndexOf(FileToDatabaseMigrator.COURSE_NAME_STRING);
@ -71,18 +77,26 @@ public class FileToDatabaseMigrator {
String courseName = row.getCell(courseNameIndex).toString().trim(); String courseName = row.getCell(courseNameIndex).toString().trim();
String symbol = row.getCell(symbolIndex).toString().trim(); String symbol = row.getCell(symbolIndex).toString().trim();
String lecturerTitle = row.getCell(titleIndex) != null ? row.getCell(titleIndex).toString().trim() : ""; String lecturerTitle = row.getCell(titleIndex) != null
String lecturerName = row.getCell(nameIndex) != null ? row.getCell(nameIndex).toString().trim() : ""; ? row.getCell(titleIndex).toString().trim()
String lecturerSurname = row.getCell(surnameIndex) != null ? row.getCell(surnameIndex).toString().trim() : "";
String lecturerName = row.getCell(nameIndex) != null ? row.getCell(nameIndex).toString().trim()
: "";
String lecturerSurname = row.getCell(surnameIndex) != null
? row.getCell(surnameIndex).toString().trim()
: ""; : "";
Integer zajCykId = row.getCell(zajCykIdIndex) != null ? (int) Double.parseDouble(row.getCell(zajCykIdIndex).toString().trim()) Integer zajCykId = row.getCell(zajCykIdIndex) != null
? (int) Double.parseDouble(row.getCell(zajCykIdIndex).toString().trim())
: null; : null;
Integer grNr = row.getCell(grNrIndex) != null ? (int) Double.parseDouble(row.getCell(grNrIndex).toString().trim()) Integer grNr = row.getCell(grNrIndex) != null
? (int) Double.parseDouble(row.getCell(grNrIndex).toString().trim())
: null; : null;
int day = row.getCell(dayIndex) != null ? (int) Double.parseDouble(row.getCell(dayIndex).toString()) : 0; int day = row.getCell(dayIndex) != null
? (int) Double.parseDouble(row.getCell(dayIndex).toString())
: 0;
WeekDay groupDay = WeekDay.getDay(day - 1); WeekDay groupDay = WeekDay.getDay(day - 1);
int time = parseTimeToInt(row.getCell(timeIndex).toString()); int time = parseTimeToInt(row.getCell(timeIndex).toString());
String room = row.getCell(roomIndex).toString().trim(); String room = row.getCell(roomIndex).toString().trim();
@ -92,12 +106,13 @@ public class FileToDatabaseMigrator {
Course course = this.courseService.getCourseByName(courseName) Course course = this.courseService.getCourseByName(courseName)
.orElseGet(() -> this.courseService.save(new Course(courseName, symbol))); .orElseGet(() -> this.courseService.save(new Course(courseName, symbol)));
Lecturer lecturer = this.lecturerService.getLecturer(lecturerTitle, lecturerName, lecturerSurname) Lecturer lecturer = this.lecturerService
.orElseGet(() -> this.lecturerService .getLecturer(lecturerTitle, lecturerName, lecturerSurname)
.save(new Lecturer(lecturerTitle, lecturerName, lecturerSurname))); .orElseGet(() -> this.lecturerService.save(
new Lecturer(lecturerTitle, lecturerName, lecturerSurname)));
Groups group = this.groupService.find(zajCykId, grNr).orElseGet( Groups group = this.groupService.find(zajCykId, grNr).orElseGet(() -> new Groups(capacity, room,
() -> new Groups(capacity, room, course, time, groupDay, lecturer, zajCykId, grNr, typeGroup)); course, time, groupDay, lecturer, zajCykId, grNr, typeGroup));
group.update(capacity, room, course, time, null, groupDay, lecturer, typeGroup); group.update(capacity, room, course, time, null, groupDay, lecturer, typeGroup);
this.groupService.save(group); this.groupService.save(group);
@ -106,6 +121,11 @@ public class FileToDatabaseMigrator {
} }
/**
*
* @param time time string in formaT hh:mm or hh.mm
* @return int time witch is minutes from 00:00
*/
private static int parseTimeToInt(String time) { private static int parseTimeToInt(String time) {
String times[] = time.split("\\.|\\:"); String times[] = time.split("\\.|\\:");
return times.length == 2 ? Integer.parseInt(times[0]) * 60 + Integer.parseInt(times[1]) : 0; return times.length == 2 ? Integer.parseInt(times[0]) * 60 + Integer.parseInt(times[1]) : 0;

View File

@ -0,0 +1,7 @@
/**
* Provides the classes necessary to to config and import related operations in
* the app
*
* @since 1.0
*/
package com.plannaplan.configutils;

View File

@ -38,6 +38,15 @@ public class Assignment {
this.group = group; this.group = group;
} }
/**
*
* @param oldAssignment old assignment that we want to move to new commision
* @param newCommision commsion to move assiongment
*/
public static Assignment getNewFromAssignment(Assignment oldAssignment, Commision newCommision) {
return new Assignment(oldAssignment.getGroup(), newCommision);
}
/** /**
* If it returns trues it mesans u are assigned to group accepted by algorythm * If it returns trues it mesans u are assigned to group accepted by algorythm
* *
@ -49,9 +58,10 @@ public class Assignment {
/** /**
* Getter of commision * Getter of commision
*
* @return Commision Commision of given assignments * @return Commision Commision of given assignments
*/ */
public Commision getCommision(){ public Commision getCommision() {
return this.commision; return this.commision;
} }
@ -68,9 +78,13 @@ public class Assignment {
public Assignment() { public Assignment() {
} }
/**
* @param commision commision to set
*/
public void setCommision(Commision commision) { public void setCommision(Commision commision) {
this.commision = commision; this.commision = commision;
} }
/** /**
* Id getter * Id getter
* *

View File

@ -0,0 +1,6 @@
/**
* Provides all entieites that are created in database by Hibernate
*
* @since 1.0
*/
package com.plannaplan.entities;

View File

@ -1,9 +1,9 @@
package com.plannaplan.exceptions; package com.plannaplan.exceptions;
public class TokenExpiredException extends RuntimeException { /**
/** * Excepction to be thrown when provided token is expired
*
*/ */
public class TokenExpiredException extends RuntimeException {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public TokenExpiredException(String message) { public TokenExpiredException(String message) {

View File

@ -1,9 +1,9 @@
package com.plannaplan.exceptions; package com.plannaplan.exceptions;
public class UserNotFoundException extends Exception { /**
/** * Exception to be thrown when provided user does not exist in database
*
*/ */
public class UserNotFoundException extends Exception {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public UserNotFoundException(String message) { public UserNotFoundException(String message) {

View File

@ -0,0 +1,6 @@
/**
* Provides custom for our app exceptions to get more accutrate errors info
*
* @since 1.0
*/
package com.plannaplan.exceptions;

View File

@ -2,6 +2,9 @@ package com.plannaplan.models;
import java.io.InputStream; import java.io.InputStream;
/**
* Config data copntainer to keep tours dates and stream of dasta to import
*/
public class ConfigData { public class ConfigData {
private TourData firstTour; private TourData firstTour;
private TourData secondTour; private TourData secondTour;

View File

@ -4,6 +4,9 @@ import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Row;
/**
* Wrapper for data readed from file
*/
public class FileData { public class FileData {
private HashMap<String, Integer> keys; private HashMap<String, Integer> keys;
@ -13,6 +16,7 @@ public class FileData {
* FileData * FileData
* *
* @param keys this is a hashmap of String and Integer * @param keys this is a hashmap of String and Integer
*
* @param rows this is a iterator of rows. * @param rows this is a iterator of rows.
*/ */
public FileData(HashMap<String, Integer> keys, Iterator<Row> rows) { public FileData(HashMap<String, Integer> keys, Iterator<Row> rows) {
@ -31,6 +35,7 @@ public class FileData {
/* /*
* setRows * setRows
*
* @param rows set the rows to given function * @param rows set the rows to given function
*/ */
public void setRows(Iterator<Row> rows) { public void setRows(Iterator<Row> rows) {
@ -39,6 +44,7 @@ public class FileData {
/* /*
* getKeys * getKeys
*
* @return keys * @return keys
*/ */
public HashMap<String, Integer> getKeys() { public HashMap<String, Integer> getKeys() {
@ -47,6 +53,7 @@ public class FileData {
/* /*
* setKeys * setKeys
*
* @param keys set the key is being a struck of hashmap (String, Integer) * @param keys set the key is being a struck of hashmap (String, Integer)
*/ */
public void setKeys(HashMap<String, Integer> keys) { public void setKeys(HashMap<String, Integer> keys) {
@ -55,6 +62,7 @@ public class FileData {
/* /*
* getIndexOf * getIndexOf
*
* @return index * @return index
*/ */
public int getIndexOf(String key) { public int getIndexOf(String key) {

View File

@ -3,27 +3,48 @@ package com.plannaplan.models;
import com.plannaplan.entities.Assignment; import com.plannaplan.entities.Assignment;
import com.plannaplan.entities.Exchange; import com.plannaplan.entities.Exchange;
/**
* Match of users Exchange's to be performed
*/
public class MatchData { public class MatchData {
private Exchange exchangeOne; private Exchange exchangeOne;
private Exchange exchangeTwo; private Exchange exchangeTwo;
/**
* create MatchData
*
* @param exchangeOne first Exchange of found match
* @param exchangeTwo second Exchange of found match
*/
public MatchData(Exchange exchangeOne, Exchange exchangeTwo) { public MatchData(Exchange exchangeOne, Exchange exchangeTwo) {
this.exchangeOne = exchangeOne; this.exchangeOne = exchangeOne;
this.exchangeTwo = exchangeTwo; this.exchangeTwo = exchangeTwo;
} }
/**
* @return first Exchange
*/
public Exchange getExchangeOne() { public Exchange getExchangeOne() {
return this.exchangeOne; return this.exchangeOne;
} }
/**
* @return second Exchange
*/
public Exchange getExchangeTwo() { public Exchange getExchangeTwo() {
return this.exchangeTwo; return this.exchangeTwo;
} }
/**
* @return second Exchange's owned assignmetn
*/
public Assignment getAssignmentTwo() { public Assignment getAssignmentTwo() {
return this.exchangeTwo.getOwnedAssignment(); return this.exchangeTwo.getOwnedAssignment();
} }
/**
* @return first Exchange's owned assignmetn
*/
public Assignment getAssignmentOne() { public Assignment getAssignmentOne() {
return this.exchangeOne.getOwnedAssignment(); return this.exchangeOne.getOwnedAssignment();
} }
@ -36,31 +57,39 @@ public class MatchData {
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
// If the object is compared with itself then return true
if (o == this) { if (o == this) {
return true; return true;
} }
/*
* Check if o is an instance of Complex or not "null instanceof [type]" also
* returns false
*/
if (!(o instanceof MatchData)) { if (!(o instanceof MatchData)) {
return false; return false;
} }
// typecast o to Complex so that we can compare data members
MatchData c = (MatchData) o; MatchData c = (MatchData) o;
// Compare the data members and return accordingly return (this.getAssignmentOne().equals(c.getAssignmentOne())
return (this.getAssignmentOne().equals(c.getAssignmentOne()) && this.getAssignmentTwo().equals(c.getAssignmentTwo())) || (this.getAssignmentOne().equals(c.getAssignmentTwo()) && this.getAssignmentTwo().equals(c.getAssignmentOne())); && this.getAssignmentTwo().equals(c.getAssignmentTwo()))
|| (this.getAssignmentOne().equals(c.getAssignmentTwo())
&& this.getAssignmentTwo().equals(c.getAssignmentOne()));
} }
/**
* comparator for MatchData. It compare it by sum of both exchange's times. For
* example MatchData with Exchanges 11:00 and 12:00 will be less than with
* Exchanges 12:00 and 12:00
*
* @param m1 MatchData instance to compare to
* @return int less than 0 if m1 is "less than", 0 if it's equal and more than 0
* otherwise
*/
public int compare(MatchData m1) { public int compare(MatchData m1) {
return Long.compare(m1.getExchangesMsValue(), this.getExchangesMsValue()); return Long.compare(m1.getExchangesMsValue(), this.getExchangesMsValue());
} }
public long getExchangesMsValue(){ /**
* @return sum of both exchanges java.sql.Timestanp::getTime"
*/
public long getExchangesMsValue() {
return this.exchangeOne.getDataExchange().getTime() + this.exchangeTwo.getDataExchange().getTime(); return this.exchangeOne.getDataExchange().getTime() + this.exchangeTwo.getDataExchange().getTime();
} }
} }

View File

@ -2,6 +2,9 @@ package com.plannaplan.models;
import java.sql.Date; import java.sql.Date;
/**
* Container for Tours dates
*/
public class TourData { public class TourData {
private Date start; private Date start;

View File

@ -11,18 +11,36 @@ public class UserApiResponse {
public UserApiResponse() { public UserApiResponse() {
} }
/**
* @return user's Surname
*/
public String getSurname() { public String getSurname() {
return surname; return surname;
} }
/**
* setter for name. Reson to have setters for this class is for case if there
* would be name and no surname or otherwise
*
* @param surname name to set that was obtained by api request
*/
public void setSurname(String surname) { public void setSurname(String surname) {
this.surname = surname; this.surname = surname;
} }
/**
* @return user's Name
*/
public String getName() { public String getName() {
return name; return name;
} }
/**
* setter for surname. Reson to have setters for this class is for case if there
* would be name and no surname or otherwise
*
* @param name name to set that was obtained by api request
*/
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }

View File

@ -0,0 +1,6 @@
/**
* Provides readonly (mostly) classes to keep data for diffrent pourposes
*
* @since 1.0
*/
package com.plannaplan.models;

View File

@ -4,5 +4,8 @@ import com.plannaplan.entities.AppConfig;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
/**
* Repository for app config
*/
public interface AppConfigRepository extends JpaRepository<AppConfig, Long> { public interface AppConfigRepository extends JpaRepository<AppConfig, Long> {
} }

View File

@ -0,0 +1,7 @@
/**
* Provides jpa repositories interfaces to comunicate with database. These are
* used exclusively in services
*
* @since 1.0
*/
package com.plannaplan.repositories;

View File

@ -91,6 +91,7 @@ public class AssignmentService {
if (com.isPresent()) { if (com.isPresent()) {
final List<Assignment> assignments = this.getCommisionAssignments(com.get()); final List<Assignment> assignments = this.getCommisionAssignments(com.get());
assignments.forEach(a -> { assignments.forEach(a -> {
if (a.isAccepted() == false) {
final Groups group = a.getGroup(); final Groups group = a.getGroup();
if (group.getCapacity() > group.getRegisteredStudents().size()) { if (group.getCapacity() > group.getRegisteredStudents().size()) {
e.claimGroup(group); e.claimGroup(group);
@ -98,6 +99,7 @@ public class AssignmentService {
} else { } else {
removed.add(group); removed.add(group);
} }
}
}); });
} }
this.userService.save(e); this.userService.save(e);

View File

@ -26,6 +26,13 @@ public class CommisionService {
public CommisionService() { public CommisionService() {
} }
/**
* save to database commision. It also checks for missing assignments from
* previous commision (you can not get rid of accepted assignment)
*
* @param commision to save to db
* @return Commision instance with id from database
*/
public Commision save(Commision commision) { public Commision save(Commision commision) {
Optional<Commision> lastCommision = this.getNewestCommision(commision.getCommisionOwner()); Optional<Commision> lastCommision = this.getNewestCommision(commision.getCommisionOwner());
if (lastCommision.isPresent()) { if (lastCommision.isPresent()) {
@ -34,6 +41,7 @@ public class CommisionService {
assignment.setPastAssignment(true); assignment.setPastAssignment(true);
this.aRepository.save(assignment); this.aRepository.save(assignment);
}); });
} }
this.repo.save(commision); this.repo.save(commision);
return commision; return commision;

View File

@ -10,7 +10,8 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
/** /**
* Service of CourseService which can get(Course By Name, All Courses, Courses Ammount ), save, delete course. * Service of CourseService which can get(Course By Name, All Courses, Courses
* Ammount ), save, delete course.
*/ */
@Service @Service
@ -18,42 +19,46 @@ public class CourseService {
@Autowired @Autowired
private CourseRepository repo; private CourseRepository repo;
/* /**
* getCourseByName * getCourseByName
* Return Course By Name *
* @param name name of course to be found
* @return Course By Name
*/ */
public Optional<Course> getCourseByName(String name) { public Optional<Course> getCourseByName(String name) {
return this.repo.findByName(name); return this.repo.findByName(name);
} }
/* /**
* getAllCourses *
* Return List of get courses * @return all courses from db
*/ */
public List<Course> getAllCourses() { public List<Course> getAllCourses() {
return this.repo.findAll(); return this.repo.findAll();
} }
/* /**
* save * save to db
*
* @param course which course you would like to save * @param course which course you would like to save
* @return Course instance with id from db
*/ */
public Course save(Course course) { public Course save(Course course) {
this.repo.save(course); this.repo.save(course);
return course; return course;
} }
/* /**
* delete * delete course from db
*
* @param course which course you would like to delete * @param course which course you would like to delete
*/ */
public void delete(Course course) { public void delete(Course course) {
this.repo.delete(course); this.repo.delete(course);
} }
/* /**
* getCoursesAmmount * @return ammount of courses in db
* Return a ammount of courses
*/ */
public int getCoursesAmmount() { public int getCoursesAmmount() {
return (int) this.repo.count(); return (int) this.repo.count();

View File

@ -12,6 +12,9 @@ import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger; import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
/**
* Service to manage app events
*/
@Service @Service
public class EventService { public class EventService {
@ -29,6 +32,9 @@ public class EventService {
System.out.println("Checking for groups"); System.out.println("Checking for groups");
} }
/**
* perfroms checks for matching exchanges daily
*/
@Scheduled(cron = "0 0 0 * * *") @Scheduled(cron = "0 0 0 * * *")
public void performExchangeService() { public void performExchangeService() {
System.out.println("Performing Exchange"); System.out.println("Performing Exchange");
@ -53,6 +59,10 @@ public class EventService {
jobsMap.put(taskId, scheduledTask); jobsMap.put(taskId, scheduledTask);
} }
/**
* init resources needed for dynamicly creating new tasks (needed to set tours
* end events)
*/
@PostConstruct @PostConstruct
public void initialize() { public void initialize() {
this.scheduler = new ThreadPoolTaskScheduler(); this.scheduler = new ThreadPoolTaskScheduler();

View File

@ -19,6 +19,9 @@ import com.plannaplan.repositories.ExchangeRepository;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
/**
* Service to manage Exchanges
*/
@Service @Service
public class ExchangeService { public class ExchangeService {
@ -50,6 +53,9 @@ public class ExchangeService {
return this.repo.findById(id); return this.repo.findById(id);
} }
/**
* @return list of all exchanges in database
*/
public List<Exchange> getAllExchanges() { public List<Exchange> getAllExchanges() {
return this.repo.findAll(); return this.repo.findAll();
} }
@ -78,6 +84,12 @@ public class ExchangeService {
return this.repo.checkForExchange(assignment, group); return this.repo.checkForExchange(assignment, group);
} }
/**
* method to perform Exchange algorythm. It search for matches and swap
* assignments between latests user commisions if it can be performed. After
* swap we block users matches that contains switched groups. After algorythm
* email is being sent to all users with information about performed exchanges
*/
public void performExchange() { public void performExchange() {
final List<MatchData> matchData = this.getMatches(); final List<MatchData> matchData = this.getMatches();
final List<Long> performedAssignmentExchanges = new ArrayList<>(); final List<Long> performedAssignmentExchanges = new ArrayList<>();
@ -127,6 +139,9 @@ public class ExchangeService {
this.repo.deleteAll(exchangesToDelete); this.repo.deleteAll(exchangesToDelete);
} }
/**
* @return list of matches found in database
*/
public List<MatchData> getMatches() { public List<MatchData> getMatches() {
final List<MatchData> matches = this.repo.getMatches().stream().map(m -> { final List<MatchData> matches = this.repo.getMatches().stream().map(m -> {
final Exchange exchangeOne = (Exchange) m[0]; final Exchange exchangeOne = (Exchange) m[0];

View File

@ -18,7 +18,6 @@ import org.springframework.stereotype.Service;
* Service of GroupService which can find(optional), get(By Course, Groups * Service of GroupService which can find(optional), get(By Course, Groups
* Ammount, Group By Id, find Not Existing Group), save, delete group. * Ammount, Group By Id, find Not Existing Group), save, delete group.
*/ */
@Service @Service
public class GroupService { public class GroupService {
@Autowired @Autowired
@ -27,34 +26,84 @@ public class GroupService {
public GroupService() { public GroupService() {
} }
/**
* find group with given properties
*
* @param time scheduled time for group as int of minutes passed from 00:00
* @param capacity capacity of group
* @param room class room
* @return optional with Groups instance if found
*/
public Optional<Groups> find(int time, int capacity, String room) { public Optional<Groups> find(int time, int capacity, String room) {
return this.repo.find(time, room, capacity); return this.repo.find(time, room, capacity);
} }
/**
* find group with given properties
*
* @param zajCykId proteprty from usos
* @param nrGr group number
* @return optional with Groups instance if found
*/
public Optional<Groups> find(Integer zajCykId, Integer nrGr) { public Optional<Groups> find(Integer zajCykId, Integer nrGr) {
return this.repo.find(zajCykId, nrGr); return this.repo.find(zajCykId, nrGr);
} }
/**
* find group with given properties
*
* @param id course id of groups belogns to
* @return list of found groups
*/
public List<Groups> getGroupsByCourse(Long id) { public List<Groups> getGroupsByCourse(Long id) {
return this.repo.getByCourse(id); return this.repo.getByCourse(id);
} }
/**
* save group to database
*
* @param group insatnce to be saved
* @return new instance that has id form database
*/
public Groups save(Groups group) { public Groups save(Groups group) {
return this.repo.save(group); return this.repo.save(group);
} }
/**
* delete from database
*
* @param groups isntance to delete
*/
public void delete(Groups groups) { public void delete(Groups groups) {
this.repo.delete(groups); this.repo.delete(groups);
} }
/**
* get hom manyh groups are in database in general
*
* @return int - groups ammount
*/
public int getGroupsAmmount() { public int getGroupsAmmount() {
return (int) this.repo.count(); return (int) this.repo.count();
} }
/**
* find group with given properties
*
* @param id group id
* @return optional with group if found
*/
public Optional<Groups> getGroupById(Long id) { public Optional<Groups> getGroupById(Long id) {
return this.repo.findById(id); return this.repo.findById(id);
} }
/**
* get wich of provided id is not existind groups
*
* @param ids list of ids to check
* @return optional with id that is not group if found. If there is multiple
* will be returned first found
*/
public Optional<Long> findNotExistingGroup(List<Long> ids) { public Optional<Long> findNotExistingGroup(List<Long> ids) {
for (Long oneId : ids) { for (Long oneId : ids) {
if (this.repo.existsById(oneId) == false) { if (this.repo.existsById(oneId) == false) {

View File

@ -0,0 +1,7 @@
/**
* Provides service classes to make operations with entities or comunicate with
* external systems.
*
* @since 1.0
*/
package com.plannaplan.services;

View File

@ -0,0 +1,6 @@
/**
* Provides enums for different goals.
*
* @since 1.0
*/
package com.plannaplan.types;

View File

@ -131,6 +131,34 @@ public class AssignmentServiceTest {
} }
@Test
@DirtiesContext(methodMode = MethodMode.BEFORE_METHOD)
public void shouldAcceptTwoTours() throws InterruptedException {
final Groups group = this.groupService.save(new Groups(5, null, null, 840, WeekDay.MONDAY, null));
final Groups group2 = this.groupService.save(new Groups(5, null, null, 840, WeekDay.MONDAY, null));
User user = this.userService.save(new User(null, null,
"shouldNotAcceptForOnePerson-" + UUID.randomUUID().toString() + "@AssignmentService.test", null,
UserRoles.STUDENT, 234));
final Commision com = this.comServie.save(new Commision(user));
this.service.save(new Assignment(group, com));
this.service.callAcceptAlgorythm();
user = this.userService.getById(user.getId()).get();
assertTrue(user.getStudentRegisteredGrups().size() == 1);
this.service.save(new Assignment(group2, com));
this.service.callAcceptAlgorythm();
user = this.userService.getById(user.getId()).get();
assertTrue(user.getStudentRegisteredGrups().size() == 2);
}
private void addAssignmentToCommision(Commision com) { private void addAssignmentToCommision(Commision com) {
Assignment a = new Assignment(null, com); Assignment a = new Assignment(null, com);
this.service.save(a); this.service.save(a);

View File

@ -21,6 +21,9 @@ import org.springframework.scheduling.annotation.EnableScheduling;
import com.plannaplan.services.ConfiguratorService; import com.plannaplan.services.ConfiguratorService;
/**
* Root class of Application.
*/
@SpringBootApplication @SpringBootApplication
@EnableScheduling @EnableScheduling
public class App { public class App {
@ -46,7 +49,9 @@ public class App {
/** /**
* method to import mocked data to testing app after startz. It is called only * method to import mocked data to testing app after startz. It is called only
* in dev profile * in dev profile. Note that tests are written to this app state so if you
* change ConfigData it can have an impact to other tests like
* CommisionControllerTest
*/ */
@EventListener(ApplicationReadyEvent.class) @EventListener(ApplicationReadyEvent.class)
public void importData() { public void importData() {

View File

@ -3,6 +3,9 @@ package com.plannaplan;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
/**
* Class to generate logo string on start application and make logs info
*/
public class Logo { public class Logo {
public static final String ANSI_RESET = "\u001B[0m"; public static final String ANSI_RESET = "\u001B[0m";
@ -35,6 +38,11 @@ ANSI_RESET;
} }
/**
* return init string to log
* @param isDev is spring profile dev
* @return string to print in log
*/
public static String getInitInfo(boolean isDev){ public static String getInitInfo(boolean isDev){
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"); DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
LocalDateTime now = LocalDateTime.now(); LocalDateTime now = LocalDateTime.now();
@ -45,6 +53,11 @@ ANSI_RESET;
return ANSI_BLACK + dtf.format(now) + ANSI_YELLOW + " plannaplan" + ANSI_RESET + " initializing [" +ANSI_BLUE + "prod" + ANSI_RESET +"]"; return ANSI_BLACK + dtf.format(now) + ANSI_YELLOW + " plannaplan" + ANSI_RESET + " initializing [" +ANSI_BLUE + "prod" + ANSI_RESET +"]";
} }
/**
* return start string to log
* @param isDev is spring profile dev
* @return string to print in log
*/
public static String getStartedInfo(boolean isDev){ public static String getStartedInfo(boolean isDev){
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"); DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
LocalDateTime now = LocalDateTime.now(); LocalDateTime now = LocalDateTime.now();

View File

@ -18,6 +18,9 @@ import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2; import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* Config class of Swagger to generate rest api documentation
*/
@Configuration @Configuration
@EnableSwagger2 @EnableSwagger2
public class Swagger2Config extends WebMvcConfigurationSupport { public class Swagger2Config extends WebMvcConfigurationSupport {

View File

@ -22,7 +22,9 @@ import com.plannaplan.responses.mappers.CommisionResponseMappers;
import com.plannaplan.responses.models.CommisionResponse; import com.plannaplan.responses.models.CommisionResponse;
import com.plannaplan.services.AssignmentService; import com.plannaplan.services.AssignmentService;
import com.plannaplan.services.CommisionService; import com.plannaplan.services.CommisionService;
import com.plannaplan.services.ConfiguratorService;
import com.plannaplan.services.GroupService; import com.plannaplan.services.GroupService;
import com.plannaplan.types.AppState;
import com.plannaplan.types.UserRoles; import com.plannaplan.types.UserRoles;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -37,10 +39,15 @@ import org.springframework.web.bind.annotation.RequestParam;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator;
import com.plannaplan.responses.mappers.AssignmentResponseMappers; import com.plannaplan.responses.mappers.AssignmentResponseMappers;
import com.plannaplan.responses.models.AssignmentResponse; import com.plannaplan.responses.models.AssignmentResponse;
/**
* Rest controller to Commision and Assignment related endpoints. More detailed
* api docs is available via swagger
*/
@RestController @RestController
@CrossOrigin @CrossOrigin
@RequestMapping("/api/" + App.API_VERSION + "/commisions") @RequestMapping("/api/" + App.API_VERSION + "/commisions")
@ -56,9 +63,17 @@ public class CommisionController extends TokenBasedController {
@Autowired @Autowired
private AssignmentService assignmentService; private AssignmentService assignmentService;
@Autowired
private ConfiguratorService configuratorService;
public CommisionController() { public CommisionController() {
} }
/**
* @param groups to make assignmetns
* @param userId user to assign to groups
* @return was operations success
*/
@PostMapping(value = { "/user", "/user/{id}" }) @PostMapping(value = { "/user", "/user/{id}" })
@ApiOperation(value = "Create commision with assignents to given groups. If group doesn't exist error will be thrown") @ApiOperation(value = "Create commision with assignents to given groups. If group doesn't exist error will be thrown")
public ResponseEntity<String> addCommision( public ResponseEntity<String> addCommision(
@ -66,7 +81,7 @@ public class CommisionController extends TokenBasedController {
@PathVariable(name = "id", required = false) Long userId) { @PathVariable(name = "id", required = false) Long userId) {
try { try {
final AppState appState = this.configuratorService.getCurrentConfig().getCurrentState();
final User asker = this.getCurrentUser() final User asker = this.getCurrentUser()
.orElseThrow(() -> new UserNotFoundException("Invalid token")); .orElseThrow(() -> new UserNotFoundException("Invalid token"));
@ -76,23 +91,46 @@ public class CommisionController extends TokenBasedController {
: asker; : asker;
Assert.isTrue((asker.getRole() == UserRoles.DEANERY && user.getRole() == UserRoles.STUDENT Assert.isTrue((asker.getRole() == UserRoles.DEANERY && user.getRole() == UserRoles.STUDENT
|| (asker.getId().equals(user.getId()) && user.getRole() == UserRoles.STUDENT)), && appState == AppState.NO_TOUR
|| (asker.getId().equals(user.getId()) && user.getRole() == UserRoles.STUDENT
&& appState != AppState.NO_TOUR)),
"Incorrect attempt to change plan"); "Incorrect attempt to change plan");
Optional<Long> notExistingGroup = this.groupServcicxe.findNotExistingGroup(groups); Optional<Long> notExistingGroup = this.groupServcicxe.findNotExistingGroup(groups);
Assert.isTrue(!notExistingGroup.isPresent(), "Group " Assert.isTrue(!notExistingGroup.isPresent(), "Group "
+ notExistingGroup.orElse(Long.MIN_VALUE).toString() + "doesn't exist"); + notExistingGroup.orElse(Long.MIN_VALUE).toString() + "doesn't exist");
final Optional<Commision> comPrev = this.commisionService.getNewestCommision(user);
final Commision com = new Commision(user, asker); final Commision com = new Commision(user, asker);
this.commisionService.save(com); this.commisionService.save(com);
final List<Long> addedGroups = new ArrayList<>();
groups.stream().forEach((groupId) -> { groups.stream().forEach((groupId) -> {
Groups group = this.groupServcicxe.getGroupById(groupId) Groups group = this.groupServcicxe.getGroupById(groupId)
.orElseThrow(() -> new NullPointerException()); .orElseThrow(() -> new NullPointerException());
Assignment a = new Assignment(group, com); Assignment a = new Assignment(group, com);
this.assignmentService.save(a); this.assignmentService.save(a);
addedGroups.add(groupId);
}); });
boolean isBad = false;
if (comPrev.isPresent()) {
final Iterator<Assignment> it = comPrev.get().getAssignments().iterator();
while (it.hasNext() && !isBad) {
final Assignment a = it.next();
if (a.isAccepted() && !addedGroups.contains(a.getId())) {
isBad = true;
}
}
}
if (isBad) {
return new ResponseEntity<>("Error. You can't delete accepted assignmet",
HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>("Succes", HttpStatus.OK); return new ResponseEntity<>("Succes", HttpStatus.OK);
} catch (UserNotFoundException exception) { } catch (UserNotFoundException exception) {
return new ResponseEntity<>(exception.getMessage(), HttpStatus.NOT_FOUND); return new ResponseEntity<>(exception.getMessage(), HttpStatus.NOT_FOUND);
@ -101,6 +139,11 @@ public class CommisionController extends TokenBasedController {
} }
} }
/**
* @param groups should include groups list in response
* @return list of user all commisions (history of schedules)
* @throws UserNotFoundException if user was found
*/
@GetMapping("/user") @GetMapping("/user")
@ApiOperation("Return list of user all commisions (history of schedules)") @ApiOperation("Return list of user all commisions (history of schedules)")
public ResponseEntity<List<? extends CommisionResponse>> getAlCommisions( public ResponseEntity<List<? extends CommisionResponse>> getAlCommisions(
@ -120,6 +163,11 @@ public class CommisionController extends TokenBasedController {
return new ResponseEntity<>(result, HttpStatus.OK); return new ResponseEntity<>(result, HttpStatus.OK);
} }
/**
* @return current schedule of user indenified via token
* @throws Exception if incorrect role was trying to see self schedule (for
* example DEANERY don't have a schedule)
*/
@GetMapping("/user/schedule") @GetMapping("/user/schedule")
@ApiOperation(value = "Return user current assignemts (from newest commision). STUDENT Token needs to be provided.") @ApiOperation(value = "Return user current assignemts (from newest commision). STUDENT Token needs to be provided.")
public ResponseEntity<List<AssignmentResponse>> getCurrentAssignments() throws Exception { public ResponseEntity<List<AssignmentResponse>> getCurrentAssignments() throws Exception {
@ -137,6 +185,12 @@ public class CommisionController extends TokenBasedController {
return new ResponseEntity<>(new ArrayList<>(), HttpStatus.OK); return new ResponseEntity<>(new ArrayList<>(), HttpStatus.OK);
} }
/**
* @param userId user id in db
* @param groups should commision include assigned groups list
* @return list of commisions for given user
* @throws UserNotFoundException
*/
@PreAuthorize("hasRole('ROLE_DEANERY')") @PreAuthorize("hasRole('ROLE_DEANERY')")
@GetMapping("/user/{id}") @GetMapping("/user/{id}")
@ApiOperation("Return list of commisions for given user. To be able to access this data u need to provide DEANERY token") @ApiOperation("Return list of commisions for given user. To be able to access this data u need to provide DEANERY token")
@ -156,6 +210,11 @@ public class CommisionController extends TokenBasedController {
return new ResponseEntity<>(result, HttpStatus.OK); return new ResponseEntity<>(result, HttpStatus.OK);
} }
/**
* @param userId schedule to display owner
* @return user's schedule
* @throws Exception if incorrect access atempt occured
*/
@PreAuthorize("hasRole('ROLE_DEANERY')") @PreAuthorize("hasRole('ROLE_DEANERY')")
@GetMapping("/user/{id}/schedule") @GetMapping("/user/{id}/schedule")
@ApiOperation(value = "Return given user current assignemts (from newest commision). DEANERY Token needs to be provided.") @ApiOperation(value = "Return given user current assignemts (from newest commision). DEANERY Token needs to be provided.")

View File

@ -35,6 +35,10 @@ import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiParam;
/**
* Rest controller to Config related endpoints. More detailed api docs is
* available via swagger
*/
@RestController @RestController
@CrossOrigin @CrossOrigin
@RequestMapping("/api/" + App.API_VERSION + "/configurator") @RequestMapping("/api/" + App.API_VERSION + "/configurator")
@ -54,7 +58,15 @@ public class ConfigController {
@Autowired @Autowired
private UserService userService; private UserService userService;
/**
* @param file file .xlsx that contains courses and groups with
* apoinnted rules
* @param firstTourBegin formated string dd.MM.yyyy
* @param firstTourEnd formated string dd.MM.yyyy
* @param secondTourBegin formated string dd.MM.yyyy
* @param secondTourEnd formated string dd.MM.yyyy
* @return was config success
*/
@PostMapping(path = "/config", consumes = { "multipart/form-data" }) @PostMapping(path = "/config", consumes = { "multipart/form-data" })
@PreAuthorize("hasRole('ROLE_ADMIN')") @PreAuthorize("hasRole('ROLE_ADMIN')")
@ApiOperation("Imports data to system. To call you need to provide ADMIN token") @ApiOperation("Imports data to system. To call you need to provide ADMIN token")
@ -82,7 +94,13 @@ public class ConfigController {
} }
} }
/**
* @param firstTourBegin formated string dd.MM.yyyy
* @param firstTourEnd formated string dd.MM.yyyy
* @param secondTourBegin formated string dd.MM.yyyy
* @param secondTourEnd formated string dd.MM.yyyy
* @return was operation successful
*/
@PostMapping(path = "/config/tours") @PostMapping(path = "/config/tours")
@PreAuthorize("hasRole('ROLE_ADMIN')") @PreAuthorize("hasRole('ROLE_ADMIN')")
@ApiOperation("Set tours dates. To call you need to provide ADMIN token") @ApiOperation("Set tours dates. To call you need to provide ADMIN token")
@ -104,12 +122,15 @@ public class ConfigController {
return new ResponseEntity<>("Sucess", HttpStatus.OK); return new ResponseEntity<>("Sucess", HttpStatus.OK);
} }
/**
* @param file file .xlsx that contains courses and groups with
* @return was operation successfull
*/
@PostMapping(path = "/config/courses", consumes = { "multipart/form-data" }) @PostMapping(path = "/config/courses", consumes = { "multipart/form-data" })
@PreAuthorize("hasRole('ROLE_ADMIN')") @PreAuthorize("hasRole('ROLE_ADMIN')")
@ApiOperation("Imports data to system. To call you need to provide ADMIN token") @ApiOperation("Imports data to system. To call you need to provide ADMIN token")
public ResponseEntity<String> configAppChangeCources( public ResponseEntity<String> configAppChangeCources(
@RequestParam("file") @ApiParam(value = "file .xlsx that contains courses and groups with apoinnted rules") MultipartFile file) @RequestParam("file") @ApiParam(value = "file .xlsx that contains courses and groups with apoinnted rules") MultipartFile file) {
{
try { try {
this.contrl.importCoursesStream(file.getInputStream()); this.contrl.importCoursesStream(file.getInputStream());
return new ResponseEntity<>("Sucess", HttpStatus.OK); return new ResponseEntity<>("Sucess", HttpStatus.OK);
@ -118,10 +139,15 @@ public class ConfigController {
} }
} }
/**
* @param ticket CAS ticket to get user wuthority
* @return was admin created
*/
@PostMapping(path = "/admin/init") @PostMapping(path = "/admin/init")
@ApiOperation("It can be run only in the initialization of the application. It will create admin user to manage the application.") @ApiOperation("It can be run only in the initialization of the application. It will create admin user to manage the application.")
public ResponseEntity<String> initAdmin(@RequestParam("ticket") @ApiParam(value = "Ticket for validation.") String ticket){ public ResponseEntity<String> initAdmin(
if (this.userService.adminExists()){ @RequestParam("ticket") @ApiParam(value = "Ticket for validation.") String ticket) {
if (this.userService.adminExists()) {
return new ResponseEntity<>("Admin had been already created.", HttpStatus.FORBIDDEN); return new ResponseEntity<>("Admin had been already created.", HttpStatus.FORBIDDEN);
} }

View File

@ -29,6 +29,10 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import com.plannaplan.responses.models.abstracts.CoursesResponse; import com.plannaplan.responses.models.abstracts.CoursesResponse;
/**
* Rest controller to Courses related endpoints. More detailed api docs is
* available via swagger
*/
@RestController @RestController
@CrossOrigin @CrossOrigin
@RequestMapping("/api/" + App.API_VERSION + "/courses") @RequestMapping("/api/" + App.API_VERSION + "/courses")
@ -41,6 +45,11 @@ public class CoursesController {
@Autowired @Autowired
private GroupService groupService; private GroupService groupService;
/**
* @param groups should include groups in response
* @param takenPlaces should include groups in response
* @return list of all courses in system
*/
@GetMapping("/all") @GetMapping("/all")
@ApiOperation(value = "Return all courses") @ApiOperation(value = "Return all courses")
public ResponseEntity<List<? extends CoursesResponse>> getMethodName( public ResponseEntity<List<? extends CoursesResponse>> getMethodName(

View File

@ -33,11 +33,15 @@ import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiParam;
/**
* Rest controller to Exchange related endpoints. More detailed api docs is
* available via swagger
*/
@RestController @RestController
@CrossOrigin @CrossOrigin
@RequestMapping("/api/" + App.API_VERSION + "/exchanges") @RequestMapping("/api/" + App.API_VERSION + "/exchanges")
@Api(tags = { "Exchange" }, value = "Exchange", description = "Endpoint to exchange with accepted assignments.") @Api(tags = { "Exchange" }, value = "Exchange", description = "Endpoint to exchange with accepted assignments.")
public class ExchangeController extends TokenBasedController{ public class ExchangeController extends TokenBasedController {
@Autowired @Autowired
private GroupService groupService; private GroupService groupService;
@ -48,40 +52,47 @@ public class ExchangeController extends TokenBasedController{
@Autowired @Autowired
private ExchangeService exchangeService; private ExchangeService exchangeService;
/**
* @param exchangeRequest mapped json body with requierd paramas (groupid and
* assignment)
* @return was job successfull
* @throws UserNotFoundException if user was not found
*/
@PostMapping("/exchange") @PostMapping("/exchange")
@ApiOperation(value = "Creates exchange offer.") @ApiOperation(value = "Creates exchange offer.")
public ResponseEntity<String> createExchange( public ResponseEntity<String> createExchange(
@ApiParam( value = "Json object that contains assignment to trade and desired group") @ApiParam(value = "Json object that contains assignment to trade and desired group. For example: { \"assignment\": 3, \"group\":32 }") @RequestBody Map<String, Long> exchangeRequest)
@RequestBody
Map<String, Long> exchangeRequest)
throws UserNotFoundException { throws UserNotFoundException {
final User asker = this.getCurrentUser() final User asker = this.getCurrentUser().orElseThrow(() -> new UserNotFoundException("Invalid token"));
.orElseThrow(() -> new UserNotFoundException("Invalid token"));
final Long assignmentId = exchangeRequest.get("assignment"); final Long assignmentId = exchangeRequest.get("assignment");
final Long groupId = exchangeRequest.get("group"); final Long groupId = exchangeRequest.get("group");
final List<Long> ownedGroups = asker.getStudentRegisteredGrups().stream().map(Groups::getId).collect(Collectors.toList()); final List<Long> ownedGroups = asker.getStudentRegisteredGrups().stream().map(Groups::getId)
.collect(Collectors.toList());
if(ownedGroups.contains(groupId)){ if (ownedGroups.contains(groupId)) {
return new ResponseEntity<>("User has already got this group.", HttpStatus.BAD_REQUEST); return new ResponseEntity<>("User has already got this group.", HttpStatus.BAD_REQUEST);
} }
if(assignmentId == null || groupId == null ){ if (assignmentId == null || groupId == null) {
return new ResponseEntity<>("Some of values are missing", HttpStatus.BAD_REQUEST); return new ResponseEntity<>("Some of values are missing", HttpStatus.BAD_REQUEST);
} }
final Optional<Assignment> assignment = this.assignmentService.getById(assignmentId); final Optional<Assignment> assignment = this.assignmentService.getById(assignmentId);
final Optional<Groups> group = this.groupService.getGroupById(groupId); final Optional<Groups> group = this.groupService.getGroupById(groupId);
if(assignment.isEmpty() || group.isEmpty()){ if (assignment.isEmpty() || group.isEmpty()) {
return new ResponseEntity<>("Some of provided value does not exist.", HttpStatus.BAD_REQUEST); return new ResponseEntity<>("Some of provided value does not exist.", HttpStatus.BAD_REQUEST);
} }
final Assignment assignmentInstance = assignment.get(); final Assignment assignmentInstance = assignment.get();
final Groups groupInstance = group.get(); final Groups groupInstance = group.get();
if(!(assignmentInstance.getCommision().getCommisionOwner().getId().equals(asker.getId()) && assignmentInstance.isAccepted())){ if (!(assignmentInstance.getCommision().getCommisionOwner().getId().equals(asker.getId())
return new ResponseEntity<>("Some of problems appeared. Check if you have access to given assignment and if it is accepted or the exchange has not been already added.", HttpStatus.BAD_REQUEST); && assignmentInstance.isAccepted())) {
return new ResponseEntity<>(
"Some of problems appeared. Check if you have access to given assignment and if it is accepted or the exchange has not been already added.",
HttpStatus.BAD_REQUEST);
} }
this.exchangeService.save(new Exchange(assignmentInstance, groupInstance)); this.exchangeService.save(new Exchange(assignmentInstance, groupInstance));
@ -89,23 +100,27 @@ public class ExchangeController extends TokenBasedController{
return new ResponseEntity<>("Success", HttpStatus.OK); return new ResponseEntity<>("Success", HttpStatus.OK);
} }
/**
* @param offerId id to delwete from db
* @return was jub successful
* @throws UserNotFoundException if user was not found
*/
@DeleteMapping("/exchange/{id}") @DeleteMapping("/exchange/{id}")
@ApiOperation(value = "Delete exchange offer") @ApiOperation(value = "Delete exchange offer")
public ResponseEntity<String> deleteExchange(@PathVariable(name = "id", required = false) Long offerId) public ResponseEntity<String> deleteExchange(@PathVariable(name = "id", required = false) Long offerId)
throws UserNotFoundException { throws UserNotFoundException {
final User asker = this.getCurrentUser() final User asker = this.getCurrentUser().orElseThrow(() -> new UserNotFoundException("Invalid token"));
.orElseThrow(() -> new UserNotFoundException("Invalid token"));
final Optional<Exchange> exchange = this.exchangeService.getById(offerId); final Optional<Exchange> exchange = this.exchangeService.getById(offerId);
if(exchange.isEmpty()){ if (exchange.isEmpty()) {
return new ResponseEntity<>("Given offer does not exist.", HttpStatus.BAD_REQUEST); return new ResponseEntity<>("Given offer does not exist.", HttpStatus.BAD_REQUEST);
} }
final Exchange exchangeToDelete = exchange.get(); final Exchange exchangeToDelete = exchange.get();
if(!(exchangeToDelete.getOwnedAssignment().getCommision().getCommisionOwner().getId().equals(asker.getId()))){ if (!(exchangeToDelete.getOwnedAssignment().getCommision().getCommisionOwner().getId().equals(asker.getId()))) {
return new ResponseEntity<>("You have not permission for that action.", HttpStatus.BAD_REQUEST); return new ResponseEntity<>("You have not permission for that action.", HttpStatus.BAD_REQUEST);
} }
@ -113,13 +128,15 @@ public class ExchangeController extends TokenBasedController{
return new ResponseEntity<>("Success", HttpStatus.OK); return new ResponseEntity<>("Success", HttpStatus.OK);
} }
/**
* @return return all user's exchange offers
* @throws UserNotFoundException iF user was not found
*/
@GetMapping("/exchange/all") @GetMapping("/exchange/all")
@ApiOperation(value = "Get exchange offers") @ApiOperation(value = "Get exchange offers")
public ResponseEntity<List<ExchangeResponse>> getExchange() public ResponseEntity<List<ExchangeResponse>> getExchange() throws UserNotFoundException {
throws UserNotFoundException {
final User asker = this.getCurrentUser() final User asker = this.getCurrentUser().orElseThrow(() -> new UserNotFoundException("Invalid token"));
.orElseThrow(() -> new UserNotFoundException("Invalid token"));
final List<Exchange> response = exchangeService.getByUserId(asker.getId()); final List<Exchange> response = exchangeService.getByUserId(asker.getId());
final List<ExchangeResponse> listOfResponses = ExchangeResponseMappers.mapToDefaultResponse(response); final List<ExchangeResponse> listOfResponses = ExchangeResponseMappers.mapToDefaultResponse(response);
@ -127,22 +144,26 @@ public class ExchangeController extends TokenBasedController{
return new ResponseEntity<>(listOfResponses, HttpStatus.OK); return new ResponseEntity<>(listOfResponses, HttpStatus.OK);
} }
/**
* @param offerId id of exchange in db
* @return Exchage response
* @throws UserNotFoundException if user was not found
*/
@GetMapping("/exchange/{id}") @GetMapping("/exchange/{id}")
@ApiOperation(value = "Get exchange offers") @ApiOperation(value = "Get exchange offer")
public ResponseEntity<ExchangeResponse> getExchangeById(@PathVariable(name = "id", required = false) Long offerId) public ResponseEntity<ExchangeResponse> getExchangeById(@PathVariable(name = "id", required = false) Long offerId)
throws UserNotFoundException { throws UserNotFoundException {
final User asker = this.getCurrentUser() final User asker = this.getCurrentUser().orElseThrow(() -> new UserNotFoundException("Invalid token"));
.orElseThrow(() -> new UserNotFoundException("Invalid token"));
final Optional<Exchange> exchange = this.exchangeService.getById(offerId); final Optional<Exchange> exchange = this.exchangeService.getById(offerId);
if(exchange.isEmpty()){ if (exchange.isEmpty()) {
return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST); return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
} }
final Exchange exchangeInstance = exchange.get(); final Exchange exchangeInstance = exchange.get();
if(!exchangeInstance.getOwnerId().equals(asker.getId())){ if (!exchangeInstance.getOwnerId().equals(asker.getId())) {
return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST); return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
} }

View File

@ -27,9 +27,12 @@ import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiParam;
/**
* Rest controller to Groups related endpoints. More detailed api docs is
* available via swagger
*/
@RestController @RestController
@CrossOrigin @CrossOrigin
@RequestMapping("/api/" + App.API_VERSION + "/groups") @RequestMapping("/api/" + App.API_VERSION + "/groups")
@Api(tags = { @Api(tags = {
"Group" }, value = "Group", description = "Enpoints to deal with gorups. Group is related directly to course and can be either class and lecture") "Group" }, value = "Group", description = "Enpoints to deal with gorups. Group is related directly to course and can be either class and lecture")
@ -37,6 +40,12 @@ public class GroupController {
@Autowired @Autowired
private GroupService groupService; private GroupService groupService;
/**
* @param id course to display with groups
* @param capacity should include capaticty in response
* @param takenPlaces should include takenPlaces in response
* @return CourseWithGroupsResponse
*/
@GetMapping("/course/{id}") @GetMapping("/course/{id}")
@ApiOperation(value = "Return list of lectures and classes (if present) given course") @ApiOperation(value = "Return list of lectures and classes (if present) given course")
public ResponseEntity<CourseWithGroupsResponse<? extends GroupDefaultResponse>> getCourses( public ResponseEntity<CourseWithGroupsResponse<? extends GroupDefaultResponse>> getCourses(
@ -61,6 +70,11 @@ public class GroupController {
return new ResponseEntity<>(GroupsMappers.mapToGetCourseGroupsDefaultResponse(groups), HttpStatus.OK); return new ResponseEntity<>(GroupsMappers.mapToGetCourseGroupsDefaultResponse(groups), HttpStatus.OK);
} }
/**
* @param id group id to change capacity
* @param newcapacity new capacity to insert
* @return ResponseEntity was action success
*/
@PutMapping("/{id}/capacity") @PutMapping("/{id}/capacity")
@PreAuthorize("hasRole('ROLE_DEANERY')") @PreAuthorize("hasRole('ROLE_DEANERY')")
@ApiOperation(value = "Change capacity of given group. You need to provide DEANERY token to be ale to change capacity") @ApiOperation(value = "Change capacity of given group. You need to provide DEANERY token to be ale to change capacity")

View File

@ -11,6 +11,10 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.authentication.AnonymousAuthenticationToken;
/**
* Abstract class for controllers that requires token to extra authorize action
* beyond spring security
*/
public abstract class TokenBasedController { public abstract class TokenBasedController {
@Autowired @Autowired
protected UserService userService; protected UserService userService;
@ -18,6 +22,10 @@ public abstract class TokenBasedController {
public TokenBasedController() { public TokenBasedController() {
} }
/**
* @return get currect user based no current spring context
* @throws UserNotFoundException if user was not fount
*/
protected Optional<User> getCurrentUser() throws UserNotFoundException { protected Optional<User> getCurrentUser() throws UserNotFoundException {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

View File

@ -26,6 +26,10 @@ import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiParam;
/**
* Rest controller to Token related endpoints. More detailed api docs is
* available via swagger
*/
@RestController @RestController
@CrossOrigin @CrossOrigin
@Api(tags = { "Token" }, value = "Token", description = "Enpoints to get authorization.") @Api(tags = { "Token" }, value = "Token", description = "Enpoints to get authorization.")
@ -40,6 +44,10 @@ public class TokenController {
@Autowired @Autowired
private UserService userService; private UserService userService;
/**
* @param ticket via CAS obtained ticket - it's base to auth user
* @return TokenResponse if operation was success
*/
@GetMapping("/token") @GetMapping("/token")
@ApiOperation(value = "Endpoint to access token required to call secured endpoints. In order to access token we need to provide access token comming from unviersity CAS system") @ApiOperation(value = "Endpoint to access token required to call secured endpoints. In order to access token we need to provide access token comming from unviersity CAS system")
public ResponseEntity<TokenResponse> getToken( public ResponseEntity<TokenResponse> getToken(
@ -64,6 +72,11 @@ public class TokenController {
} }
} }
/**
* @param refreshToken refresh token obtained via /token endpoint
* @return TokenResponse if operation was success
* @throws NullPointerException is thrown if user was not found by refrshtoken
*/
@GetMapping("/token/refresh") @GetMapping("/token/refresh")
@ApiOperation(value = "Endpoint to access new token based on refresh token. It's needed when request with provided token fail with code 403") @ApiOperation(value = "Endpoint to access new token based on refresh token. It's needed when request with provided token fail with code 403")
public ResponseEntity<TokenResponse> getRefreshToken( public ResponseEntity<TokenResponse> getRefreshToken(

View File

@ -27,6 +27,10 @@ import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
/**
* Rest controller to assignments related endpoints. More detailed api docs is
* available via swagger
*/
@RestController @RestController
@CrossOrigin @CrossOrigin
@RequestMapping("/api/" + App.API_VERSION + "/users") @RequestMapping("/api/" + App.API_VERSION + "/users")
@ -36,6 +40,10 @@ public class UsersController {
@Autowired @Autowired
private UserService userService; private UserService userService;
/**
* @param query to filrer userst with STUDENT role
* @return list found
*/
@GetMapping("/student/search") @GetMapping("/student/search")
@PreAuthorize("hasRole('ROLE_DEANERY')") @PreAuthorize("hasRole('ROLE_DEANERY')")
@ApiOperation(value = "Serch for user by providing query. If query is empty it will return all students. You need token with DEANERY role to call this") @ApiOperation(value = "Serch for user by providing query. If query is empty it will return all students. You need token with DEANERY role to call this")
@ -46,6 +54,9 @@ public class UsersController {
return new ResponseEntity<>(response, HttpStatus.OK); return new ResponseEntity<>(response, HttpStatus.OK);
} }
/**
* @return list of all studnents
*/
@GetMapping("/students") @GetMapping("/students")
@PreAuthorize("hasRole('ROLE_DEANERY')") @PreAuthorize("hasRole('ROLE_DEANERY')")
@ApiOperation(value = "Gets all students. You need token with DEANERY role to call this") @ApiOperation(value = "Gets all students. You need token with DEANERY role to call this")
@ -55,10 +66,16 @@ public class UsersController {
return new ResponseEntity<>(response, HttpStatus.OK); return new ResponseEntity<>(response, HttpStatus.OK);
} }
/**
* @param authority USOS ID or E-mail. If user does not exist it should be USOS
* ID
* @return response entity was operation with succcesss
*/
@PostMapping(path = "/admin") @PostMapping(path = "/admin")
@PreAuthorize("hasRole('ROLE_ADMIN')") @PreAuthorize("hasRole('ROLE_ADMIN')")
@ApiOperation(value = "Adds new admin user.") @ApiOperation(value = "Adds new admin user.")
public ResponseEntity<String> addAdmin(@RequestParam("authority") @ApiParam(value = "USOS ID or E-mail. If user does not exist it should be USOS ID") String authority) { public ResponseEntity<String> addAdmin(
@RequestParam("authority") @ApiParam(value = "USOS ID or E-mail. If user does not exist it should be USOS ID") String authority) {
final Optional<User> userResponse = this.userService.getByAuthority(authority); final Optional<User> userResponse = this.userService.getByAuthority(authority);
final User user = userResponse.orElseGet(() -> new User(null, null, null, authority, UserRoles.ADMIN)); final User user = userResponse.orElseGet(() -> new User(null, null, null, authority, UserRoles.ADMIN));
user.setRole(UserRoles.ADMIN); user.setRole(UserRoles.ADMIN);
@ -66,10 +83,16 @@ public class UsersController {
return new ResponseEntity<>("Success", HttpStatus.OK); return new ResponseEntity<>("Success", HttpStatus.OK);
} }
/**
* @param authority USOS ID or E-mail. If user does not exist it should be USOS
* ID
* @return response entity was operation with succcesss
*/
@PostMapping(path = "/deanery") @PostMapping(path = "/deanery")
@PreAuthorize("hasRole('ROLE_ADMIN')") @PreAuthorize("hasRole('ROLE_ADMIN')")
@ApiOperation(value = "Adds new deanery user.") @ApiOperation(value = "Adds new deanery user.")
public ResponseEntity<String> addDeanery(@RequestParam("authority") @ApiParam(value = "USOS ID or E-mail. If user does not exist it should be USOS ID") String authority) { public ResponseEntity<String> addDeanery(
@RequestParam("authority") @ApiParam(value = "USOS ID or E-mail. If user does not exist it should be USOS ID") String authority) {
final Optional<User> userResponse = this.userService.getByAuthority(authority); final Optional<User> userResponse = this.userService.getByAuthority(authority);
final User user = userResponse.orElseGet(() -> new User(null, null, null, authority, UserRoles.DEANERY)); final User user = userResponse.orElseGet(() -> new User(null, null, null, authority, UserRoles.DEANERY));
user.setRole(UserRoles.DEANERY); user.setRole(UserRoles.DEANERY);

View File

@ -0,0 +1,6 @@
/**
* Provides rest controllers that defines endpoints and their accessibility
*
* @since 1.0
*/
package com.plannaplan.controllers;

View File

@ -0,0 +1,6 @@
/**
* Root package of project
*
* @since 1.0
*/
package com.plannaplan;

View File

@ -11,12 +11,25 @@ import com.plannaplan.entities.Groups;
import com.plannaplan.responses.models.AssignmentResponse; import com.plannaplan.responses.models.AssignmentResponse;
import com.plannaplan.types.GroupType; import com.plannaplan.types.GroupType;
/**
* Mappers for Assingnmetns to api responses
*/
public class AssignmentResponseMappers { public class AssignmentResponseMappers {
/**
* @param assignments lsit of assignments to be maped
* @return list of api responses
*/
public static final List<AssignmentResponse> mapToResponse(List<Assignment> assignments) { public static final List<AssignmentResponse> mapToResponse(List<Assignment> assignments) {
return mapToResponse(assignments, null); return mapToResponse(assignments, null);
} }
/**
*
* @param assignments lsit of assignments to be maped
* @param ammounts ammounts to be take into account
* @return list of api responses
*/
public static final List<AssignmentResponse> mapToResponse(List<Assignment> assignments, public static final List<AssignmentResponse> mapToResponse(List<Assignment> assignments,
HashMap<Long, Integer> ammounts) { HashMap<Long, Integer> ammounts) {
List<AssignmentResponse> response = new ArrayList<>(); List<AssignmentResponse> response = new ArrayList<>();

View File

@ -8,11 +8,22 @@ import com.plannaplan.entities.Commision;
import com.plannaplan.responses.models.CommisionResponse; import com.plannaplan.responses.models.CommisionResponse;
import com.plannaplan.responses.models.CommisionWithGroupsResponse; import com.plannaplan.responses.models.CommisionWithGroupsResponse;
/**
* Mappers for Commisions to api responses
*/
public class CommisionResponseMappers { public class CommisionResponseMappers {
/**
* @param commisions list of commisions to be mapped
* @return list of api responses
*/
public static final List<CommisionResponse> mapToResponse(List<Commision> commisions) { public static final List<CommisionResponse> mapToResponse(List<Commision> commisions) {
return commisions.stream().filter(Objects::nonNull).map(CommisionResponse::new).collect(Collectors.toList()); return commisions.stream().filter(Objects::nonNull).map(CommisionResponse::new).collect(Collectors.toList());
} }
/**
* @param commisions list of commisions to be mapped
* @return list of api responses
*/
public static final List<CommisionWithGroupsResponse> mapToResponseWithGroups(List<Commision> commisions) { public static final List<CommisionWithGroupsResponse> mapToResponseWithGroups(List<Commision> commisions) {
return commisions.stream().filter(Objects::nonNull).map(CommisionWithGroupsResponse::new) return commisions.stream().filter(Objects::nonNull).map(CommisionWithGroupsResponse::new)
.collect(Collectors.toList()); .collect(Collectors.toList());

View File

@ -8,11 +8,22 @@ import com.plannaplan.entities.Course;
import com.plannaplan.responses.models.CoursesDefaultResponse; import com.plannaplan.responses.models.CoursesDefaultResponse;
import com.plannaplan.responses.models.CoursesWithGroupsResponse; import com.plannaplan.responses.models.CoursesWithGroupsResponse;
/**
* Mappers for Courses to api responses
*/
public class CoursesResponseMappers { public class CoursesResponseMappers {
/**
* @param courses list of courses to be mapped
* @return list of api responses
*/
public static final List<CoursesDefaultResponse> mapToGetCoursesResponse(List<Course> courses) { public static final List<CoursesDefaultResponse> mapToGetCoursesResponse(List<Course> courses) {
return courses.stream().filter(Objects::nonNull).map(CoursesDefaultResponse::new).collect(Collectors.toList()); return courses.stream().filter(Objects::nonNull).map(CoursesDefaultResponse::new).collect(Collectors.toList());
} }
/**
* @param courses list of courses to be mapped
* @return list of api responses
*/
public static final List<CoursesWithGroupsResponse> mapToGetCoursesWithGroupsResponse(List<Course> courses) { public static final List<CoursesWithGroupsResponse> mapToGetCoursesWithGroupsResponse(List<Course> courses) {
return courses.stream().filter(Objects::nonNull).map(CoursesWithGroupsResponse::new) return courses.stream().filter(Objects::nonNull).map(CoursesWithGroupsResponse::new)
.collect(Collectors.toList()); .collect(Collectors.toList());

View File

@ -7,7 +7,14 @@ import java.util.stream.Collectors;
import com.plannaplan.entities.Exchange; import com.plannaplan.entities.Exchange;
import com.plannaplan.responses.models.ExchangeResponse; import com.plannaplan.responses.models.ExchangeResponse;
/**
* Mappers for Exchange to api responses
*/
public class ExchangeResponseMappers { public class ExchangeResponseMappers {
/**
* @param exchanges lsit of exchanges to be mapped
* @return list of api responses
*/
public static final List<ExchangeResponse> mapToDefaultResponse(List<Exchange> exchanges) { public static final List<ExchangeResponse> mapToDefaultResponse(List<Exchange> exchanges) {
return exchanges.stream().filter(Objects::nonNull).map(ExchangeResponse::new).collect(Collectors.toList()); return exchanges.stream().filter(Objects::nonNull).map(ExchangeResponse::new).collect(Collectors.toList());
} }

View File

@ -13,7 +13,15 @@ import com.plannaplan.responses.models.CourseWithGroupsResponse;
import com.plannaplan.responses.models.GroupWithCapacityResponse; import com.plannaplan.responses.models.GroupWithCapacityResponse;
import com.plannaplan.types.GroupType; import com.plannaplan.types.GroupType;
/**
* Mappers for Groups to api responses
*/
public class GroupsMappers { public class GroupsMappers {
/**
* @param groups list of groups to be mapped
* @param taken ammoints to be take into account
* @return list of api responses
*/
public static List<GroupDefaultResponse> mapToDefaultResponse(List<Groups> groups, HashMap<Long, Integer> taken) { public static List<GroupDefaultResponse> mapToDefaultResponse(List<Groups> groups, HashMap<Long, Integer> taken) {
return groups.stream().filter(Objects::nonNull).map(new Function<Groups, GroupDefaultResponse>() { return groups.stream().filter(Objects::nonNull).map(new Function<Groups, GroupDefaultResponse>() {
@Override @Override
@ -27,10 +35,20 @@ public class GroupsMappers {
}).collect(Collectors.toList()); }).collect(Collectors.toList());
} }
/**
*
* @param groups list of groups to be mapped
* @return ammoints to be take into account
*/
public static List<GroupDefaultResponse> mapToDefaultResponse(List<Groups> groups) { public static List<GroupDefaultResponse> mapToDefaultResponse(List<Groups> groups) {
return GroupsMappers.mapToDefaultResponse(groups, null); return GroupsMappers.mapToDefaultResponse(groups, null);
} }
/**
* @param groups list of groups to be mapped
* @param taken ammoints to be take into account
* @return list of api responses
*/
public static List<GroupWithCapacityResponse> mapToCapacityResponse(List<Groups> groups, public static List<GroupWithCapacityResponse> mapToCapacityResponse(List<Groups> groups,
HashMap<Long, Integer> taken) { HashMap<Long, Integer> taken) {
return groups.stream().filter(Objects::nonNull).map(new Function<Groups, GroupWithCapacityResponse>() { return groups.stream().filter(Objects::nonNull).map(new Function<Groups, GroupWithCapacityResponse>() {
@ -45,10 +63,19 @@ public class GroupsMappers {
}).collect(Collectors.toList()); }).collect(Collectors.toList());
} }
/**
* @param groups list of groups to be mapped
* @return ammoints to be take into account
*/
public static List<GroupWithCapacityResponse> mapToCapacityResponse(List<Groups> groups) { public static List<GroupWithCapacityResponse> mapToCapacityResponse(List<Groups> groups) {
return GroupsMappers.mapToCapacityResponse(groups, null); return GroupsMappers.mapToCapacityResponse(groups, null);
} }
/**
* @param groups list of groups to be mapped
* @param taken ammoints to be take into account
* @return list of api responses
*/
public static CourseWithGroupsResponse<GroupDefaultResponse> mapToGetCourseGroupsDefaultResponse( public static CourseWithGroupsResponse<GroupDefaultResponse> mapToGetCourseGroupsDefaultResponse(
List<Groups> groups, HashMap<Long, Integer> taken) { List<Groups> groups, HashMap<Long, Integer> taken) {
@ -74,11 +101,20 @@ public class GroupsMappers {
return new CourseWithGroupsResponse<>(classes, lectures); return new CourseWithGroupsResponse<>(classes, lectures);
} }
/**
* @param groups list of groups to be mapped
* @return ammoints to be take into account
*/
public static CourseWithGroupsResponse<GroupDefaultResponse> mapToGetCourseGroupsDefaultResponse( public static CourseWithGroupsResponse<GroupDefaultResponse> mapToGetCourseGroupsDefaultResponse(
List<Groups> groups) { List<Groups> groups) {
return GroupsMappers.mapToGetCourseGroupsDefaultResponse(groups, null); return GroupsMappers.mapToGetCourseGroupsDefaultResponse(groups, null);
} }
/**
* @param groups list of groups to be mapped
* @param taken ammoints to be take into account
* @return list of api responses
*/
public static CourseWithGroupsResponse<GroupWithCapacityResponse> mapToGetCourseGroupsWithCapacityResponse( public static CourseWithGroupsResponse<GroupWithCapacityResponse> mapToGetCourseGroupsWithCapacityResponse(
List<Groups> groups, HashMap<Long, Integer> taken) { List<Groups> groups, HashMap<Long, Integer> taken) {
@ -105,6 +141,10 @@ public class GroupsMappers {
return new CourseWithGroupsResponse<>(classes, lectures); return new CourseWithGroupsResponse<>(classes, lectures);
} }
/**
* @param groups list of groups to be mapped
* @return ammoints to be take into account
*/
public static CourseWithGroupsResponse<GroupWithCapacityResponse> mapToGetCourseGroupsWithCapacityResponse( public static CourseWithGroupsResponse<GroupWithCapacityResponse> mapToGetCourseGroupsWithCapacityResponse(
List<Groups> groups) { List<Groups> groups) {
return GroupsMappers.mapToGetCourseGroupsWithCapacityResponse(groups, null); return GroupsMappers.mapToGetCourseGroupsWithCapacityResponse(groups, null);

View File

@ -7,9 +7,15 @@ import java.util.stream.Collectors;
import com.plannaplan.entities.User; import com.plannaplan.entities.User;
import com.plannaplan.responses.models.UserResponse; import com.plannaplan.responses.models.UserResponse;
/**
* Mappers for Users to api responses
*/
public class UserResponseMappers { public class UserResponseMappers {
/**
* @param groups list of groups to be mapped
* @return list of api responses
*/
public static List<UserResponse> mapToDefaultResponse(List<User> groups) { public static List<UserResponse> mapToDefaultResponse(List<User> groups) {
return groups.stream().filter(Objects::nonNull).map(UserResponse::new) return groups.stream().filter(Objects::nonNull).map(UserResponse::new).collect(Collectors.toList());
.collect(Collectors.toList());
} }
} }

View File

@ -0,0 +1,6 @@
/**
* Provides mappers to map mutiple entites from db to single api response
*
* @since 1.0
*/
package com.plannaplan.responses.mappers;

View File

@ -8,6 +8,9 @@ import com.plannaplan.types.GroupType;
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModel;
/**
* Assignment entity api response
*/
@ApiModel(description = "Response shows information about given assigment to course.", value = "AssignmentResponse") @ApiModel(description = "Response shows information about given assigment to course.", value = "AssignmentResponse")
public class AssignmentResponse { public class AssignmentResponse {
private Long id; private Long id;
@ -15,6 +18,11 @@ public class AssignmentResponse {
private GroupWithCapacityResponse classes; private GroupWithCapacityResponse classes;
private GroupWithCapacityResponse lecture; private GroupWithCapacityResponse lecture;
/**
* @param course course entity
* @param lecture lecture Groups entity
* @param classes class Groups entity
*/
public AssignmentResponse(Course course, Groups lecture, Groups classes) { public AssignmentResponse(Course course, Groups lecture, Groups classes) {
this.id = course.getId(); this.id = course.getId();
this.name = course.getName(); this.name = course.getName();
@ -22,6 +30,13 @@ public class AssignmentResponse {
this.classes = classes == null ? null : new GroupWithCapacityResponse(classes); this.classes = classes == null ? null : new GroupWithCapacityResponse(classes);
} }
/**
* @param course course entity
* @param lecture lecture Groups entity
* @param classes class Groups entity
* @param ammounts map with ammounts key - group id, value - ammounts of taken
* places
*/
public AssignmentResponse(Course course, Groups lecture, Groups classes, HashMap<Long, Integer> ammounts) { public AssignmentResponse(Course course, Groups lecture, Groups classes, HashMap<Long, Integer> ammounts) {
this.id = course.getId(); this.id = course.getId();
this.name = course.getName(); this.name = course.getName();
@ -29,28 +44,51 @@ public class AssignmentResponse {
this.classes = classes == null ? null : new GroupWithCapacityResponse(classes, ammounts.get(classes.getId())); this.classes = classes == null ? null : new GroupWithCapacityResponse(classes, ammounts.get(classes.getId()));
} }
/**
*
* @param course course entity
* @param group class/lecture entity
*/
public AssignmentResponse(Course course, Groups group) { public AssignmentResponse(Course course, Groups group) {
this(course, group.getType() == GroupType.LECTURE ? group : null, this(course, group.getType() == GroupType.LECTURE ? group : null,
group.getType() == GroupType.CLASS ? group : null); group.getType() == GroupType.CLASS ? group : null);
} }
/**
* @param course course entity
* @param group class/lecture entity
* @param ammounts map with ammounts key - group id, value - ammounts of taken
* places
*/
public AssignmentResponse(Course course, Groups group, HashMap<Long, Integer> ammounts) { public AssignmentResponse(Course course, Groups group, HashMap<Long, Integer> ammounts) {
this(course, group.getType() == GroupType.LECTURE ? group : null, this(course, group.getType() == GroupType.LECTURE ? group : null,
group.getType() == GroupType.CLASS ? group : null, ammounts); group.getType() == GroupType.CLASS ? group : null, ammounts);
} }
/**
* @return Lecture in api response forms
*/
public GroupWithCapacityResponse getLecture() { public GroupWithCapacityResponse getLecture() {
return this.lecture; return this.lecture;
} }
/**
* @return Class in api response forms
*/
public GroupWithCapacityResponse getClasses() { public GroupWithCapacityResponse getClasses() {
return this.classes; return this.classes;
} }
/**
* @return String course name
*/
public String getName() { public String getName() {
return this.name; return this.name;
} }
/**
* @return db assignment id
*/
public Long getId() { public Long getId() {
return this.id; return this.id;
} }

View File

@ -5,6 +5,9 @@ import com.plannaplan.entities.Commision;
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
/**
* Commision api response
*/
@ApiModel(description = "Response shows information about commision.", value = "CommisionResponse") @ApiModel(description = "Response shows information about commision.", value = "CommisionResponse")
public class CommisionResponse { public class CommisionResponse {
@ApiModelProperty(value = "ID created by database") @ApiModelProperty(value = "ID created by database")
@ -19,6 +22,9 @@ public class CommisionResponse {
@ApiModelProperty(value = "Timestamp where the user commit the commision") @ApiModelProperty(value = "Timestamp where the user commit the commision")
private String commisionDate; private String commisionDate;
/**
* @param commision commision to map to api response
*/
public CommisionResponse(Commision commision) { public CommisionResponse(Commision commision) {
this.id = commision.getId(); this.id = commision.getId();
this.commisionDate = commision.getCommisionDate().toString(); this.commisionDate = commision.getCommisionDate().toString();
@ -27,18 +33,30 @@ public class CommisionResponse {
: null; : null;
} }
/**
* @return get Commiter user as api response
*/
public UserResponse getCommiter() { public UserResponse getCommiter() {
return commiter; return commiter;
} }
/**
* @return get Owner user as api response
*/
public UserResponse getOwner() { public UserResponse getOwner() {
return owner; return owner;
} }
/**
* @return when commision was created string formated
*/
public String getCommisionDate() { public String getCommisionDate() {
return commisionDate; return commisionDate;
} }
/**
* @return db id
*/
public Long getId() { public Long getId() {
return id; return id;
} }

View File

@ -11,12 +11,18 @@ import com.plannaplan.entities.Commision;
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
/**
* Commision With Groups api Response. It extends CommisionResponse repsone
*/
@ApiModel(description = "Response shows information about commision and its groups.", value = "CommisionWithGroupsResponse") @ApiModel(description = "Response shows information about commision and its groups.", value = "CommisionWithGroupsResponse")
public class CommisionWithGroupsResponse extends CommisionResponse { public class CommisionWithGroupsResponse extends CommisionResponse {
@ApiModelProperty(value = "List of groups ids in databse that belongs to commision") @ApiModelProperty(value = "List of groups ids in databse that belongs to commision")
private List<Long> groups; private List<Long> groups;
/**
* @param commision commision to map to api response
*/
public CommisionWithGroupsResponse(Commision commision) { public CommisionWithGroupsResponse(Commision commision) {
super(commision); super(commision);
this.groups = commision.getAssignments().stream().filter(Objects::nonNull) this.groups = commision.getAssignments().stream().filter(Objects::nonNull)
@ -29,6 +35,9 @@ public class CommisionWithGroupsResponse extends CommisionResponse {
}).collect(Collectors.toList()); }).collect(Collectors.toList());
} }
/**
* @return lsit of fetured groups ids
*/
public List<Long> getGroups() { public List<Long> getGroups() {
return groups; return groups;
} }

View File

@ -5,21 +5,36 @@ import java.util.List;
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModel;
/**
* Course respose with all realted groups as api response. Alse needs to specify
* what type of Groups api response will be kept here. For excmaple it can be
* <b> GroupDefaultRespnse </b>
*/
@ApiModel(description = "Response shows information about groups to given course.", value = "CourseWithGroupsResponse") @ApiModel(description = "Response shows information about groups to given course.", value = "CourseWithGroupsResponse")
public class CourseWithGroupsResponse <T> { public class CourseWithGroupsResponse<T> {
private List<T> lectures = new ArrayList<>(); private List<T> lectures = new ArrayList<>();
private List<T> classes = new ArrayList<>(); private List<T> classes = new ArrayList<>();
public CourseWithGroupsResponse(List<T> classes, List<T> lectures ){ /**
* @param classes realted classes Groups instance
* @param lectures realted lectures Groups instance
*/
public CourseWithGroupsResponse(List<T> classes, List<T> lectures) {
this.lectures = lectures; this.lectures = lectures;
this.classes = classes; this.classes = classes;
} }
/**
* @return realted classes Groups instance
*/
public List<T> getClasses() { public List<T> getClasses() {
return this.classes; return this.classes;
} }
/**
* @return realted lectures Groups instance
*/
public List<T> getLectures() { public List<T> getLectures() {
return this.lectures; return this.lectures;
} }

View File

@ -5,9 +5,21 @@ import com.plannaplan.responses.models.abstracts.CoursesResponse;
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModel;
/**
* Courses Default Api Response. It extends abstract response - CoursesResponse.
* It was one of first repsones created in system. Later we resigned from
* asbstract and used settig
* <code>spring.jackson.default-property-inclusion = NON_NULL</code> in
* properties instead.
*/
@ApiModel(description = "Response shows information about course.", value = "CoursesDefaultResponse") @ApiModel(description = "Response shows information about course.", value = "CoursesDefaultResponse")
public class CoursesDefaultResponse extends CoursesResponse { public class CoursesDefaultResponse extends CoursesResponse {
/**
* create new instance
*
* @param course course to map to api response
*/
public CoursesDefaultResponse(Course course) { public CoursesDefaultResponse(Course course) {
super(course); super(course);
} }

View File

@ -9,12 +9,24 @@ import com.plannaplan.types.GroupType;
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModel;
/**
* Courses With Groups Api Response . It extends abstract response -
* CoursesResponse. It was one of first repsones created in system. Later we
* resigned from asbstract and used settig
* <code>spring.jackson.default-property-inclusion = NON_NULL</code> in
* properties instead.
*/
@ApiModel(description = "Response shows information about groups to given course.", value = "CoursesWithGroupsResponse") @ApiModel(description = "Response shows information about groups to given course.", value = "CoursesWithGroupsResponse")
public class CoursesWithGroupsResponse extends CoursesResponse { public class CoursesWithGroupsResponse extends CoursesResponse {
private List<GroupWithCapacityResponse> lectures = new ArrayList<>(); private List<GroupWithCapacityResponse> lectures = new ArrayList<>();
private List<GroupWithCapacityResponse> classes = new ArrayList<>(); private List<GroupWithCapacityResponse> classes = new ArrayList<>();
/**
* create new instance
*
* @param course course to map to api response
*/
public CoursesWithGroupsResponse(Course course) { public CoursesWithGroupsResponse(Course course) {
super(course); super(course);
course.getGroups().stream().forEach(group -> { course.getGroups().stream().forEach(group -> {
@ -26,6 +38,12 @@ public class CoursesWithGroupsResponse extends CoursesResponse {
}); });
} }
/**
*
* @param course course to map to api response
* @param lectures list of api resposnes of lectures
* @param classes list of api resposnes of classes
*/
public CoursesWithGroupsResponse(Course course, List<GroupWithCapacityResponse> lectures, public CoursesWithGroupsResponse(Course course, List<GroupWithCapacityResponse> lectures,
List<GroupWithCapacityResponse> classes) { List<GroupWithCapacityResponse> classes) {
super(course); super(course);
@ -33,10 +51,16 @@ public class CoursesWithGroupsResponse extends CoursesResponse {
this.classes = classes; this.classes = classes;
} }
/**
* @return list of api resposnes of classes
*/
public List<GroupWithCapacityResponse> getClasses() { public List<GroupWithCapacityResponse> getClasses() {
return this.classes; return this.classes;
} }
/**
* @return list of api resposnes of lectures
*/
public List<GroupWithCapacityResponse> getLectures() { public List<GroupWithCapacityResponse> getLectures() {
return this.lectures; return this.lectures;
} }

View File

@ -2,35 +2,72 @@ package com.plannaplan.responses.models;
import com.plannaplan.entities.Exchange; import com.plannaplan.entities.Exchange;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* Exchange proposal api repsonse
*/
@ApiModel(description = "Response shows information about user exchanges", value = "CourseWithGroupsResponse")
public class ExchangeResponse { public class ExchangeResponse {
@ApiModelProperty(value = "Database id")
private Long id; private Long id;
@ApiModelProperty(value = "Assignmetn that user want to trade")
private GroupDefaultResponse ownedAssignment; private GroupDefaultResponse ownedAssignment;
@ApiModelProperty(value = "Group that user want to get")
private GroupDefaultResponse desiredGroup; private GroupDefaultResponse desiredGroup;
public ExchangeResponse(Exchange exchange){ /**
* creat new instance
*
* @param exchange entity to map to api repsone
*/
public ExchangeResponse(Exchange exchange) {
this.id = exchange.getId(); this.id = exchange.getId();
this.ownedAssignment = new GroupDefaultResponse(exchange.getOwnedAssignment().getGroup()); this.ownedAssignment = new GroupDefaultResponse(exchange.getOwnedAssignment().getGroup());
this.desiredGroup = new GroupDefaultResponse(exchange.getDesiredAssignment()); this.desiredGroup = new GroupDefaultResponse(exchange.getDesiredAssignment());
} }
/**
* @return get api respondse of wanted byt user group
*/
public GroupDefaultResponse getDesiredGroup() { public GroupDefaultResponse getDesiredGroup() {
return desiredGroup; return desiredGroup;
} }
/**
* @param desiredGroup set api respondse of wanted byt user group
*/
public void setDesiredGroup(GroupDefaultResponse desiredGroup) { public void setDesiredGroup(GroupDefaultResponse desiredGroup) {
this.desiredGroup = desiredGroup; this.desiredGroup = desiredGroup;
} }
/**
* @return get api respondse of owned user group
*/
public GroupDefaultResponse getOwnedAssignment() { public GroupDefaultResponse getOwnedAssignment() {
return ownedAssignment; return ownedAssignment;
} }
/**
* @param ownedAssignment set api respondse of owned user group
*/
public void setOwnedAssignment(GroupDefaultResponse ownedAssignment) { public void setOwnedAssignment(GroupDefaultResponse ownedAssignment) {
this.ownedAssignment = ownedAssignment; this.ownedAssignment = ownedAssignment;
} }
/**
* @return database id
*/
public Long getId() { public Long getId() {
return id; return id;
} }
/**
* @param id set database id
*/
public void setId(Long id) { public void setId(Long id) {
this.id = id; this.id = id;
} }
} }

View File

@ -8,6 +8,9 @@ import com.plannaplan.types.GroupType;
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
/**
* Default api response for Groups entity
*/
@JsonInclude(JsonInclude.Include.NON_NULL) @JsonInclude(JsonInclude.Include.NON_NULL)
@ApiModel(description = "Response shows information about given group.", value = "GroupDefaultResponse") @ApiModel(description = "Response shows information about given group.", value = "GroupDefaultResponse")
public class GroupDefaultResponse { public class GroupDefaultResponse {
@ -36,6 +39,11 @@ public class GroupDefaultResponse {
@ApiModelProperty(value = "Value shows how many places is already taken by other students.") @ApiModelProperty(value = "Value shows how many places is already taken by other students.")
private Integer takenPlaces; private Integer takenPlaces;
/**
* creat new entity
*
* @param group entity to map to api response
*/
public GroupDefaultResponse(Groups group) { public GroupDefaultResponse(Groups group) {
this.id = group.getId() != null ? group.getId() : null; this.id = group.getId() != null ? group.getId() : null;
this.day = group.getDay() != null ? group.getDay().label : -1; this.day = group.getDay() != null ? group.getDay().label : -1;
@ -46,43 +54,77 @@ public class GroupDefaultResponse {
this.type = group.getType() != null ? group.getType() : null; this.type = group.getType() != null ? group.getType() : null;
} }
/**
*
* @param group entity to map to api response
* @param takenPlaces ammount of taken places for group by other users
*/
public GroupDefaultResponse(Groups group, int takenPlaces) { public GroupDefaultResponse(Groups group, int takenPlaces) {
this(group); this(group);
this.takenPlaces = takenPlaces; this.takenPlaces = takenPlaces;
} }
/**
* creat new entity
*
* @param assignment entity to map to api response
*/
public GroupDefaultResponse(Assignment assignment) { public GroupDefaultResponse(Assignment assignment) {
this(assignment.getGroup()); this(assignment.getGroup());
} }
/**
* @return what typew of group is this (lecture or class)
*/
public GroupType getType() { public GroupType getType() {
return type; return type;
} }
/**
* @return room where classes will take place
*/
public String getRoom() { public String getRoom() {
return room; return room;
} }
/**
* @return name of group lecturer
*/
public String getLecturer() { public String getLecturer() {
return lecturer; return lecturer;
} }
/**
* @return time when group is scheduled on
*/
public String getTime() { public String getTime() {
return time; return time;
} }
/**
* @return time when class ends
*/
public String getEndTime() { public String getEndTime() {
return endTime; return endTime;
} }
/**
* @return int what day is it. 0-6 (Monday - Sunday)
*/
public int getDay() { public int getDay() {
return day; return day;
} }
/**
* @return db id
*/
public Long getId() { public Long getId() {
return id; return id;
} }
/**
* @return ammount of taken places for group by other users
*/
public Integer getTakenPlaces() { public Integer getTakenPlaces() {
return this.takenPlaces; return this.takenPlaces;
} }

View File

@ -4,29 +4,57 @@ import com.plannaplan.entities.Assignment;
import com.plannaplan.entities.Groups; import com.plannaplan.entities.Groups;
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModel;
/**
* Group api response featuring group capacity
*/
@ApiModel(description = "Response shows information about group with included capacity.", value = "GroupWithCapacityResponse") @ApiModel(description = "Response shows information about group with included capacity.", value = "GroupWithCapacityResponse")
public class GroupWithCapacityResponse extends GroupDefaultResponse { public class GroupWithCapacityResponse extends GroupDefaultResponse {
private int capacity; private int capacity;
/**
* create new instance
*
* @param group entity to map to api response
*/
public GroupWithCapacityResponse(Groups group) { public GroupWithCapacityResponse(Groups group) {
super(group); super(group);
this.capacity = group.getCapacity(); this.capacity = group.getCapacity();
} }
/**
* create new instance
*
* @param group entity to map to api response
* @param takenPlaces group taken places
*/
public GroupWithCapacityResponse(Groups group, int takenPlaces) { public GroupWithCapacityResponse(Groups group, int takenPlaces) {
super(group, takenPlaces); super(group, takenPlaces);
this.capacity = group.getCapacity(); this.capacity = group.getCapacity();
} }
/**
* create new instance
*
* @param assignment entity to map to api response
*/
public GroupWithCapacityResponse(Assignment assignment) { public GroupWithCapacityResponse(Assignment assignment) {
this(assignment.getGroup()); this(assignment.getGroup());
} }
/**
* create new instance
*
* @param assignment entity to map to api response
* @param takenPlaces group taken places
*/
public GroupWithCapacityResponse(Assignment assignment, int takenPlaces) { public GroupWithCapacityResponse(Assignment assignment, int takenPlaces) {
this(assignment.getGroup(), takenPlaces); this(assignment.getGroup(), takenPlaces);
} }
/**
* @return group taken places
*/
public int getCapacity() { public int getCapacity() {
return capacity; return capacity;
} }

View File

@ -5,6 +5,9 @@ import com.plannaplan.entities.User;
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
/**
* Response to show after successfully login cation
*/
@ApiModel(description = "Response shows information about logged user.", value = "TokenResponse") @ApiModel(description = "Response shows information about logged user.", value = "TokenResponse")
public class TokenResponse { public class TokenResponse {
@ApiModelProperty(value = "user token used to verify requests") @ApiModelProperty(value = "user token used to verify requests")
@ -18,6 +21,9 @@ public class TokenResponse {
@ApiModelProperty(value = "user unviersity email") @ApiModelProperty(value = "user unviersity email")
private String email; private String email;
/**
* @param user user to be mapped to api response
*/
public TokenResponse(User user) { public TokenResponse(User user) {
this.id = user.getId(); this.id = user.getId();
this.authorityRole = user.getRole().toString(); this.authorityRole = user.getRole().toString();
@ -26,22 +32,37 @@ public class TokenResponse {
this.refreshToken = user.getRefreshToken(); this.refreshToken = user.getRefreshToken();
} }
/**
* @return user email
*/
public String getEmail() { public String getEmail() {
return email; return email;
} }
/**
* @return user role in system
*/
public String getAuthorityRole() { public String getAuthorityRole() {
return authorityRole; return authorityRole;
} }
/**
* @return db id
*/
public Long getId() { public Long getId() {
return id; return id;
} }
/**
* @return user token to authorize other requests
*/
public String getToken() { public String getToken() {
return token; return token;
} }
/**
* @return user refresh token
*/
public String getRefreshToken() { public String getRefreshToken() {
return this.refreshToken; return this.refreshToken;
} }

View File

@ -4,6 +4,9 @@ import com.plannaplan.entities.User;
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModel;
/**
* Model for api response for user serach results.
*/
@ApiModel(description = "Response shows information about user.", value = "UserResponse") @ApiModel(description = "Response shows information about user.", value = "UserResponse")
public class UserResponse { public class UserResponse {
@ -12,6 +15,9 @@ public class UserResponse {
private String surname; private String surname;
private String email; private String email;
/**
* @param user entity to be mapped to api response
*/
public UserResponse(User user) { public UserResponse(User user) {
this.id = user.getId(); this.id = user.getId();
this.name = user.getName() != null ? user.getName() : ""; this.name = user.getName() != null ? user.getName() : "";
@ -19,18 +25,30 @@ public class UserResponse {
this.email = user.getEmail(); this.email = user.getEmail();
} }
/**
* @return user email
*/
public String getEmail() { public String getEmail() {
return email; return email;
} }
/**
* @return user surname
*/
public String getSurname() { public String getSurname() {
return surname; return surname;
} }
/**
* @return user name
*/
public String getName() { public String getName() {
return name; return name;
} }
/**
* @return db id
*/
public Long getId() { public Long getId() {
return id; return id;
} }

View File

@ -2,20 +2,34 @@ package com.plannaplan.responses.models.abstracts;
import com.plannaplan.entities.Course; import com.plannaplan.entities.Course;
/**
* Course entity api response
*/
public abstract class CoursesResponse { public abstract class CoursesResponse {
private Long id; private Long id;
private String name; private String name;
/**
* create instance
*
* @param course entity to map to api response
*/
public CoursesResponse(Course course) { public CoursesResponse(Course course) {
this.id = course.getId() != null ? course.getId() : null; this.id = course.getId() != null ? course.getId() : null;
this.name = course.getName() != null ? course.getName() : ""; this.name = course.getName() != null ? course.getName() : "";
} }
/**
* @return course name
*/
public String getName() { public String getName() {
return name; return name;
} }
/**
* @return db id
*/
public Long getId() { public Long getId() {
return id; return id;
} }

View File

@ -0,0 +1,6 @@
/**
* Abstract api responses
*
* @since 1.0
*/
package com.plannaplan.responses.models.abstracts;

View File

@ -0,0 +1,7 @@
/**
* Provides models of all possible api responses. Convention for naming this
* class is EntityModifierRepsone. For Example CourseDefaultResponse
*
* @since 1.0
*/
package com.plannaplan.responses.models;

View File

@ -0,0 +1,6 @@
/**
* Contains packeges realted to creating api responses
*
* @since 1.0
*/
package com.plannaplan.responses;

View File

@ -17,6 +17,9 @@ import org.springframework.security.web.util.matcher.RequestMatcher;
import static org.springframework.http.HttpHeaders.AUTHORIZATION; import static org.springframework.http.HttpHeaders.AUTHORIZATION;
/**
* Spring authentication filter class
*/
public class AuthenticationFilter extends AbstractAuthenticationProcessingFilter { public class AuthenticationFilter extends AbstractAuthenticationProcessingFilter {
AuthenticationFilter(final RequestMatcher requiresAuth) { AuthenticationFilter(final RequestMatcher requiresAuth) {

View File

@ -16,6 +16,9 @@ import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
/**
* Spring authentication provider
*/
@Component @Component
public class AuthenticationProvider extends AbstractUserDetailsAuthenticationProvider { public class AuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {
@ -25,8 +28,6 @@ public class AuthenticationProvider extends AbstractUserDetailsAuthenticationPro
@Override @Override
protected void additionalAuthenticationChecks(UserDetails userDetails, protected void additionalAuthenticationChecks(UserDetails userDetails,
UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
// is being done in other task
} }
@Override @Override

View File

@ -6,6 +6,9 @@ import com.plannaplan.types.UserRoles;
import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.GrantedAuthority;
/**
* Users Roles for spring app
*/
public enum AuthorityRoles implements GrantedAuthority { public enum AuthorityRoles implements GrantedAuthority {
STUDENT("ROLE_STUDENT"), DEANERY("ROLE_DEANERY"), ADMIN("ROLE_ADMIN"), TEST_USER("ROLE_TESTUSER"); STUDENT("ROLE_STUDENT"), DEANERY("ROLE_DEANERY"), ADMIN("ROLE_ADMIN"), TEST_USER("ROLE_TESTUSER");
@ -20,6 +23,12 @@ public enum AuthorityRoles implements GrantedAuthority {
return this.role; return this.role;
} }
/**
* map buisness logic UserRoles enum to spring enum
*
* @param role buisness logic enum
* @return restservice AuthorityRoles enum
*/
public static final Optional<AuthorityRoles> getAuthorityRole(UserRoles role) { public static final Optional<AuthorityRoles> getAuthorityRole(UserRoles role) {
switch (role) { switch (role) {
case ADMIN: case ADMIN:

View File

@ -16,9 +16,11 @@ import org.springframework.http.HttpStatus;
import org.springframework.security.web.authentication.AnonymousAuthenticationFilter; import org.springframework.security.web.authentication.AnonymousAuthenticationFilter;
import org.springframework.security.web.authentication.HttpStatusEntryPoint; import org.springframework.security.web.authentication.HttpStatusEntryPoint;
/**
* Spring config class for security
*/
@Configuration @Configuration
@EnableWebSecurity @EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private static final RequestMatcher PROTECTED_URLS = new OrRequestMatcher(new AntPathRequestMatcher("/api/**")); private static final RequestMatcher PROTECTED_URLS = new OrRequestMatcher(new AntPathRequestMatcher("/api/**"));

View File

@ -1,18 +1,35 @@
package com.plannaplan.security.cas; package com.plannaplan.security.cas;
/**
* Model to keep data from Cas response. It's important to remember that wee
* need to register our domain name in CAS in order to get this data. Otherwise
* CAS will retuned what user typed as login.
*/
public class CasUserIdentity { public class CasUserIdentity {
private String usosId; private String usosId;
private String email; private String email;
public CasUserIdentity(String usosId, String email){ /**
* creates new instance
*
* @param usosId usosId retured from CAS
* @param email emial returned from CAS
*/
public CasUserIdentity(String usosId, String email) {
this.usosId = usosId; this.usosId = usosId;
this.email = email; this.email = email;
} }
/**
* @return string with usosid
*/
public String getUsosId() { public String getUsosId() {
return usosId; return usosId;
} }
/**
* @return string with email
*/
public String getEmail() { public String getEmail() {
return email; return email;
} }

View File

@ -1,9 +1,9 @@
package com.plannaplan.security.cas; package com.plannaplan.security.cas;
public class CasValidationExcepiton extends RuntimeException { /**
/** * Exception to throw when cas didn't validate provided ticket
*
*/ */
public class CasValidationExcepiton extends RuntimeException {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public CasValidationExcepiton(String s) { public CasValidationExcepiton(String s) {

View File

@ -1,6 +1,17 @@
package com.plannaplan.security.cas; package com.plannaplan.security.cas;
/**
* We can authorize in different contexts. For example if we rgister our domain
* we will get more info than on localhost. This abstraction let's us handle
* both cases based on spring profile
*/
public interface CasValidator { public interface CasValidator {
/**
* validate ticket (should be provided in costructor or by setter)
*
* @return CasUserIdentity instance with values from response or null if
* validation failed
*/
CasUserIdentity validate(); CasUserIdentity validate();
} }

View File

@ -4,6 +4,10 @@ import org.jasig.cas.client.validation.Assertion;
import org.jasig.cas.client.validation.Cas20ServiceTicketValidator; import org.jasig.cas.client.validation.Cas20ServiceTicketValidator;
import org.jasig.cas.client.validation.TicketValidationException; import org.jasig.cas.client.validation.TicketValidationException;
/**
* Cas Validator for UAM with domain registered for email and usosid as a
* repsonse
*/
public class CustomUAMCasValidator implements CasValidator { public class CustomUAMCasValidator implements CasValidator {
private static String CAS_URL = "https://cas.amu.edu.pl/cas"; private static String CAS_URL = "https://cas.amu.edu.pl/cas";
private static String EMAIL_FIELD = "mail"; private static String EMAIL_FIELD = "mail";
@ -11,31 +15,36 @@ public class CustomUAMCasValidator implements CasValidator {
private String service; private String service;
private String ticket; private String ticket;
public CustomUAMCasValidator(String service, String ticket){ /**
* craste new instance
*
* @param service string with url of our service from where request began
* @param ticket ticket returned after user provided creeds on cas page
*/
public CustomUAMCasValidator(String service, String ticket) {
this.service = service; this.service = service;
this.ticket = ticket; this.ticket = ticket;
} }
@Override @Override
public CasUserIdentity validate() { public CasUserIdentity validate() {
/*
* TO DO
* Dodać case z CAS10/CAS20/CAS30
*/
final Cas20ServiceTicketValidator validator = new Cas20ServiceTicketValidator(CustomUAMCasValidator.CAS_URL); final Cas20ServiceTicketValidator validator = new Cas20ServiceTicketValidator(CustomUAMCasValidator.CAS_URL);
try { try {
final Assertion assertion = validator.validate(this.ticket, this.service); final Assertion assertion = validator.validate(this.ticket, this.service);
if (assertion == null) { if (assertion == null) {
throw new CasValidationExcepiton("Validation failed. Assertion could not be retrieved for ticket " + ""); throw new CasValidationExcepiton(
"Validation failed. Assertion could not be retrieved for ticket " + "");
} }
final String usosid = assertion.getPrincipal().getAttributes().get(CustomUAMCasValidator.USOS_ID).toString(); final String usosid = assertion.getPrincipal().getAttributes().get(CustomUAMCasValidator.USOS_ID)
.toString();
final String mail = assertion.getPrincipal().getAttributes().get(CustomUAMCasValidator.EMAIL_FIELD).toString(); final String mail = assertion.getPrincipal().getAttributes().get(CustomUAMCasValidator.EMAIL_FIELD)
.toString();
return new CasUserIdentity(usosid,mail); return new CasUserIdentity(usosid, mail);
} catch (TicketValidationException e) { } catch (TicketValidationException e) {
e.printStackTrace(); e.printStackTrace();

View File

@ -9,12 +9,21 @@ import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
/**
* Cas Validator for localhost and not registered dopmains
*/
public class DefaultUAMCasValidator implements CasValidator { public class DefaultUAMCasValidator implements CasValidator {
private static String CAS_URL = "https://cas.amu.edu.pl/cas"; private static String CAS_URL = "https://cas.amu.edu.pl/cas";
private final CloseableHttpClient httpClient = HttpClients.createDefault(); private final CloseableHttpClient httpClient = HttpClients.createDefault();
private String service; private String service;
private String ticket; private String ticket;
/**
* craste new instance
*
* @param service string with url of our service from where request began
* @param ticket ticket returned after user provided creeds on cas page
*/
public DefaultUAMCasValidator(String service, String ticket) { public DefaultUAMCasValidator(String service, String ticket) {
this.service = service; this.service = service;
this.ticket = ticket; this.ticket = ticket;
@ -39,7 +48,7 @@ public class DefaultUAMCasValidator implements CasValidator {
} }
String res = result.substring(result.indexOf('\n') + 1); String res = result.substring(result.indexOf('\n') + 1);
return new CasUserIdentity(null,res); return new CasUserIdentity(null, res);
} }
} }

View File

@ -0,0 +1,6 @@
/**
* All calsses realted to authorizing user with CAS system.
*
* @since 1.0
*/
package com.plannaplan.security.cas;

View File

@ -0,0 +1,7 @@
/**
* All classes realted to seciuirty includin spring secuirty and cas
* authentication
*
* @since 1.0
*/
package com.plannaplan.security;

View File

@ -14,6 +14,21 @@
"name": "plannaplan.email", "name": "plannaplan.email",
"type": "java.lang.String", "type": "java.lang.String",
"description": "Email from which app sends message" "description": "Email from which app sends message"
},
{
"name": "plannaplan.apiurl",
"type": "java.lang.String",
"description": "Url to usos api endpoints"
},
{
"name": "plannaplan.apikey",
"type": "java.lang.String",
"description": "Api consumer key"
},
{
"name": "plannaplan.apisecret",
"type": "java.lang.String",
"description": "Api consumer secret"
} }
] ]
} }

View File

@ -67,14 +67,14 @@ public class CommisionControllerTest extends AbstractControllerTest {
} }
@Test @Test
public void shouldReturnOkAddingCommision() throws Exception { public void shouldFailAddingCommisionDueToWrongTour() throws Exception {
this.checkUsers(); this.checkUsers();
final User user = this.service.checkForUser(TEST_COMMISIONS_STUDENT_EMAIL, null); final User user = this.service.checkForUser(TEST_COMMISIONS_STUDENT_EMAIL, null);
final String token = this.service.login(user).getToken(); final String token = this.service.login(user).getToken();
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build(); MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
mockMvc.perform(post(ADD_COMMISION_ENDPOINT).header("Authorization", "Bearer " + token) mockMvc.perform(post(ADD_COMMISION_ENDPOINT).header("Authorization", "Bearer " + token)
.contentType(APPLICATION_JSON_UTF8).content("[]")).andExpect(status().isOk()); .contentType(APPLICATION_JSON_UTF8).content("[]")).andExpect(status().is4xxClientError());
} }
@Test @Test
@ -95,15 +95,16 @@ public class CommisionControllerTest extends AbstractControllerTest {
} }
@Test @Test
public void shouldAddCommisionWithSelfIdPrivided() throws Exception { public void shouldFailAddingCommisionWithSelfIdPrividedDueToWrongTour() throws Exception {
this.checkUsers(); this.checkUsers();
final User user = this.service.checkForUser(TEST_COMMISIONS_STUDENT_EMAIL, null); final User user = this.service.checkForUser(TEST_COMMISIONS_STUDENT_EMAIL, null);
final String token = this.service.login(user).getToken(); final String token = this.service.login(user).getToken();
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build(); MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
mockMvc.perform(post(ADD_COMMISION_ENDPOINT + "/" + CommisionControllerTest.user.getId().toString()) mockMvc.perform(post(ADD_COMMISION_ENDPOINT + "/" + CommisionControllerTest.user.getId().toString())
.header("Authorization", "Bearer " + token).contentType(APPLICATION_JSON_UTF8).content("[]")) .header("Authorization", "Bearer " + token).contentType(APPLICATION_JSON_UTF8).content("[]"))
.andExpect(status().isOk()); .andExpect(status().is4xxClientError());
} }
@Test @Test