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