JUnits for coverage
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / portal / service / UserServiceImpl.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  *
8  * Unless otherwise specified, all software contained herein is licensed
9  * under the Apache License, Version 2.0 (the "License");
10  * you may not use this software except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *             http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  *
21  * Unless otherwise specified, all documentation contained herein is licensed
22  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23  * you may not use this documentation except in compliance with the License.
24  * You may obtain a copy of the License at
25  *
26  *             https://creativecommons.org/licenses/by/4.0/
27  *
28  * Unless required by applicable law or agreed to in writing, documentation
29  * distributed under the License is distributed on an "AS IS" BASIS,
30  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31  * See the License for the specific language governing permissions and
32  * limitations under the License.
33  *
34  * ============LICENSE_END============================================
35  *
36  * 
37  */
38 package org.onap.portalapp.portal.service;
39
40 import java.io.BufferedReader;
41 import java.io.IOException;
42 import java.io.InputStreamReader;
43 import java.net.HttpURLConnection;
44 import java.net.URL;
45 import java.util.ArrayList;
46 import java.util.List;
47
48 import org.hibernate.criterion.Criterion;
49 import org.hibernate.criterion.Restrictions;
50 import org.json.JSONArray;
51 import org.json.JSONObject;
52 import org.onap.portalapp.portal.domain.EPUser;
53 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
54 import org.onap.portalsdk.core.domain.FusionObject.Utilities;
55 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
56 import org.onap.portalsdk.core.onboarding.util.CipherUtil;
57 import org.onap.portalsdk.core.service.DataAccessService;
58 import org.onap.portalsdk.core.util.SystemProperties;
59 import org.springframework.beans.factory.annotation.Autowired;
60 import org.springframework.stereotype.Service;
61 import org.springframework.transaction.annotation.Transactional;
62
63 @Service("userService")
64 @Transactional
65 public class UserServiceImpl implements UserService {
66
67         private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserServiceImpl.class);
68
69         @Autowired
70         private DataAccessService dataAccessService;
71
72         public DataAccessService getDataAccessService() {
73                 return dataAccessService;
74         }
75
76         public void setDataAccessService(DataAccessService dataAccessService) {
77                 this.dataAccessService = dataAccessService;
78         }
79
80         @SuppressWarnings("unchecked")
81         @Override
82         public List<EPUser> getUserByUserId(String userId) {
83
84                 if (SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM).trim().equalsIgnoreCase("OIDC")) {
85                         List<EPUser> users = new ArrayList<EPUser>();
86                         List<EPUser> filterdUsers = new ArrayList<EPUser>();
87                         BufferedReader in = null;
88                         HttpURLConnection con = null;
89                         try {
90                                 String url = EPCommonSystemProperties.getProperty(EPCommonSystemProperties.AUTH_USER_SERVER);
91                                 URL obj = new URL(url);
92
93                                 con = (HttpURLConnection) obj.openConnection();
94
95                                 // optional default is GET
96                                 con.setRequestMethod("GET");
97                                 con.setConnectTimeout(3000);
98                                 con.setReadTimeout(8000);
99
100                                 StringBuffer response = new StringBuffer();
101
102                                 in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
103                                 String inputLine;
104                                 while ((inputLine = in.readLine()) != null)
105                                         response.append(inputLine);
106                                 JSONObject jObject = new JSONObject(response.toString()); // json
107                                 JSONArray jsonUsers = jObject.getJSONArray("response"); // get
108                                                                                                                                                 // data
109                                                                                                                                                 // object
110                                 for (int i = 0; i < jsonUsers.length(); i++) {
111                                         JSONObject eachObject = jsonUsers.getJSONObject(i);
112                                         EPUser eachUser = new EPUser();
113                                         eachUser.setOrgUserId(eachObject.get("id").toString());
114                                         eachUser.setFirstName(eachObject.get("givenName").toString());
115                                         eachUser.setLastName(eachObject.get("familyName").toString());
116                                         eachUser.setEmail(eachObject.get("email").toString());
117                                         users.add(eachUser);
118                                 }
119
120                                 for (int i = 0; i < users.size(); i++) {
121                                         if (Utilities.nvl(userId).length() > 0) {
122                                                 if (!userId.equalsIgnoreCase(users.get(i).getOrgUserId())) {
123                                                         continue;
124                                                 }
125                                         }
126                                         filterdUsers.add(users.get(i));
127                                 }
128
129                         } catch (Exception e) {
130                                 logger.error(EELFLoggerDelegate.errorLogger, "getUserByUserId failed", e);
131                         } finally {
132                                 try {
133                                         if(in!=null) {
134                                         in.close();
135                                         }
136                                         con.disconnect();
137                                 } catch (IOException e) {
138                                         logger.error(EELFLoggerDelegate.errorLogger, "getUserByUserId failed to close", e);
139                                 }
140                         }
141
142                         return filterdUsers;
143
144                 } else {
145
146                         List<Criterion> restrictionsList = new ArrayList<Criterion>();
147                         Criterion orgUserIdCriterion = Restrictions.eq("orgUserId",userId);
148                         restrictionsList.add(orgUserIdCriterion);
149                         
150                         List<EPUser> list = (List<EPUser>) dataAccessService.getList(EPUser.class, null, restrictionsList, null);
151
152                         return (list == null || list.size() == 0) ? null : list;
153
154                 }
155
156         }
157
158         @SuppressWarnings("unchecked")
159         @Override
160         public List<EPUser> getUserByFirstLastName(String firstName, String lastName) {
161
162                 if (!SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM).trim().equalsIgnoreCase("OIDC")) {
163                         List<Criterion> restrictionsList = new ArrayList<Criterion>();
164                         Criterion firstNameCriterion = Restrictions.eq("firstName", firstName);
165                         Criterion lastNameCriterion = Restrictions.eq("lastName", lastName);
166                         restrictionsList.add(Restrictions.or(firstNameCriterion, lastNameCriterion));
167
168                         List<EPUser> list = (List<EPUser>) dataAccessService.getList(EPUser.class, null, restrictionsList, null);
169                         return (list == null || list.size() == 0) ? null : list;
170
171                 } else {
172
173                         List<EPUser> users = new ArrayList<EPUser>();
174                         List<EPUser> filterdUsers = new ArrayList<EPUser>();
175                         BufferedReader in = null;
176                         HttpURLConnection con = null;
177                         try {
178                                 String url = EPCommonSystemProperties.getProperty(EPCommonSystemProperties.AUTH_USER_SERVER);
179                                 URL obj = new URL(url);
180
181                                 con = (HttpURLConnection) obj.openConnection();
182
183                                 // optional default is GET
184                                 con.setRequestMethod("GET");
185                                 con.setConnectTimeout(3000);
186                                 con.setReadTimeout(8000);
187
188                                 StringBuffer response = new StringBuffer();
189
190                                 in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
191                                 String inputLine;
192                                 while ((inputLine = in.readLine()) != null) {
193                                         response.append(inputLine);
194                                 }
195                                 JSONObject jObject = new JSONObject(response.toString()); // json
196                                 JSONArray jsonUsers = jObject.getJSONArray("response"); // get
197                                                                                                                                                 // data
198                                                                                                                                                 // object
199                                 for (int i = 0; i < jsonUsers.length(); i++) {
200                                         JSONObject eachObject = jsonUsers.getJSONObject(i);
201                                         EPUser eachUser = new EPUser();
202                                         eachUser.setOrgUserId(eachObject.get("id").toString());// getString("id"));
203                                         eachUser.setFirstName(eachObject.get("givenName").toString());
204                                         eachUser.setLastName(eachObject.get("familyName").toString());
205                                         eachUser.setEmail(eachObject.get("email").toString());
206                                         users.add(eachUser);
207                                 }
208
209                                 for (int i = 0; i < users.size(); i++) {
210
211                                         if (Utilities.nvl(firstName).length() > 0) {
212                                                 if (!firstName.equalsIgnoreCase(users.get(i).getFirstName())) {
213                                                         continue;
214                                                 }
215                                         }
216                                         if (Utilities.nvl(lastName).length() > 0) {
217                                                 if (!lastName.equalsIgnoreCase(users.get(i).getLastName())) {
218                                                         continue;
219                                                 }
220                                         }
221
222                                         filterdUsers.add(users.get(i));
223
224                                 }
225
226                         } catch (Exception e) {
227                                 logger.error(EELFLoggerDelegate.errorLogger, "getUserByFirstLastName failed", e);
228                         } finally {
229                                 try {
230                                         if(in!=null) {
231                                         in.close();
232                                         con.disconnect();
233                                         }
234                                 } catch (IOException e) {
235                                         logger.error(EELFLoggerDelegate.errorLogger, "getUserByFirstLastName failed to close", e);
236                                 }
237                         }
238
239                         return filterdUsers;
240                 }
241
242         }
243
244         @SuppressWarnings("unchecked")
245         public String saveNewUser(EPUser newUser, String checkDuplicate) throws Exception {
246
247                 try {
248
249                         List<Criterion> restrictionsList = new ArrayList<Criterion>();
250                         Criterion orgUserIdCriterion = Restrictions.eq("orgUserId",newUser.getLoginId());
251                         restrictionsList.add(orgUserIdCriterion);
252                         List<EPUser> list = (List<EPUser>) dataAccessService.getList(EPUser.class, null, restrictionsList, null);
253                         
254                         if (list == null || list.size() == 0) {
255                                 newUser.setActive(true);
256                                 newUser.setOrgUserId(newUser.getLoginId());
257                                 newUser.setLoginPwd(CipherUtil.encryptPKC(newUser.getLoginPwd()));
258                                 getDataAccessService().saveDomainObject(newUser, null);
259                         } else {
260                                 if (checkDuplicate.equals("Yes")) {
261                                         // userId already exist in database
262                                         return "Record already exist";
263                                 } else {
264
265                                         EPUser oldUser = (EPUser) list.get(0);
266                                         oldUser.setFirstName(newUser.getFirstName());
267                                         oldUser.setLastName(newUser.getLastName());
268                                         oldUser.setMiddleInitial(newUser.getMiddleInitial());
269                                         if (!oldUser.getLoginPwd().equals(newUser.getLoginPwd()))
270                                                 oldUser.setLoginPwd(CipherUtil.encryptPKC(newUser.getLoginPwd()));
271                                         else
272                                                 oldUser.setLoginPwd(newUser.getLoginPwd());
273                                         getDataAccessService().saveDomainObject(oldUser, null);
274
275                                 }
276
277                         }
278
279                 } catch (Exception e) {
280                         logger.error(EELFLoggerDelegate.errorLogger, "saveNewUser failed", e);
281                         throw new Exception(e);
282                 }
283                 return "success";
284         };
285
286         @Override
287         public void saveUser(EPUser user) throws Exception {
288                 getDataAccessService().saveDomainObject(user, null);
289         }
290
291 }