1

Merge branch 'master' into refactor-controllerService

# Conflicts:
#	src/main/java/mops/gruppen2/service/ControllerService.java
This commit is contained in:
AndiBuls
2020-03-25 16:45:01 +01:00
19 changed files with 831 additions and 398 deletions

View File

@ -86,8 +86,6 @@ dependencies {
}
testImplementation 'org.springframework.security:spring-security-test'
testImplementation 'com.tngtech.archunit:archunit-junit5:0.13.1'
implementation 'junit:junit:4.12'
implementation 'junit:junit:4.12'
}
test {

View File

@ -1,38 +1,20 @@
package mops.gruppen2.controller;
import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException;
import mops.gruppen2.domain.Group;
import mops.gruppen2.domain.Role;
import mops.gruppen2.domain.User;
import mops.gruppen2.domain.Visibility;
import mops.gruppen2.domain.exception.EventException;
import mops.gruppen2.domain.exception.GroupFullException;
import mops.gruppen2.domain.exception.GroupNotFoundException;
import mops.gruppen2.domain.exception.NoAccessException;
import mops.gruppen2.domain.exception.NoAdminAfterActionException;
import mops.gruppen2.domain.exception.PageNotFoundException;
import mops.gruppen2.domain.exception.UserAlreadyExistsException;
import mops.gruppen2.domain.exception.WrongFileException;
import mops.gruppen2.security.Account;
import mops.gruppen2.service.ControllerService;
import mops.gruppen2.service.CsvService;
import mops.gruppen2.service.GroupService;
import mops.gruppen2.service.KeyCloakService;
import mops.gruppen2.service.UserService;
import mops.gruppen2.service.*;
import org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.annotation.SessionScope;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.security.RolesAllowed;
import javax.servlet.http.HttpServletRequest;
import java.io.CharConversionException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@ -47,12 +29,14 @@ public class WebController {
private final GroupService groupService;
private final UserService userService;
private final ControllerService controllerService;
private final ValidationService validationService;
public WebController(KeyCloakService keyCloakService, GroupService groupService, UserService userService, ControllerService controllerService) {
public WebController(KeyCloakService keyCloakService, GroupService groupService, UserService userService, ControllerService controllerService, ValidationService validationService) {
this.keyCloakService = keyCloakService;
this.groupService = groupService;
this.userService = userService;
this.controllerService = controllerService;
this.validationService = validationService;
}
/**
@ -96,7 +80,11 @@ public class WebController {
Account account = keyCloakService.createAccountFromPrincipal(token);
UUID parentUUID = controllerService.getUUID(parent);
controllerService.createOrga(account, title, description, visibility, lecture, maxInfiniteUsers, userMaximum, parentUUID, file);
List<User> userList = new ArrayList<>();
validationService.checkFields(description, title, userMaximum, maxInfiniteUsers);
Group group = userService.getGroupById(controllerService.createOrga(account, title, description, visibility, lecture, maxInfiniteUsers, userMaximum, parentUUID));
userList = validationService.checkFile(file, userList, group.getId().toString(), group, account);
controllerService.addUserList(userList, group.getId());
return "redirect:/gruppen2/";
}
@ -121,6 +109,7 @@ public class WebController {
Account account = keyCloakService.createAccountFromPrincipal(token);
UUID parentUUID = controllerService.getUUID(parent);
validationService.checkFields(description, title, userMaximum, maxInfiniteUsers);
controllerService.createGroup(account, title, description, visibility, maxInfiniteUsers, userMaximum, parentUUID);
return "redirect:/gruppen2/";
}
@ -133,17 +122,7 @@ public class WebController {
Account account = keyCloakService.createAccountFromPrincipal(token);
List<User> userList = new ArrayList<>();
Group group = userService.getGroupById(UUID.fromString(groupId));
if (!file.isEmpty()) {
try {
userList = CsvService.read(file.getInputStream());
if (userList.size() + group.getMembers().size() > group.getUserMaximum()) {
controllerService.updateMaxUser(account, UUID.fromString(groupId), (long) userList.size() + group.getMembers().size());
}
} catch (UnrecognizedPropertyException | CharConversionException ex) {
throw new WrongFileException(file.getOriginalFilename());
}
}
userList = validationService.checkFile(file, userList, groupId, group, account);
UUID groupUUID = controllerService.getUUID(groupId);
controllerService.addUserList(userList, groupUUID);
return "redirect:/gruppen2/details/members/" + groupId;
@ -155,13 +134,11 @@ public class WebController {
Account account = keyCloakService.createAccountFromPrincipal(token);
User user = new User(account.getName(), account.getGivenname(), account.getFamilyname(), account.getEmail());
Group group = userService.getGroupById(UUID.fromString(groupId));
validationService.checkIfAdmin(group, user);
model.addAttribute("account", account);
UUID parentId = group.getParent();
Group parent = new Group();
if (!group.getMembers().contains(user)) {
if (group.getVisibility() == Visibility.PRIVATE) {
throw new NoAccessException("Die Gruppe ist privat");
}
if (!validationService.checkIfUserInGroup(group, user)) {
model.addAttribute("group", group);
model.addAttribute("parentId", parentId);
model.addAttribute("parent", parent);
@ -184,9 +161,10 @@ public class WebController {
@RequestParam("groupId") String groupId) throws EventException {
Account account = keyCloakService.createAccountFromPrincipal(token);
controllerService.updateTitle(account, UUID.fromString(groupId), title);
controllerService.updateDescription(account, UUID.fromString(groupId), description);
User user = new User(account.getName(), account.getGivenname(), account.getFamilyname(), account.getEmail());
Group group = userService.getGroupById(UUID.fromString(groupId));
validationService.checkIfAdmin(group, user);
validationService.checkTitleAndDescription(title, description, account, groupId);
return "redirect:/gruppen2/details/" + groupId;
}
@ -196,12 +174,8 @@ public class WebController {
Model model,
@RequestParam(value = "suchbegriff", required = false) String search) throws EventException {
Account account = keyCloakService.createAccountFromPrincipal(token);
List<Group> groups = new ArrayList<>();
if (search != null) {
groups = groupService.findGroupWith(search, account);
}
groups = validationService.checkSearch(search, groups, account);
model.addAttribute("account", account);
model.addAttribute("gruppen", groups);
return "search";
@ -215,28 +189,18 @@ public class WebController {
Group group = userService.getGroupById(UUID.fromString(groupId));
Account account = keyCloakService.createAccountFromPrincipal(token);
User user = new User(account.getName(), account.getGivenname(), account.getFamilyname(), account.getEmail());
UUID parentId = group.getParent();
Group parent = new Group();
if (group.getTitle() == null) {
throw new GroupNotFoundException("@details");
}
validationService.checkGroup(group.getTitle());
Group parent = validationService.checkParent(parentId);
if (!group.getMembers().contains(user)) {
if (group.getVisibility() == Visibility.PRIVATE) {
throw new NoAccessException("Die Gruppe ist privat");
}
if (!validationService.checkIfUserInGroup(group, user)) {
model.addAttribute("group", group);
model.addAttribute("parentId", parentId);
model.addAttribute("parent", parent);
return "detailsNoMember";
}
if (!controllerService.idIsEmpty(parentId)) {
parent = userService.getGroupById(parentId);
}
model.addAttribute("parentId", parentId);
model.addAttribute("parent", parent);
model.addAttribute("group", group);
@ -246,7 +210,6 @@ public class WebController {
String URL = request.getRequestURL().toString();
String serverURL = URL.substring(0, URL.indexOf("gruppen2/"));
model.addAttribute("link", serverURL + "gruppen2/acceptinvite/" + groupId);
return "detailsMember";
@ -260,14 +223,9 @@ public class WebController {
Account account = keyCloakService.createAccountFromPrincipal(token);
User user = new User(account.getName(), account.getGivenname(), account.getFamilyname(), account.getEmail());
Group group = userService.getGroupById(UUID.fromString(groupId));
if (group.getMembers().contains(user)) {
throw new UserAlreadyExistsException("Du bist bereits in dieser Gruppe.");
}
validationService.checkIfUserInGroupJoin(group, user);
validationService.checkIfGroupFull(group);
controllerService.addUser(account, UUID.fromString(groupId));
if (group.getUserMaximum() < group.getMembers().size()) {
throw new GroupFullException("Du kannst der Gruppe daher leider nicht beitreten.");
}
//controllerService.addUser(account, groupId);
return "redirect:/gruppen2/";
}
@ -279,21 +237,15 @@ public class WebController {
model.addAttribute("account", keyCloakService.createAccountFromPrincipal(token));
Group group = userService.getGroupById(UUID.fromString(groupId));
UUID parentId = group.getParent();
Group parent = new Group();
Group parent = validationService.checkParent(parentId);
if (!controllerService.idIsEmpty(parentId)) {
parent = userService.getGroupById(parentId);
}
if (group.getUserMaximum() > group.getMembers().size()) {
validationService.checkIfGroupFull(group);
model.addAttribute("group", group);
model.addAttribute("parentId", parentId);
model.addAttribute("parent", parent);
return "detailsNoMember";
}
throw new GroupNotFoundException("@search");
}
@RolesAllowed({"ROLE_orga", "ROLE_studentin", "ROLE_actuator"})
@GetMapping("/acceptinvite/{groupId}")
@ -301,12 +253,10 @@ public class WebController {
Model model, @PathVariable String groupId) throws EventException {
model.addAttribute("account", keyCloakService.createAccountFromPrincipal(token));
Group group = userService.getGroupById(UUID.fromString(groupId));
if (group != null) {
validationService.checkGroup(group.getTitle());
model.addAttribute("group", group);
return "redirect:/gruppen2/detailsSearch?id=" + group.getId();
}
throw new GroupNotFoundException("@accept");
}
@RolesAllowed({"ROLE_orga", "ROLE_studentin", "ROLE_actuator"})
@PostMapping("/leaveGroup")
@ -316,11 +266,7 @@ public class WebController {
User user = new User(account.getName(), account.getGivenname(), account.getFamilyname(), account.getEmail());
controllerService.passIfLastAdmin(account, UUID.fromString(groupId));
controllerService.deleteUser(user.getId(), UUID.fromString(groupId));
if (userService.getGroupById(UUID.fromString(groupId)).getMembers().isEmpty()) {
controllerService.deleteGroupEvent(user.getId(), UUID.fromString(groupId));
}
validationService.checkIfGroupEmpty(groupId, user);
return "redirect:/gruppen2/";
}
@ -331,9 +277,7 @@ public class WebController {
Account account = keyCloakService.createAccountFromPrincipal(token);
User user = new User(account.getName(), account.getGivenname(), account.getFamilyname(), account.getEmail());
Group group = userService.getGroupById(UUID.fromString(groupId));
if (group.getRoles().get(user.getId()) != Role.ADMIN) {
throw new NoAccessException("");
}
validationService.checkIfAdmin(group, user);
controllerService.deleteGroupEvent(user.getId(), UUID.fromString(groupId));
return "redirect:/gruppen2/";
}
@ -346,19 +290,12 @@ public class WebController {
Account account = keyCloakService.createAccountFromPrincipal(token);
Group group = userService.getGroupById(UUID.fromString(groupId));
User user = new User(account.getName(), "", "", "");
if (group.getMembers().contains(user)) {
if (group.getRoles().get(account.getName()) == Role.ADMIN) {
validationService.checkIfAdmin(group, user);
model.addAttribute("account", account);
model.addAttribute("members", group.getMembers());
model.addAttribute("group", group);
model.addAttribute("admin", Role.ADMIN);
return "editMembers";
} else {
return "redirect:/details/";
}
} else {
throw new NoAccessException("Die Gruppe ist privat");
}
}
@RolesAllowed({"ROLE_orga", "ROLE_studentin", "ROLE_actuator)"})
@ -367,14 +304,9 @@ public class WebController {
@RequestParam("group_id") String groupId,
@RequestParam("user_id") String userId) throws EventException {
Account account = keyCloakService.createAccountFromPrincipal(token);
if (userId.equals(account.getName())) {
if (controllerService.passIfLastAdmin(account, UUID.fromString(groupId))) {
throw new NoAdminAfterActionException("Du otto bist letzter Admin");
}
controllerService.updateRole(userId, UUID.fromString(groupId));
if (validationService.checkIfDemotingSelf(userId, groupId, account)) {
return "redirect:/gruppen2/details/" + groupId;
}
controllerService.updateRole(userId, UUID.fromString(groupId));
return "redirect:/gruppen2/details/members/" + groupId;
}
@ -392,10 +324,9 @@ public class WebController {
@PostMapping("/details/members/deleteUser")
public String deleteUser(@RequestParam("group_id") String groupId,
@RequestParam("user_id") String userId) throws EventException {
User user = new User(userId, "", "", "");
controllerService.deleteUser(userId, UUID.fromString(groupId));
if (userService.getGroupById(UUID.fromString(groupId)).getMembers().isEmpty()) {
controllerService.deleteGroupEvent(userId, UUID.fromString(groupId));
}
validationService.checkIfGroupEmpty(groupId, user);
return "redirect:/gruppen2/details/members/" + groupId;
}

View File

@ -39,7 +39,7 @@ public class AddUserEvent extends Event {
throw new UserAlreadyExistsException(this.getClass().toString());
}
if (group.getMembers().size() == group.getUserMaximum()) {
if (group.getMembers().size() >= group.getUserMaximum()) {
throw new GroupFullException(this.getClass().toString());
}

View File

@ -9,6 +9,7 @@ import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
//TODO Rename Queries + Formatting
public interface EventRepository extends CrudRepository<EventDTO, Long> {
@Query("select distinct group_id from event where user_id =:id")

View File

@ -46,26 +46,6 @@ public class ControllerService {
this.logger = Logger.getLogger("controllerServiceLogger");
}
/**
* Überprüft ob alle Felder richtig gesetzt sind.
* @param description
* @param title
* @param userMaximum
*/
private void checkFields(String description, String title, Long userMaximum ) {
if(description == null) {
throw new BadParameterException("Die Beschreibung wurde nicht korrekt angegeben");
}
if(title == null) {
throw new BadParameterException("Der Titel wurde nicht korrekt angegeben");
}
if (userMaximum == null) {
throw new BadParameterException("Teilnehmeranzahl wurde nicht korrekt angegeben");
}
}
/**
* Erzeugt eine neue Gruppe, fügt den User, der die Gruppe erstellt hat, hinzu und setzt seine Rolle als Admin fest.
* Zudem wird der Gruppentitel und die Gruppenbeschreibung erzeugt, welche vorher der Methode übergeben wurden.
@ -77,12 +57,10 @@ public class ControllerService {
*/
public void createGroup(Account account, String title, String description, Boolean isVisibilityPrivate, Boolean isMaximumInfinite, Long userMaximum, UUID parent) throws EventException {
Visibility groupVisibility = setGroupVisibility(isVisibilityPrivate);
UUID groupId = eventService.checkGroup();
UUID groupId = UUID.randomUUID();
userMaximum = checkInfiniteUsers(isMaximumInfinite, userMaximum);
checkFields(description, title, userMaximum);
CreateGroupEvent createGroupEvent = new CreateGroupEvent(groupId, account.getName(), parent, GroupType.SIMPLE, groupVisibility, userMaximum);
eventService.saveEvent(createGroupEvent);
@ -92,18 +70,16 @@ public class ControllerService {
updateRole(account.getName(), groupId);
}
public void createOrga(Account account, String title, String description, Boolean isVisibilityPrivate, Boolean isLecture, Boolean isMaximumInfinite, Long userMaximum, UUID parent, MultipartFile file) throws EventException, IOException {
public UUID createOrga(Account account, String title, String description, Boolean isVisibilityPrivate, Boolean isLecture, Boolean isMaximumInfinite, Long userMaximum, UUID parent, MultipartFile file) throws EventException, IOException {
userMaximum = checkInfiniteUsers(isMaximumInfinite, userMaximum);
checkFields(description, title, userMaximum);
List<User> userList = readCsvFile(file);
if (userList.size() > userMaximum) {
userMaximum = (long) userList.size() + 1;
}
UUID groupId = eventService.checkGroup();
UUID groupId = UUID.randomUUID();
Visibility groupVisibility = setGroupVisibility(isVisibilityPrivate);
GroupType groupType = setGroupType(isLecture);
@ -114,7 +90,8 @@ public class ControllerService {
updateTitle(account, groupId, title);
updateDescription(account, groupId, description);
updateRole(account.getName(), groupId);
addUserList(userList, groupId);
return groupId;
}
private Long checkInfiniteUsers(Boolean isMaximumInfinite, Long userMaximum) {

View File

@ -12,6 +12,7 @@ import java.util.UUID;
import java.util.stream.Collectors;
@Service
//TODO: Evtl aufsplitten in EventRepoService und EventService?
public class EventService {
private final JsonService jsonService;
@ -28,8 +29,22 @@ public class EventService {
* @param event Event, welches gespeichert wird
*/
public void saveEvent(Event event) {
EventDTO eventDTO = getDTO(event);
eventStore.save(eventDTO);
eventStore.save(getDTO(event));
}
public void saveAll(Event... events) {
for (Event event : events) {
eventStore.save(getDTO(event));
}
}
@SafeVarargs
public final void saveAll(List<Event>... events) {
for (List<Event> eventlist : events) {
for (Event event : eventlist) {
eventStore.save(getDTO(event));
}
}
}
/**
@ -39,6 +54,7 @@ public class EventService {
* @param event Event, welches in DTO übersetzt wird
* @return EventDTO Neues DTO
*/
//TODO Rename: getDTOFromEvent?
public EventDTO getDTO(Event event) {
String payload = "";
try {
@ -56,26 +72,9 @@ public class EventService {
return event.getClass().getName().substring(lastDot + 1);
}
/**
* Gibt die nächst höhere groupID zurück die belegt werden kann.
* Gibt 1 zurück, falls keine Gruppe vorhanden ist.
*
* @return Long GruppenId
*/
public UUID checkGroup() {
return UUID.randomUUID();
/*Long maxGroupID = eventStore.getMaxGroupID();
if (maxGroupID == null) {
return 1L;
}
return maxGroupID + 1;*/
}
/**
* Findet alle Events welche ab dem neuen Status hinzugekommen sind.
* Sucht alle Events mit event_id > status
*
* @param status Die Id des zuletzt gespeicherten Events
* @return Liste von neueren Events
@ -93,6 +92,7 @@ public class EventService {
* @param eventDTOS Liste von DTOs
* @return Liste von Events
*/
//TODO Rename: getEventsFromDTO?
public List<Event> translateEventDTOs(Iterable<EventDTO> eventDTOS) {
List<Event> events = new ArrayList<>();
@ -106,17 +106,6 @@ public class EventService {
return events;
}
/**
* Sichert eine Liste von Event Objekten mithilfe der Methode saveEvent(Event event).
*
* @param eventList Liste von Event Objekten
*/
public void saveEventList(List<Event> eventList) {
for (Event event : eventList) {
saveEvent(event);
}
}
public Long getMaxEvent_id() {
return eventStore.getHighesEvent_ID();
}
@ -126,6 +115,7 @@ public class EventService {
return translateEventDTOs(eventDTOList);
}
//TODO: Nur AddUserEvents betrachten
public List<UUID> findGroupIdsByUser(String userId) {
return eventStore.findGroup_idsWhereUser_id(userId).stream()
.map(UUID::fromString)

View File

@ -35,6 +35,7 @@ public class GroupService {
* @param groupIds Liste an IDs
* @return Liste an Events
*/
//TODO Das vielleicht in den EventRepoService?
public List<Event> getGroupEvents(List<UUID> groupIds) {
List<EventDTO> eventDTOS = new ArrayList<>();
for (UUID groupId : groupIds) {
@ -75,6 +76,7 @@ public class GroupService {
* @return Liste von projizierten Gruppen
* @throws EventException Projektionsfehler
*/
//TODO Rename
public List<Group> getAllGroupWithVisibilityPublic(String userId) throws EventException {
List<Event> groupEvents = eventService.translateEventDTOs(eventRepository.findAllEventsByType("CreateGroupEvent"));
groupEvents.addAll(eventService.translateEventDTOs(eventRepository.findAllEventsByType("UpdateGroupDescriptionEvent")));
@ -84,7 +86,9 @@ public class GroupService {
List<Group> visibleGroups = projectEventList(groupEvents);
return visibleGroups.parallelStream()
sortByGroupType(visibleGroups);
return visibleGroups.stream()
.filter(group -> group.getType() != null)
.filter(group -> !eventService.userInGroup(group.getId(), userId))
.filter(group -> group.getVisibility() == Visibility.PUBLIC)
@ -101,11 +105,11 @@ public class GroupService {
List<Event> createEvents = eventService.translateEventDTOs(eventRepository.findAllEventsByType("CreateGroupEvent"));
createEvents.addAll(eventService.translateEventDTOs(eventRepository.findAllEventsByType("DeleteGroupEvent")));
createEvents.addAll(eventService.translateEventDTOs(eventRepository.findAllEventsByType("UpdateGroupTitleEvent")));
createEvents.addAll(eventService.translateEventDTOs(eventRepository.findAllEventsByType("DeleteGroupEvent")));
List<Group> visibleGroups = projectEventList(createEvents);
return visibleGroups.parallelStream()
.filter(group -> group.getType() != null)
return visibleGroups.stream()
.filter(group -> group.getType() == GroupType.LECTURE)
.filter(group -> group.getVisibility() == Visibility.PUBLIC)
.collect(Collectors.toList());
@ -120,6 +124,7 @@ public class GroupService {
* @return Liste von projizierten Gruppen
* @throws EventException Projektionsfehler
*/
//Todo Rename
public List<Group> findGroupWith(String search, Account account) throws EventException {
if (search.isEmpty()) {
return getAllGroupWithVisibilityPublic(account.getName());
@ -127,9 +132,21 @@ public class GroupService {
return getAllGroupWithVisibilityPublic(account.getName())
.parallelStream()
.filter(group ->
group.getTitle().toLowerCase().contains(search.toLowerCase()) ||
group.getDescription().toLowerCase().contains(search.toLowerCase()))
.filter(group -> group.getTitle().toLowerCase().contains(search.toLowerCase())
|| group.getDescription().toLowerCase().contains(search.toLowerCase()))
.collect(Collectors.toList());
}
public void sortByGroupType(List<Group> groups) {
groups.sort((g1, g2) -> {
if (g1.getType() == GroupType.LECTURE) {
return -1;
}
if (g2.getType() == GroupType.LECTURE) {
return 0;
}
return 1;
});
}
}

View File

@ -35,6 +35,9 @@ public class UserService {
newGroups.add(group);
}
}
groupService.sortByGroupType(newGroups);
return newGroups;
}

View File

@ -0,0 +1,138 @@
package mops.gruppen2.service;
import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException;
import mops.gruppen2.domain.Group;
import mops.gruppen2.domain.Role;
import mops.gruppen2.domain.User;
import mops.gruppen2.domain.Visibility;
import mops.gruppen2.domain.exception.*;
import mops.gruppen2.security.Account;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.swing.text.StyledEditorKit;
import javax.validation.ValidationException;
import java.io.CharConversionException;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
@Service
public class ValidationService {
private final ControllerService controllerService;
private final UserService userService;
private final GroupService groupService;
public ValidationService(ControllerService controllerService, UserService userService, GroupService groupService) {
this.controllerService = controllerService;
this.userService = userService;
this.groupService = groupService;
}
public void checkTitleAndDescription(String title, String description, Account account, String groupId) {
if (title == null || description == null) {
throw new NoValueException("Titel und Beschreibung müssen ausgefüllt werden");
}
controllerService.updateTitle(account, UUID.fromString(groupId), title);
controllerService.updateDescription(account, UUID.fromString(groupId), description);
}
public List<Group> checkSearch(String search, List<Group> groups, Account account) {
if (search != null) {
groups = groupService.findGroupWith(search, account);
}
return groups;
}
public void checkGroup(String title) {
if (title == null) throw new GroupNotFoundException("@details");
}
public boolean checkIfUserInGroup(Group group, User user) {
if (!group.getMembers().contains(user) && group.getVisibility() == Visibility.PRIVATE) {
throw new NoAccessException("");
} else return group.getMembers().contains(user);
}
public Group checkParent(UUID parentId) {
Group parent = new Group();
if (!controllerService.idIsEmpty(parentId)) {
parent = userService.getGroupById(parentId);
}
return parent;
}
public void checkIfUserInGroupJoin(Group group, User user) {
if (group.getMembers().contains(user)) {
throw new UserAlreadyExistsException("@details");
}
}
public void checkIfGroupFull(Group group) {
if (group.getUserMaximum() < group.getMembers().size() + 1) {
throw new GroupFullException("Du kannst der Gruppe daher leider nicht beitreten.");
}
}
public void checkIfGroupEmpty(String groupId, User user) {
if (userService.getGroupById(UUID.fromString(groupId)).getMembers().isEmpty()) {
controllerService.deleteGroupEvent(user.getId(), UUID.fromString(groupId));
}
}
public void checkIfAdmin(Group group, User user) {
checkIfUserInGroup(group, user);
if (group.getRoles().get(user.getId()) != Role.ADMIN) {
throw new NoAccessException("");
}
}
public boolean checkIfDemotingSelf(String userId, String groupId, Account account) {
if (userId.equals(account.getName())) {
if (controllerService.passIfLastAdmin(account, UUID.fromString(groupId))) {
throw new NoAdminAfterActionException("Du Otto bist letzter Admin");
}
controllerService.updateRole(userId, UUID.fromString(groupId));
return true;
}
controllerService.updateRole(userId, UUID.fromString(groupId));
return false;
}
public List<User> checkFile(MultipartFile file, List<User> userList, String groupId, Group group, Account account) {
if (!file.isEmpty()) {
try {
userList = CsvService.read(file.getInputStream());
if (userList.size() + group.getMembers().size() > group.getUserMaximum()) {
controllerService.updateMaxUser(account, UUID.fromString(groupId), (long) userList.size() + group.getMembers().size());
}
} catch (IOException ex) {
throw new WrongFileException(file.getOriginalFilename());
}
}
return userList;
}
/**
* Überprüft ob alle Felder richtig gesetzt sind.
* @param description
* @param title
* @param userMaximum
*/
public void checkFields(String description, String title, Long userMaximum, Boolean maxInfiniteUsers) {
if (description == null) {
throw new BadParameterException("Die Beschreibung wurde nicht korrekt angegeben");
}
if (title == null) {
throw new BadParameterException("Der Titel wurde nicht korrekt angegeben");
}
if (userMaximum == null && maxInfiniteUsers == null) {
throw new BadParameterException("Teilnehmeranzahl wurde nicht korrekt angegeben");
}
}
}

View File

@ -10,7 +10,8 @@
</head>
<body>
<header>
<nav class="navigation navigation-secondary" is="mops-navigation" th:fragment="navigation" th:switch="${account.getRoles().contains('orga')}">
<nav class="navigation navigation-secondary" is="mops-navigation" th:fragment="navigation"
th:switch="${account.getRoles().contains('orga')}">
<ul>
<li class="active">
<a href="/" th:href="@{/gruppen2}">Gruppen</a>
@ -44,8 +45,12 @@
</h3>
<br>
<div th:each="gruppe: ${gruppen}">
<div class="shadow-sm p-4" style="border: none; border-radius: 5px; background: aliceblue">
<div class="shadow-sm p-4"
style="border: none; border-radius: 5px; background: aliceblue">
<h3 style="color: dodgerblue; font-weight: bold; font-optical-sizing: auto; overflow-wrap: break-word">
<span class="badge badge-pill badge-success"
style="background: lightseagreen; margin-right: 25px;"
th:if='${gruppe.getType() == gruppe.getType().LECTURE}'>Veranstaltung</span>
<a th:href="@{/gruppen2/details/{id}(id=${gruppe.getId()})}"
th:text="${gruppe.getTitle()}"></a>
</h3>

View File

@ -59,8 +59,11 @@
<tbody>
<tr th:each="gruppe : ${gruppen}" th:switch="${gruppe.getUserMaximum() != 100000}">
<th scope="row">
<span class="badge badge-pill badge-success"
style="background: lightseagreen; margin-right: 25px;"
th:if='${gruppe.getType() == gruppe.getType().LECTURE}'>Veranstaltung</span>
<a th:href="@{/gruppen2/detailsSearch(id=${gruppe.getId()})}"
th:text="${gruppe.getTitle()}">Gruppenname</a>
th:text="${#strings.abbreviate(gruppe.getTitle(), 50)}">Gruppenname</a>
</th>
<td style="" th:text="${#strings.abbreviate(gruppe.getDescription(), 50)}">
Beschreibung

View File

@ -7,11 +7,13 @@ import mops.gruppen2.domain.Role;
import mops.gruppen2.domain.Visibility;
import mops.gruppen2.domain.event.AddUserEvent;
import mops.gruppen2.domain.event.CreateGroupEvent;
import mops.gruppen2.domain.event.DeleteGroupEvent;
import mops.gruppen2.domain.event.DeleteUserEvent;
import mops.gruppen2.domain.event.Event;
import mops.gruppen2.domain.event.UpdateGroupDescriptionEvent;
import mops.gruppen2.domain.event.UpdateGroupTitleEvent;
import mops.gruppen2.domain.event.UpdateRoleEvent;
import mops.gruppen2.security.Account;
import java.util.ArrayList;
import java.util.Collection;
@ -25,28 +27,67 @@ public class TestBuilder {
private static final Faker faker = new Faker();
public static Account account(String name) {
return new Account(name,
"",
"",
"",
"",
null);
}
public static Group apply(Group group, Event... events) {
for (Event event : events) {
event.apply(group);
}
return group;
}
public static Group apply(Event... events) {
return apply(new Group(), events);
}
/**
* Baut eine UUID.
*
* @param id Integer id
* @return UUID
*/
public static UUID uuidFromInt(int id) {
return UUID.fromString("00000000-0000-0000-0000-"
+ "0".repeat(11 - String.valueOf(id).length())
+ id);
}
/**
* Generiert ein EventLog mit mehreren Gruppen und Usern.
*
* @param count Gruppenanzahl
* @param membercount Gesamte Mitgliederanzahl
* @param membercount Mitgliederanzahl pro Gruppe
* @return Eventliste
*/
public static List<Event> completeGroups(int count, int membercount) {
int memPerGroup = membercount / count;
return IntStream.rangeClosed(0, count)
public static List<Event> completePublicGroups(int count, int membercount) {
return IntStream.range(0, count)
.parallel()
.mapToObj(i -> completeGroup(memPerGroup))
.mapToObj(i -> completePublicGroup(membercount))
.flatMap(Collection::stream)
.collect(Collectors.toList());
}
public static List<Event> completeGroup(int membercount) {
public static List<Event> completePrivateGroups(int count, int membercount) {
return IntStream.range(0, count)
.parallel()
.mapToObj(i -> completePrivateGroup(membercount))
.flatMap(Collection::stream)
.collect(Collectors.toList());
}
public static List<Event> completePublicGroup(int membercount) {
List<Event> eventList = new ArrayList<>();
UUID groupId = UUID.randomUUID();
eventList.add(createGroupEvent(groupId));
eventList.add(createPublicGroupEvent(groupId));
eventList.add(updateGroupTitleEvent(groupId));
eventList.add(updateGroupDescriptionEvent(groupId));
eventList.addAll(addUserEvents(membercount, groupId));
@ -54,8 +95,24 @@ public class TestBuilder {
return eventList;
}
public static List<Event> completeGroup() {
return completeGroup(100);
public static List<Event> completePrivateGroup(int membercount) {
List<Event> eventList = new ArrayList<>();
UUID groupId = UUID.randomUUID();
eventList.add(createPrivateGroupEvent(groupId));
eventList.add(updateGroupTitleEvent(groupId));
eventList.add(updateGroupDescriptionEvent(groupId));
eventList.addAll(addUserEvents(membercount, groupId));
return eventList;
}
public static List<Event> completePublicGroup() {
return completePublicGroup(100);
}
public static List<Event> completePrivateGroup() {
return completePrivateGroup(100);
}
/**
@ -64,26 +121,69 @@ public class TestBuilder {
* @param count Anzahl der verschiedenen Gruppen
* @return Eventliste
*/
public static List<CreateGroupEvent> createGroupEvents(int count) {
return IntStream.rangeClosed(0, count)
public static List<Event> createPublicGroupEvents(int count) {
return IntStream.range(0, count)
.parallel()
.mapToObj(i -> createGroupEvent())
.mapToObj(i -> createPublicGroupEvent())
.collect(Collectors.toList());
}
public static CreateGroupEvent createGroupEvent(UUID groupId) {
public static List<Event> createPrivateGroupEvents(int count) {
return IntStream.range(0, count)
.parallel()
.mapToObj(i -> createPublicGroupEvent())
.collect(Collectors.toList());
}
public static List<Event> createMixedGroupEvents(int count) {
return IntStream.range(0, count)
.parallel()
.mapToObj(i -> faker.random().nextInt(0, 1) > 0.5
? createPublicGroupEvent()
: createPrivateGroupEvent())
.collect(Collectors.toList());
}
public static Event createPrivateGroupEvent(UUID groupId) {
return createGroupEvent(groupId, Visibility.PRIVATE);
}
public static Event createPrivateGroupEvent() {
return createPrivateGroupEvent(UUID.randomUUID());
}
public static Event createPublicGroupEvent(UUID groupId) {
return createGroupEvent(groupId, Visibility.PUBLIC);
}
public static Event createPublicGroupEvent() {
return createPublicGroupEvent(UUID.randomUUID());
}
public static Event createGroupEvent(UUID groupId, Visibility visibility) {
return new CreateGroupEvent(
groupId,
faker.random().hex(),
null,
GroupType.SIMPLE,
Visibility.PUBLIC,
visibility,
10000000L
);
}
public static CreateGroupEvent createGroupEvent() {
return createGroupEvent(UUID.randomUUID());
public static Event createLectureEvent() {
return createLectureEvent(UUID.randomUUID());
}
public static Event createLectureEvent(UUID groupId) {
return new CreateGroupEvent(
groupId,
faker.random().hex(),
null,
GroupType.LECTURE,
Visibility.PUBLIC,
10000000L
);
}
/**
@ -94,13 +194,13 @@ public class TestBuilder {
* @return Eventliste
*/
public static List<Event> addUserEvents(int count, UUID groupId) {
return IntStream.rangeClosed(1, count)
return IntStream.range(0, count)
.parallel()
.mapToObj(i -> addUserEvent(groupId, String.valueOf(i)))
.collect(Collectors.toList());
}
public static AddUserEvent addUserEvent(UUID groupId, String userId) {
public static Event addUserEvent(UUID groupId, String userId) {
String firstname = firstname();
String lastname = lastname();
@ -113,10 +213,11 @@ public class TestBuilder {
);
}
public static AddUserEvent addUserEvent(UUID groupId) {
public static Event addUserEvent(UUID groupId) {
return addUserEvent(groupId, faker.random().hex());
}
// Am besten einfach nicht benutzen
public static List<Event> deleteUserEvents(int count, List<Event> eventList) {
List<Event> removeEvents = new ArrayList<>();
List<Event> shuffle = eventList.parallelStream()
@ -142,36 +243,44 @@ public class TestBuilder {
* @param group Gruppe welche geleert wird
* @return Eventliste
*/
public static List<DeleteUserEvent> deleteUserEvents(Group group) {
public static List<Event> deleteUserEvents(Group group) {
return group.getMembers().parallelStream()
.map(user -> deleteUserEvent(group.getId(), user.getId()))
.collect(Collectors.toList());
}
public static DeleteUserEvent deleteUserEvent(UUID groupId, String userId) {
public static Event deleteUserEvent(UUID groupId, String userId) {
return new DeleteUserEvent(
groupId,
userId
);
}
public static UpdateGroupDescriptionEvent updateGroupDescriptionEvent(UUID groupId) {
public static Event updateGroupDescriptionEvent(UUID groupId) {
return updateGroupDescriptionEvent(groupId, quote());
}
public static Event updateGroupDescriptionEvent(UUID groupId, String description) {
return new UpdateGroupDescriptionEvent(
groupId,
faker.random().hex(),
quote()
description
);
}
public static UpdateGroupTitleEvent updateGroupTitleEvent(UUID groupId) {
public static Event updateGroupTitleEvent(UUID groupId) {
return updateGroupTitleEvent(groupId, champion());
}
public static Event updateGroupTitleEvent(UUID groupId, String title) {
return new UpdateGroupTitleEvent(
groupId,
faker.random().hex(),
champion()
title
);
}
public static UpdateRoleEvent randomUpdateRoleEvent(UUID groupId, String userId, Role role) {
public static Event updateRoleEvent(UUID groupId, String userId, Role role) {
return new UpdateRoleEvent(
groupId,
userId,
@ -179,6 +288,10 @@ public class TestBuilder {
);
}
public static Event deleteGroupEvent(UUID groupId) {
return new DeleteGroupEvent(groupId, faker.random().hex());
}
private static String firstname() {
return clean(faker.name().firstName());
}

View File

@ -4,6 +4,7 @@ import com.tngtech.archunit.core.importer.ImportOption;
import com.tngtech.archunit.junit.AnalyzeClasses;
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.lang.ArchRule;
import mops.gruppen2.domain.exception.EventException;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
@ -44,6 +45,16 @@ public class DomainTest {
@ArchTest
public static final ArchRule classesThatHaveExceptionInNameShouldBeAssignableToExceptionClass = classes()
.that().haveSimpleNameEndingWith("Exception")
.should().beAssignableTo(Exception.class);
.should().beAssignableTo(EventException.class);
@ArchTest
public static final ArchRule classesInDtoPackageShouldHaveDtoInName = classes()
.that().resideInAPackage("..domain.dto..")
.should().haveSimpleNameEndingWith("DTO");
@ArchTest
public static final ArchRule dtoClassesShouldBeInDtoPackage = classes()
.that().haveSimpleNameEndingWith("DTO")
.should().resideInAPackage("..domain.dto..");
}

View File

@ -1,141 +0,0 @@
package mops.gruppen2.domain;
class GroupTest {
/*
@BeforeEach
public void setUp() {
}
@Test
void applyEvent() {
}
@Test
void createSingleGroup() throws Exception {
CreateGroupEvent createGroupEvent = new CreateGroupEvent(1L, "Prof", null, GroupType.LECTURE, Visibility.PRIVATE);
Group group = new Group();
group.applyEvent(createGroupEvent);
assertThat(group.getId()).isEqualTo(1L);
assertNull(group.getParent());
assertEquals(GroupType.LECTURE, group.getType());
assertEquals(Visibility.PRIVATE, group.getVisibility());
}
// Verwendet CreateGroupEvent
@Test
void addSingleUser() throws Exception {
CreateGroupEvent createGroupEvent = new CreateGroupEvent(1L, "pepee",null, GroupType.LECTURE , Visibility.PRIVATE);
Group group = new Group();
group.applyEvent(createGroupEvent);
User user = new User("prof", "jens", "bendi", "hi@gmail.com");
AddUserEvent addUserEvent = new AddUserEvent(1L, 1L, user);
group.applyEvent(addUserEvent);
assertThat(group.getMembers().get(0)).isEqualTo(user);
}
@Test
void addExistingUser() throws Exception {
CreateGroupEvent createGroupEvent = new CreateGroupEvent(1L, "prof1", null, GroupType.LECTURE, Visibility.PRIVATE);
Group group = new Group();
group.applyEvent(createGroupEvent);
User user1 = new User("prof", "jens", "bendi", "hi@gmail.com");
AddUserEvent addUserEvent1 = new AddUserEvent(2L, 1L, user1);
group.applyEvent(addUserEvent1);
User user2 = new User("prof", "olga", "bendi", "hi@gmail.com");
AddUserEvent addUserEvent2 = new AddUserEvent(3L, 1L, user2);
Assertions.assertThrows(UserAlreadyExistsException.class, () -> {
group.applyEvent(addUserEvent2);
});
assertThat(group.getMembers().size()).isEqualTo(1);
}
@Test
void deleteSingleUser() throws Exception {
CreateGroupEvent createGroupEvent = new CreateGroupEvent(1L, "Prof", null, GroupType.LECTURE, Visibility.PRIVATE);
User user = new User("Prof", "Pro", "fessor", "pro@fessor.de");
AddUserEvent addUserEvent = new AddUserEvent(2L, 2L, user);
Group group = new Group();
group.applyEvent(createGroupEvent);
group.applyEvent(addUserEvent);
DeleteUserEvent deleteUserEvent = new DeleteUserEvent(3L, 2L, "Prof");
group.applyEvent(deleteUserEvent);
assertThat(group.getMembers().size()).isEqualTo(0);
}
@Test
void deleteUserThatDoesNotExists() throws Exception {
CreateGroupEvent createGroupEvent = new CreateGroupEvent(1L, "Prof", null, GroupType.LECTURE, Visibility.PRIVATE);
Group group = new Group();
group.applyEvent(createGroupEvent);
DeleteUserEvent deleteUserEvent = new DeleteUserEvent(3L, 2L, "Prof");
Assertions.assertThrows(UserNotFoundException.class, () -> {
group.applyEvent(deleteUserEvent);
});
}
// Verwendet CreateGroupEvent und AddUserEvent
@Test
void updateRoleForExistingUser() throws Exception {
// Arrange
CreateGroupEvent createGroupEvent = new CreateGroupEvent(1L, "Prof", null, GroupType.LECTURE, Visibility.PRIVATE);
AddUserEvent addUserEvent = new AddUserEvent(1L, 1L, "5L", "Peter", "Pan", "123@mail.de");
Group group = new Group();
group.applyEvent(createGroupEvent);
group.applyEvent(addUserEvent);
UpdateRoleEvent updateRoleEvent = new UpdateRoleEvent(1L, 1L, "5L", Role.ADMIN);
// Act
group.applyEvent(updateRoleEvent);
// Assert
assertThat(group.getRoles())
.containsOnlyKeys(group.getMembers().get(0).getUser_id())
.containsValue(Role.ADMIN);
}
@Test
void updateRoleForNonExistingUser() throws Exception {
CreateGroupEvent createGroupEvent = new CreateGroupEvent(1L, "Prof", null, GroupType.LECTURE, Visibility.PRIVATE);
UpdateRoleEvent updateRoleEvent = new UpdateRoleEvent(345L, 33L, "coolerUser", Role.ADMIN);
Group group = new Group();
group.applyEvent(createGroupEvent);
Assertions.assertThrows(UserNotFoundException.class, () -> {
group.applyEvent(updateRoleEvent);
});
}
@Test
void updateTitle() throws Exception { //bitte umschreiben
Group group = new Group();
UpdateGroupTitleEvent updateGroupTitleEvent = new UpdateGroupTitleEvent(2L, 1L, "Klaus", "Toller Titel");
group.applyEvent(updateGroupTitleEvent);
assertThat("Toller Titel").isEqualTo("Toller Titel");
}
@Test
void updateBeschreibung() throws Exception { //bitte umschreiben
Group group = new Group();
UpdateGroupDescriptionEvent updateGroupDescriptionEvent = new UpdateGroupDescriptionEvent(2L, 1L, "Peter", "Tolle Beschreibung");
group.applyEvent(updateGroupDescriptionEvent);
assertThat("Tolle Beschreibung").isEqualTo("Tolle Beschreibung");
}*/
}

View File

@ -1,23 +1,35 @@
package mops.gruppen2.domain.event;
import mops.gruppen2.domain.Group;
import mops.gruppen2.domain.User;
import mops.gruppen2.domain.exception.EventException;
import mops.gruppen2.domain.exception.UserAlreadyExistsException;
import org.junit.jupiter.api.Test;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
class AddUserEventTest {
/*@Test
@Test
void userAlreadyExistExeption() throws EventException {
Group group = new Group();
User user = new User("user1", "Stein", "Speck", "@sdasd");
group.getMembers().add(user);
group.setUserMaximum(10L);
Event event1 = new AddUserEvent(4L, "user2", "Rock", "Roll", "and");
UUID id = UUID.randomUUID();
Event event1 = new AddUserEvent(id, "user2", "Rock", "Roll", "and");
event1.apply(group);
Event event2 = new AddUserEvent(4L, "user1", "Rock", "Roll", "and");
Event event2 = new AddUserEvent(id, "user1", "Rock", "Roll", "and");
assertThrows(UserAlreadyExistsException.class, () ->
event2.apply(group)
);
assertThat(group.getMembers().size()).isEqualTo(2);
}*/
}
}

View File

@ -1,8 +1,20 @@
package mops.gruppen2.domain.event;
import mops.gruppen2.domain.Group;
import mops.gruppen2.domain.User;
import mops.gruppen2.domain.exception.EventException;
import mops.gruppen2.domain.exception.UserNotFoundException;
import org.junit.jupiter.api.Test;
import java.util.UUID;
import static mops.gruppen2.domain.Role.MEMBER;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
class DeleteUserEventTest {
/*@Test
@Test
void applyDeleteUser() throws EventException {
Group group = new Group();
User user = new User("user1", "Stein", "Speck", "@sdasd");
@ -12,7 +24,7 @@ class DeleteUserEventTest {
group.getMembers().add(user2);
group.getRoles().put("user2", MEMBER);
Event event = new DeleteUserEvent(1L, "user1");
Event event = new DeleteUserEvent(UUID.randomUUID(), "user1");
event.apply(group);
assertThat(group.getMembers().size()).isEqualTo(1);
@ -27,10 +39,10 @@ class DeleteUserEventTest {
group.getMembers().add(user);
group.getRoles().put("user1", MEMBER);
Event event = new DeleteUserEvent(17L, "user5");
Event event = new DeleteUserEvent(UUID.randomUUID(), "user5");
assertThrows(UserNotFoundException.class, () ->
event.apply(group)
);
assertThat(group.getMembers().size()).isEqualTo(1);
}*/
}
}

View File

@ -0,0 +1,80 @@
package mops.gruppen2.service;
import com.github.javafaker.Faker;
import mops.gruppen2.repository.EventRepository;
import mops.gruppen2.security.Account;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.HashSet;
import java.util.Set;
import static org.mockito.Mockito.mock;
class ControllerServiceTest {
Faker faker;
Account account;
ControllerService controllerService;
EventService eventService;
UserService userService;
EventRepository eventRepository;
GroupService groupService;
JsonService jsonService;
@BeforeEach
void setUp() {
jsonService = new JsonService();
eventRepository = mock(EventRepository.class);
eventService = new EventService(jsonService, eventRepository);
groupService = new GroupService(eventService, eventRepository);
userService = new UserService(groupService, eventService);
controllerService = new ControllerService(eventService, userService);
Set<String> roles = new HashSet<>();
roles.add("l");
account = new Account("ich", "ich@hhu.de", "l", "ichdude", "jap", roles);
}
@Test
void createGroupTest() {
}
@Test
void createOrga() {
}
@Test
void addUser() {
}
@Test
void addUserList() {
}
@Test
void updateTitle() {
}
@Test
void updateDescription() {
}
@Test
void updateRoleTest() {
}
@Test
void deleteUser() {
}
@Test
void deleteGroupEvent() {
}
@Test
void passIfLastAdmin() {
}
}

View File

@ -1,55 +1,132 @@
package mops.gruppen2.service;
import mops.gruppen2.Gruppen2Application;
import mops.gruppen2.domain.dto.EventDTO;
import mops.gruppen2.domain.event.Event;
import mops.gruppen2.repository.EventRepository;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.transaction.annotation.Transactional;
@RunWith(MockitoJUnitRunner.class)
import static mops.gruppen2.TestBuilder.addUserEvent;
import static mops.gruppen2.TestBuilder.addUserEvents;
import static mops.gruppen2.TestBuilder.createPrivateGroupEvent;
import static mops.gruppen2.TestBuilder.createPrivateGroupEvents;
import static mops.gruppen2.TestBuilder.createPublicGroupEvent;
import static mops.gruppen2.TestBuilder.createPublicGroupEvents;
import static mops.gruppen2.TestBuilder.updateGroupDescriptionEvent;
import static mops.gruppen2.TestBuilder.uuidFromInt;
import static org.assertj.core.api.Assertions.assertThat;
//TODO: Der ID autocounter wird nicht resettet -> Tests schlagen fehl beim nacheinanderausführen
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = Gruppen2Application.class)
@Transactional
@Rollback
class EventServiceTest {
@Autowired
private EventRepository eventRepository;
@Autowired
private JsonService jsonService;
private EventService eventService;
/*@BeforeEach
@BeforeEach
void setUp() {
eventRepository = mock(EventRepository.class);
eventService = new EventService(mock(JsonService.class), eventRepository);
eventService = new EventService(jsonService, eventRepository);
eventRepository.deleteAll();
}
@Test
void getMaxID() {
when(eventRepository.getHighesEvent_ID()).thenReturn(42L);
void saveEvent() {
eventService.saveEvent(createPublicGroupEvent());
assertEquals(eventService.getMaxEvent_id(), 42L);
assertThat(eventRepository.findAll()).hasSize(1);
}
@Test
void checkGroupReturnNextValue() {
when(eventRepository.getMaxGroupID()).thenReturn(2L);
void saveAll() {
eventService.saveAll(createPrivateGroupEvents(10));
assertEquals(eventService.checkGroup(), 3L);
assertThat(eventRepository.findAll()).hasSize(10);
}
@Test
void checkGroupReturnOneIfDBIsEmpty() {
List<EventDTO> eventDTOS = new ArrayList<>();
when(eventRepository.findAll()).thenReturn(eventDTOS);
void testSaveAll() {
eventService.saveAll(createPublicGroupEvents(5),
createPrivateGroupEvents(5));
assertEquals(eventService.checkGroup(), 1);
}*/
/*@Test
void getDTOOffentlichTest() {
CreateGroupEvent createGroupEvent = new CreateGroupEvent(eventService.checkGroup(), "test", null, GroupType.LECTURE, Visibility.PUBLIC, null);
EventDTO eventDTO = eventService.getDTO(createGroupEvent);
assertTrue(eventDTO.isVisibility());
assertThat(eventRepository.findAll()).hasSize(10);
}
@Test
void getDTOPrivatTest() {
AddUserEvent addUserEvent = new AddUserEvent(eventService.checkGroup(), "test", "franz", "mueller", "a@a");
EventDTO eventDTO = eventService.getDTO(addUserEvent);
assertFalse(eventDTO.isVisibility());
}*/
void getDTO() {
Event event = createPublicGroupEvent();
EventDTO dto = eventService.getDTO(event);
assertThat(dto.getGroup_id()).isEqualTo(event.getGroupId().toString());
assertThat(dto.getUser_id()).isEqualTo(event.getUserId());
assertThat(dto.getEvent_id()).isEqualTo(null);
assertThat(dto.getEvent_type()).isEqualTo("CreateGroupEvent");
}
@Disabled
@Test
void getNewEvents_createGroupEvents() {
eventService.saveAll(createPrivateGroupEvents(10));
assertThat(eventService.getNewEvents(0L)).hasSize(10);
assertThat(eventService.getNewEvents(5L)).hasSize(5);
assertThat(eventService.getNewEvents(10L)).isEmpty();
}
@Disabled
@Test
void getNewEvents_mixedEvents() {
eventService.saveAll(createPrivateGroupEvent(uuidFromInt(0)),
updateGroupDescriptionEvent(uuidFromInt(0)),
createPrivateGroupEvent(uuidFromInt(1)),
updateGroupDescriptionEvent(uuidFromInt(1)));
assertThat(eventService.getNewEvents(0L)).hasSize(4);
assertThat(eventService.getNewEvents(1L)).hasSize(4);
assertThat(eventService.getNewEvents(2L)).hasSize(2);
assertThat(eventService.getNewEvents(3L)).hasSize(2);
}
@Disabled
@Test
void getMaxEvent_id() {
eventService.saveAll(createPrivateGroupEvents(10));
assertThat(eventService.getMaxEvent_id()).isEqualTo(10);
}
@Test
void getEventsOfGroup() {
eventService.saveAll(addUserEvents(10, uuidFromInt(0)),
addUserEvents(5, uuidFromInt(1)));
assertThat(eventService.getEventsOfGroup(uuidFromInt(0))).hasSize(10);
assertThat(eventService.getEventsOfGroup(uuidFromInt(1))).hasSize(5);
}
@Test
void findGroupIdsByUser() {
eventService.saveAll(addUserEvent(uuidFromInt(0), "A"),
addUserEvent(uuidFromInt(1), "A"),
addUserEvent(uuidFromInt(2), "A"),
addUserEvent(uuidFromInt(3), "A"),
addUserEvent(uuidFromInt(3), "B"));
assertThat(eventService.findGroupIdsByUser("A")).hasSize(4);
assertThat(eventService.findGroupIdsByUser("B")).hasSize(1);
}
}

View File

@ -1,28 +1,234 @@
package mops.gruppen2.service;
import mops.gruppen2.Gruppen2Application;
import mops.gruppen2.TestBuilder;
import mops.gruppen2.domain.Group;
import mops.gruppen2.domain.Visibility;
import mops.gruppen2.domain.event.Event;
import mops.gruppen2.repository.EventRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.transaction.annotation.Transactional;
import static org.mockito.Mockito.mock;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import static mops.gruppen2.TestBuilder.account;
import static mops.gruppen2.TestBuilder.addUserEvent;
import static mops.gruppen2.TestBuilder.completePrivateGroup;
import static mops.gruppen2.TestBuilder.completePrivateGroups;
import static mops.gruppen2.TestBuilder.completePublicGroups;
import static mops.gruppen2.TestBuilder.createLectureEvent;
import static mops.gruppen2.TestBuilder.createPrivateGroupEvent;
import static mops.gruppen2.TestBuilder.createPublicGroupEvent;
import static mops.gruppen2.TestBuilder.deleteGroupEvent;
import static mops.gruppen2.TestBuilder.updateGroupDescriptionEvent;
import static mops.gruppen2.TestBuilder.updateGroupTitleEvent;
import static mops.gruppen2.TestBuilder.uuidFromInt;
import static org.assertj.core.api.Assertions.assertThat;
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = Gruppen2Application.class)
@Transactional
@Rollback
class GroupServiceTest {
@Autowired
private EventRepository eventRepository;
@Autowired
private EventService eventService;
private GroupService groupService;
@BeforeEach
void setUp() {
groupService = new GroupService(mock(EventService.class), mock(EventRepository.class));
groupService = new GroupService(eventService, eventRepository);
eventRepository.deleteAll();
}
/* @Test
//TODO: Wofür ist dieser Test?
@Test
void rightClassForSuccessfulGroup() {
List<Event> eventList = new ArrayList<>();
eventList.add(new CreateGroupEvent(1L, "Prof", null, GroupType.LECTURE, Visibility.PRIVATE,1000L));
eventList.add(new AddUserEvent(1L, "Ulli", "Ulli", "Honnis", "FC@B.de"));
/*List<Event> eventList = new ArrayList<>();
UUID id = UUID.randomUUID();
eventList.add(new CreateGroupEvent(id, "Prof", null, GroupType.LECTURE, Visibility.PRIVATE, 1000L));
eventList.add(new AddUserEvent(id, "Ulli", "Ulli", "Honnis", "FC@B.de"));*/
List<Event> eventList = completePrivateGroup(1);
List<Group> groups = groupService.projectEventList(eventList);
assertThat(groups.get(0)).isInstanceOf(Group.class);
}
@Test
void projectEventList_SingleGroup() {
List<Event> eventList = completePrivateGroup(5);
List<Group> groups = groupService.projectEventList(eventList);
assertThat(groups.get(0)).isInstanceOf(Group.class);
}*/
assertThat(groups).hasSize(1);
assertThat(groups.get(0).getMembers()).hasSize(5);
assertThat(groups.get(0).getVisibility()).isEqualTo(Visibility.PRIVATE);
}
@Test
void projectEventList_MultipleGroups() {
List<Event> eventList = completePrivateGroups(10, 2);
eventList.addAll(completePublicGroups(10, 5));
List<Group> groups = groupService.projectEventList(eventList);
assertThat(groups).hasSize(20);
assertThat(groups.stream().map(group -> group.getMembers().size()).reduce(Integer::sum).get()).isEqualTo(70);
}
@Test
void getGroupEvents() {
// CreateGroupEvent test1 = new CreateGroupEvent(uuidFromInt(0), "test1", null, GroupType.SIMPLE, Visibility.PUBLIC, 20L);
// CreateGroupEvent test2 = new CreateGroupEvent(uuidFromInt(1), "test2", null, GroupType.SIMPLE, Visibility.PUBLIC, 10L);
eventService.saveAll(createPublicGroupEvent(uuidFromInt(0)),
createPublicGroupEvent(uuidFromInt(1)),
createPrivateGroupEvent(uuidFromInt(2)));
List<UUID> groupIds = Arrays.asList(uuidFromInt(0), uuidFromInt(1));
assertThat(groupService.getGroupEvents(groupIds)).hasSize(2);
assertThat(groupService.getGroupEvents(groupIds).get(0).getGroupId()).isEqualTo(uuidFromInt(0));
assertThat(groupService.getGroupEvents(groupIds).get(1).getGroupId()).isEqualTo(uuidFromInt(1));
}
@Test
void getAllGroupWithVisibilityPublicTestCreateAndDeleteSameGroup() {
//CreateGroupEvent test1 = new CreateGroupEvent(uuidFromInt(0), "test1", null, GroupType.SIMPLE, Visibility.PUBLIC, 20L);
//DeleteGroupEvent test2 = new DeleteGroupEvent(uuidFromInt(0), "test1");
Event test1 = createPublicGroupEvent(uuidFromInt(0));
Event test2 = deleteGroupEvent(uuidFromInt(0));
//Group group = new Group();
//test1.apply(group);
//test2.apply(group);
//TODO: Hier projectEventlist()?
Group group = TestBuilder.apply(test1, test2);
assertThat(group.getType()).isEqualTo(null);
assertThat(groupService.getAllGroupWithVisibilityPublic("test1")).isEmpty();
}
@Test
void getAllGroupWithVisibilityPublicTestGroupPublic() {
// eventService.saveEvent(new CreateGroupEvent(uuidFromInt(0), "test1", null, GroupType.SIMPLE, Visibility.PUBLIC, 20L));
// eventService.saveEvent(new DeleteGroupEvent(uuidFromInt(0), "test1"));
// eventService.saveEvent(new CreateGroupEvent(uuidFromInt(1), "test2", null, GroupType.LECTURE, Visibility.PUBLIC, 10L));
// eventService.saveEvent(new UpdateRoleEvent(uuidFromInt(1), "test2", Role.MEMBER)); //Wofür ist das
eventService.saveAll(createPublicGroupEvent(uuidFromInt(0)),
deleteGroupEvent(uuidFromInt(0)),
createPublicGroupEvent());
assertThat(groupService.getAllGroupWithVisibilityPublic("test1").size()).isEqualTo(1);
}
@Test
void getAllGroupWithVisibilityPublicTestAddSomeEvents() {
// eventService.saveEvent(new CreateGroupEvent(uuidFromInt(0), "test1", null, GroupType.SIMPLE, Visibility.PUBLIC, 20L));
// eventService.saveEvent(new DeleteGroupEvent(uuidFromInt(0), "test1"));
// eventService.saveEvent(new CreateGroupEvent(uuidFromInt(1), "test2", null, GroupType.LECTURE, Visibility.PUBLIC, 10L));
// eventService.saveEvent(new UpdateRoleEvent(uuidFromInt(1), "test2", Role.MEMBER)); // Wofür?
// eventService.saveEvent(new CreateGroupEvent(uuidFromInt(2), "test3", null, GroupType.LECTURE, Visibility.PUBLIC, 10L));
// eventService.saveEvent(new CreateGroupEvent(uuidFromInt(3), "test4", null, GroupType.LECTURE, Visibility.PUBLIC, 10L));
// eventService.saveEvent(new CreateGroupEvent(uuidFromInt(4), "test5", null, GroupType.LECTURE, Visibility.PUBLIC, 10L));
eventService.saveAll(createPublicGroupEvent(uuidFromInt(0)),
deleteGroupEvent(uuidFromInt(0)),
createPublicGroupEvent(),
createPublicGroupEvent(),
createPublicGroupEvent(),
createPrivateGroupEvent());
assertThat(groupService.getAllGroupWithVisibilityPublic("test1").size()).isEqualTo(3);
}
@Disabled
@Test
void getAllGroupWithVisibilityPublicTestIsUserInGroup() {
// eventService.saveEvent(new CreateGroupEvent(uuidFromInt(0), "test1", null, GroupType.SIMPLE, Visibility.PUBLIC, 20L));
// eventService.saveEvent(new AddUserEvent(uuidFromInt(0), "test1", "test", "test", "test@test"));
eventService.saveAll(createPublicGroupEvent(uuidFromInt(0)),
addUserEvent(uuidFromInt(0), "kobold"),
createPrivateGroupEvent(),
createPublicGroupEvent());
//Das kommt glaube ich eher in einen Test für die Projektion
//assertThat(groupService.getAllGroupWithVisibilityPublic("test2").get(0).getMembers().size()).isEqualTo(1);
assertThat(groupService.getAllGroupWithVisibilityPublic("kobold")).hasSize(1);
assertThat(groupService.getAllGroupWithVisibilityPublic("peter")).hasSize(2);
}
@Test
void getAllLecturesWithVisibilityPublic() {
// eventService.saveEvent(new CreateGroupEvent(uuidFromInt(0), "test1", null, GroupType.SIMPLE, Visibility.PUBLIC, 20L));
// eventService.saveEvent(new CreateGroupEvent(uuidFromInt(1), "test2", null, GroupType.LECTURE, Visibility.PUBLIC, 10L));
// eventService.saveEvent(new UpdateRoleEvent(uuidFromInt(1), "test2", Role.MEMBER)); // Hä
// eventService.saveEvent(new CreateGroupEvent(uuidFromInt(2), "test3", null, GroupType.LECTURE, Visibility.PUBLIC, 10L));
// eventService.saveEvent(new CreateGroupEvent(uuidFromInt(3), "test4", null, GroupType.LECTURE, Visibility.PUBLIC, 10L));
// eventService.saveEvent(new CreateGroupEvent(uuidFromInt(4), "test5", null, GroupType.LECTURE, Visibility.PUBLIC, 10L));
eventService.saveAll(createLectureEvent(),
createPublicGroupEvent(),
createLectureEvent(),
createLectureEvent(),
createLectureEvent());
assertThat(groupService.getAllLecturesWithVisibilityPublic().size()).isEqualTo(4);
}
@Test
void findGroupWith_UserMember_AllGroups() {
// eventService.saveEvent(new CreateGroupEvent(uuidFromInt(0), "test1", null, GroupType.SIMPLE, Visibility.PUBLIC, 20L));
// eventService.saveEvent(new AddUserEvent(uuidFromInt(0), "test1", "test", "test", "test@test"));
// eventService.saveEvent(new UpdateGroupTitleEvent(uuidFromInt(0), "test1", "TestGroup"));
// eventService.saveEvent(new UpdateGroupDescriptionEvent(uuidFromInt(0), "test1", "TestDescription"));
// eventService.saveEvent(new UpdateRoleEvent(uuidFromInt(0), "test1", Role.MEMBER));
eventService.saveAll(createPublicGroupEvent(uuidFromInt(0)),
addUserEvent(uuidFromInt(0), "jens"),
updateGroupTitleEvent(uuidFromInt(0)),
updateGroupDescriptionEvent(uuidFromInt(0)));
//assertThat(groupService.findGroupWith("T", new Account("jens", "a@A", "test", "peter", "mueller", null)).size()).isEqualTo(1);
assertThat(groupService.findGroupWith("", account("jens"))).isEmpty();
}
@Test
void findGroupWith_UserNoMember_AllGroups() {
eventService.saveAll(completePublicGroups(10, 0),
completePrivateGroups(10, 0));
assertThat(groupService.findGroupWith("", account("jens"))).hasSize(10);
}
@Test
void findGroupWith_FilterGroups() {
eventService.saveAll(createPublicGroupEvent(uuidFromInt(0)),
updateGroupTitleEvent(uuidFromInt(0), "KK"),
updateGroupDescriptionEvent(uuidFromInt(0), "ABCDE"),
createPublicGroupEvent(uuidFromInt(1)),
updateGroupTitleEvent(uuidFromInt(1), "ABCDEFG"),
updateGroupDescriptionEvent(uuidFromInt(1), "KK"),
createPrivateGroupEvent());
assertThat(groupService.findGroupWith("A", account("jesus"))).hasSize(2);
assertThat(groupService.findGroupWith("F", account("jesus"))).hasSize(1);
assertThat(groupService.findGroupWith("Z", account("jesus"))).hasSize(0);
}
}