Merge "Drop Nokia from file header copyright line, part 2"
[portal/ric-dashboard.git] / 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 java.io.File;
23 import java.io.IOException;
24 import java.lang.invoke.MethodHandles;
25 import java.util.ArrayList;
26 import java.util.HashSet;
27 import java.util.List;
28 import java.util.Set;
29
30 import org.onap.portalsdk.core.onboarding.exception.PortalAPIException;
31 import org.onap.portalsdk.core.restful.domain.EcompRole;
32 import org.onap.portalsdk.core.restful.domain.EcompUser;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35
36 import com.fasterxml.jackson.core.JsonGenerationException;
37 import com.fasterxml.jackson.core.type.TypeReference;
38 import com.fasterxml.jackson.databind.JsonMappingException;
39 import com.fasterxml.jackson.databind.ObjectMapper;
40
41 /**
42  * Provides simple user-management services.
43  * 
44  * This first implementation serializes user details to a file.
45  * 
46  * TODO: migrate to a database.
47  */
48 public class DashboardUserManager {
49
50         private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
51
52         public static final String USER_FILE_PATH = "/tmp/dashboard-users.json";
53
54         private final File userFile;
55         private final List<EcompUser> users;
56
57         /**
58          * convenience constructor that uses default file path
59          * 
60          * @param clear
61          *                  If true, start empty and remove any existing file.
62          * 
63          * @throws IOException
64          *                         On file error
65          */
66         public DashboardUserManager(boolean clear) throws IOException {
67                 this(USER_FILE_PATH);
68                 if (clear) {
69                         logger.debug("ctor: removing file {}", userFile.getAbsolutePath());
70                         File f = new File(DashboardUserManager.USER_FILE_PATH);
71                         if (f.exists())
72                                 f.delete();
73                         users.clear();
74                 }
75         }
76
77         /**
78          * Uses specified file path
79          * 
80          * @param userFilePath
81          *                         File path
82          * @throws IOException
83          *                         If file cannot be read
84          */
85         public DashboardUserManager(final String userFilePath) throws IOException {
86                 logger.debug("ctor: userfile {}", userFilePath);
87                 if (userFilePath == null)
88                         throw new IllegalArgumentException("Missing or empty user file property");
89                 userFile = new File(userFilePath);
90                 logger.debug("ctor: managing users in file {}", userFile.getAbsolutePath());
91                 if (userFile.exists()) {
92                         final ObjectMapper mapper = new ObjectMapper();
93                         users = mapper.readValue(userFile, new TypeReference<List<EcompUser>>() {
94                         });
95                 } else {
96                         users = new ArrayList<>();
97                 }
98         }
99
100         /**
101          * Gets the current users.
102          * 
103          * @return List of EcompUser objects, possibly empty
104          */
105         public List<EcompUser> getUsers() {
106                 return this.users;
107         }
108
109         /**
110          * Gets the user with the specified login Id
111          * 
112          * @param loginId
113          *                    Desired login Id
114          * @return User object; null if Id is not known
115          */
116         public EcompUser getUser(String loginId) {
117                 for (EcompUser u : this.users) {
118                         if (u.getLoginId().equals(loginId)) {
119                                 logger.debug("getUser: match on {}", loginId);
120                                 return u;
121                         }
122                 }
123                 logger.debug("getUser: no match on {}", loginId);
124                 return null;
125         }
126
127         private void saveUsers() throws JsonGenerationException, JsonMappingException, IOException {
128                 final ObjectMapper mapper = new ObjectMapper();
129                 mapper.writeValue(userFile, users);
130         }
131
132         /*
133          * Allow at most one thread to create a user at one time.
134          */
135         public synchronized void createUser(EcompUser user) throws PortalAPIException {
136                 logger.debug("createUser: loginId is " + user.getLoginId());
137                 if (users.contains(user))
138                         throw new PortalAPIException("User exists: " + user.getLoginId());
139                 users.add(user);
140                 try {
141                         saveUsers();
142                 } catch (Exception ex) {
143                         throw new PortalAPIException("Save failed", ex);
144                 }
145         }
146
147         /*
148          * Allow at most one thread to modify a user at one time. We still have
149          * last-edit-wins of course.
150          */
151         public synchronized void updateUser(String loginId, EcompUser user) throws PortalAPIException {
152                 logger.debug("editUser: loginId is " + loginId);
153                 int index = users.indexOf(user);
154                 if (index < 0)
155                         throw new PortalAPIException("User does not exist: " + user.getLoginId());
156                 users.remove(index);
157                 users.add(user);
158                 try {
159                         saveUsers();
160                 } catch (Exception ex) {
161                         throw new PortalAPIException("Save failed", ex);
162                 }
163         }
164
165         // Test infrastructure
166         public static void main(String[] args) throws Exception {
167                 DashboardUserManager dum = new DashboardUserManager(false);
168                 EcompUser user = new EcompUser();
169                 user.setActive(true);
170                 user.setLoginId("demo");
171                 user.setFirstName("First");
172                 user.setLastName("Last");
173                 EcompRole role = new EcompRole();
174                 role.setId(1L);
175                 role.setName(DashboardConstants.ROLE_NAME_ADMIN);
176                 Set<EcompRole> roles = new HashSet<>();
177                 roles.add(role);
178                 user.setRoles(roles);
179                 dum.createUser(user);
180                 logger.debug("Created user {}", user);
181         }
182
183 }