1 package de.dlr.shepard.neo4Core.services;
2
3 import java.util.ArrayList;
4 import java.util.List;
5
6 import de.dlr.shepard.neo4Core.dao.PermissionsDAO;
7 import de.dlr.shepard.neo4Core.dao.UserDAO;
8 import de.dlr.shepard.neo4Core.dao.UserGroupDAO;
9 import de.dlr.shepard.neo4Core.entities.Permissions;
10 import de.dlr.shepard.neo4Core.entities.User;
11 import de.dlr.shepard.neo4Core.entities.UserGroup;
12 import de.dlr.shepard.neo4Core.io.PermissionsIO;
13 import lombok.extern.slf4j.Slf4j;
14
15 @Slf4j
16 public class PermissionsService {
17
18 private PermissionsDAO permissionsDAO = new PermissionsDAO();
19 private UserDAO userDAO = new UserDAO();
20 private UserGroupDAO userGroupDAO = new UserGroupDAO();
21
22
23
24
25
26
27
28 public Permissions getPermissionsByEntity(long entityId) {
29 var permissions = permissionsDAO.findByEntity(entityId);
30 if (permissions == null) {
31 log.error("Permissions with entity id {} is null", entityId);
32 return null;
33 }
34 return permissions;
35 }
36
37
38
39
40
41
42
43 public Permissions createPermissions(long entityId) {
44 var permissions = new Permissions();
45 return permissionsDAO.createWithEntity(permissions, entityId);
46 }
47
48
49
50
51
52
53
54
55 public Permissions updatePermissions(PermissionsIO permissions, long entityId) {
56 var owner = permissions.getOwner() != null ? userDAO.find(permissions.getOwner()) : null;
57 var permissionType = permissions.getPermissionType();
58 var reader = fetchUsers(permissions.getReader());
59 var writer = fetchUsers(permissions.getWriter());
60 var readerGroups = fetchUserGroups(permissions.getReaderGroupIds());
61 var writerGroups = fetchUserGroups(permissions.getWriterGroupIds());
62 var manager = fetchUsers(permissions.getManager());
63 var old = getPermissionsByEntity(entityId);
64 if (old == null) {
65
66 var toCreate = new Permissions(owner, reader, writer, readerGroups, writerGroups, manager,
67 permissions.getPermissionType());
68 return permissionsDAO.createWithEntity(toCreate, entityId);
69 }
70 old.setOwner(owner);
71 old.setReader(reader);
72 old.setWriter(writer);
73 old.setReaderGroups(readerGroups);
74 old.setWriterGroups(writerGroups);
75 old.setManager(manager);
76 old.setPermissionType(permissionType);
77 return permissionsDAO.createOrUpdate(old);
78
79 }
80
81 private List<User> fetchUsers(String[] usernames) {
82 var result = new ArrayList<User>(usernames.length);
83 for (var username : usernames) {
84 if (username == null) {
85 continue;
86 }
87
88 var user = userDAO.find(username);
89 if (user != null) {
90 result.add(user);
91 }
92 }
93 return result;
94 }
95
96 private List<UserGroup> fetchUserGroups(long[] userGroupIds) {
97 var result = new ArrayList<UserGroup>(userGroupIds.length);
98 for (var userGroupId : userGroupIds) {
99 var userGroup = userGroupDAO.find(userGroupId);
100 if (userGroup != null) {
101 result.add(userGroup);
102 }
103 }
104 return result;
105 }
106 }