Remove code smells in dashboard
[nonrtric.git] / dashboard / webapp-backend / src / main / java / org / oransc / ric / portal / dashboard / DashboardUserManager.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2019 AT&T Intellectual Property
6  * %%
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ========================LICENSE_END===================================
19  */
20 package org.oransc.ric.portal.dashboard;
21
22 import com.fasterxml.jackson.core.type.TypeReference;
23 import com.fasterxml.jackson.databind.ObjectMapper;
24
25 import java.io.File;
26 import java.io.IOException;
27 import java.lang.invoke.MethodHandles;
28 import java.nio.file.Files;
29 import java.util.ArrayList;
30 import java.util.HashSet;
31 import java.util.List;
32 import java.util.Set;
33
34 import org.onap.portalsdk.core.onboarding.exception.PortalAPIException;
35 import org.onap.portalsdk.core.restful.domain.EcompRole;
36 import org.onap.portalsdk.core.restful.domain.EcompUser;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 /**
41  * Provides simple user-management services.
42  *
43  * This first implementation serializes user details to a file.
44  */
45 public class DashboardUserManager {
46
47     private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
48
49     // This default value is only useful for development and testing.
50     public static final String USER_FILE_PATH = "dashboard-users.json";
51
52     private final File userFile;
53     private final List<EcompUser> users;
54
55     /**
56      * Development/test-only constructor that uses default file path.
57      *
58      * @param clear
59      *        If true, start empty and remove any existing file.
60      *
61      * @throws IOException
62      *         On file error
63      */
64     public DashboardUserManager(boolean clear) throws IOException {
65         this(USER_FILE_PATH);
66         if (clear) {
67             logger.debug("ctor: removing file {}", userFile.getAbsolutePath());
68             File f = new File(DashboardUserManager.USER_FILE_PATH);
69             if (f.exists())
70                 Files.delete(f.toPath());
71             users.clear();
72         }
73     }
74
75     /**
76      * Constructur that accepts a file path
77      *
78      * @param userFilePath
79      *        File path
80      * @throws IOException
81      *         If file cannot be read
82      */
83     public DashboardUserManager(final String userFilePath) throws IOException {
84         logger.debug("ctor: userfile {}", userFilePath);
85         if (userFilePath == null)
86             throw new IllegalArgumentException("Missing or empty user file property");
87         userFile = new File(userFilePath);
88         logger.debug("ctor: managing users in file {}", userFile.getAbsolutePath());
89         if (userFile.exists()) {
90             final ObjectMapper mapper = new ObjectMapper();
91             users = mapper.readValue(userFile, new TypeReference<List<EcompUser>>() {});
92         } else {
93             users = new ArrayList<>();
94         }
95     }
96
97     /**
98      * Gets the current users.
99      *
100      * @return List of EcompUser objects, possibly empty
101      */
102     public List<EcompUser> getUsers() {
103         return this.users;
104     }
105
106     /**
107      * Gets the user with the specified login Id
108      *
109      * @param loginId
110      *        Desired login Id
111      * @return User object; null if Id is not known
112      */
113     public EcompUser getUser(String loginId) {
114         for (EcompUser u : this.users) {
115             if (u.getLoginId().equals(loginId)) {
116                 logger.debug("getUser: match on {}", loginId);
117                 return u;
118             }
119         }
120         logger.debug("getUser: no match on {}", loginId);
121         return null;
122     }
123
124     private void saveUsers() throws IOException {
125         final ObjectMapper mapper = new ObjectMapper();
126         mapper.writeValue(userFile, users);
127     }
128
129     /*
130      * Allow at most one thread to create a user at one time.
131      */
132     public synchronized void createUser(EcompUser user) throws PortalAPIException {
133         if (logger.isDebugEnabled()) {
134             logger.debug("createUser: loginId is {}", user.getLoginId());
135         }
136         if (users.contains(user))
137             throw new PortalAPIException("User exists: " + user.getLoginId());
138         users.add(user);
139         try {
140             saveUsers();
141         } catch (Exception ex) {
142             throw new PortalAPIException("Save failed", ex);
143         }
144     }
145
146     /*
147      * Allow at most one thread to modify a user at one time. We still have
148      * last-edit-wins of course.
149      */
150     public synchronized void updateUser(String loginId, EcompUser user) throws PortalAPIException {
151         logger.debug("editUser: loginId is {}", loginId);
152         int index = users.indexOf(user);
153         if (index < 0)
154             throw new PortalAPIException("User does not exist: " + user.getLoginId());
155         users.remove(index);
156         users.add(user);
157         try {
158             saveUsers();
159         } catch (Exception ex) {
160             throw new PortalAPIException("Save failed", ex);
161         }
162     }
163
164     // Test infrastructure
165     public static void main(String[] args) throws Exception {
166         DashboardUserManager dum = new DashboardUserManager(false);
167         EcompUser user = new EcompUser();
168         user.setActive(true);
169         user.setLoginId("demo");
170         user.setFirstName("First");
171         user.setLastName("Last");
172         EcompRole role = new EcompRole();
173         role.setId(1L);
174         role.setName(DashboardConstants.ROLE_NAME_ADMIN);
175         Set<EcompRole> roles = new HashSet<>();
176         roles.add(role);
177         user.setRoles(roles);
178         dum.createUser(user);
179         logger.debug("Created user {}", user);
180     }
181
182 }