968bdd6471a1bbf54c7fbc0d18e2ea616dc4dac3
[portal/sdk.git] /
1 /*
2  * ============LICENSE_START==========================================
3  * ONAP Portal SDK
4  * ===================================================================
5  * Copyright © 2017 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  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
37  */
38 package org.onap.portalsdk.analytics.system.fusion.adapter;
39
40 import java.util.HashMap;
41 import java.util.HashSet;
42 import java.util.Iterator;
43 import java.util.LinkedHashMap;
44 import java.util.List;
45 import java.util.Map;
46 import java.util.Set;
47 import java.util.TreeSet;
48
49 import javax.servlet.http.HttpServletRequest;
50 import javax.servlet.http.HttpSession;
51
52 import org.onap.portalsdk.analytics.system.AppUtils;
53 import org.onap.portalsdk.core.domain.Menu;
54 import org.onap.portalsdk.core.domain.MenuData;
55 import org.onap.portalsdk.core.domain.Role;
56 import org.onap.portalsdk.core.domain.RoleFunction;
57 import org.onap.portalsdk.core.domain.User;
58 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
59 import org.onap.portalsdk.core.service.DataAccessService;
60 import org.onap.portalsdk.core.util.SystemProperties;
61 import org.onap.portalsdk.core.web.support.UserUtils;
62 import org.springframework.beans.factory.annotation.Autowired;
63 import org.springframework.stereotype.Service;
64
65 @Service("raptorAdapter")
66 public class RaptorAdapter extends FusionAdapter {
67         
68         private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RaptorAdapter.class);
69
70         @Autowired
71         private static DataAccessService dataAccessService;
72   
73     public static final int    RAPTOR_USER_ID              = 20000; // RAPTOR system user id (for auditing purposes)
74     public static final String RAPTOR_CONTROLLER_CLASSNAME = "org.onap.portalsdk.analytics.controller.Controller";
75     public static final String KEY_USER_ROLES_CACHE        =  "userRoles";
76     
77     public void initializeRaptor() {
78         org.onap.portalsdk.analytics.config.ConfigLoader.setConfigFilesPath(SystemProperties.getProperty(SystemProperties.RAPTOR_CONFIG_FILE_PATH));
79         org.onap.portalsdk.analytics.system.Globals.initializeSystem(getServletContext());
80     }
81
82
83     /** Returns ID of the user currently logged in */
84     public static String getUserID(HttpServletRequest request) {
85         return String.valueOf(UserUtils.getUserId(request));
86         //return null;
87     }
88
89     public static String getUserID(String user_id) {
90         return user_id;
91     }    
92     
93
94     public static String getUserBackdoorLoginId(HttpServletRequest request) {
95       if(AppUtils.getRequestNvlValue(request, "login_id").length()>0) return AppUtils.getRequestNvlValue(request, "login_id");
96         return String.valueOf(UserUtils.getUserSession(request).getLoginId());
97     }
98
99     public static String getUserBackdoorLoginId(String user_id) {
100          return getUserLoginId(user_id);
101       }
102
103     /** Obtains user name by ID */
104     public static String getUserName(String userId) {
105         Map<String, Long> params = new HashMap<String, Long>();
106         params.put("user_id", new Long(userId));
107
108         List list = getDataAccessService().executeNamedQuery("getUserNameById", params, null);
109
110         String firstName = "";
111         String lastName = "";
112
113         if (list != null) {
114             if (!list.isEmpty()) {
115                 Object[] user = (Object[]) list.get(0);
116                 firstName = (String) user[0]; // firstName scalar
117                 lastName = (String) user[1]; // lastName scalar
118             }
119         }
120
121         return lastName + ", " + firstName;
122     }
123
124     public static String getUserName(HttpServletRequest request) {
125         User user = UserUtils.getUserSession(request);
126         return user.getLastName() + ", " + user.getFirstName();
127     }
128     
129     public static String getUserEmail(String userId) {
130         Map<String, Long> params = new HashMap<String, Long>();
131         params.put("user_id", new Long(userId));
132         List list = getDataAccessService().executeNamedQuery("getUserEmail", params, null);
133         String email = "";
134         if (list != null && !list.isEmpty())
135             email = (String) list.get(0);
136         return email;
137     }
138
139     public static String getUserEmail(HttpServletRequest request) {
140         User user = UserUtils.getUserSession(request);
141         return user.getEmail();
142     }
143     
144     public static String getUserLoginId(String userId) {
145         
146         String loginId = "";
147         try{
148                 List  list = getDataAccessService().getList(User.class, " where user_id = " + userId, null, null);
149                 if (list != null) {
150               if (!list.isEmpty()) {
151                 User user = (User)list.get(0);
152                 loginId = user.getLoginId(); // firstName scalar            
153               }
154             }
155         }catch(Exception e){
156                 logger.error(EELFLoggerDelegate.debugLogger, ("error while getting login id : Exception" + e.getMessage()));
157         }
158         return loginId;
159       }
160
161     
162     public static String getUserLoginId(HttpServletRequest request) {
163         User user = UserUtils.getUserSession(request);
164         return user.getLoginId();
165     }
166     
167     /** Obtains list of all users (in IdNameValue objects) */
168     public static Map<Long, String> getAllUsers(String customizedQuery, String param, boolean isAdmin) {      
169         List users = null;
170         Map<Long, String> map = new LinkedHashMap<Long, String>();
171         
172         if(customizedQuery.length()>0 && !isAdmin) {
173
174                 users = getDataAccessService().executeSQLQuery(customizedQuery, IdName.class, null);
175
176                 if (users != null) {                    
177                         Iterator i = users.iterator();
178                         while (i.hasNext()) {
179                                 IdName item = (IdName)i.next();
180                                 map.put(item.getId(), item.getName());
181                         }
182                 }
183                 
184         } else {
185             users = getDataAccessService().executeNamedQuery("getAllUsers", null, null);
186             if (users != null) {
187               Iterator i = users.iterator();
188                while (i.hasNext()) {
189                  Object[]    user = (Object[])i.next();
190                  Long          id = (Long)user[0];   // id scalar
191                  String firstName = (String)user[1]; // firstName scalar
192                  String  lastName = (String)user[2]; // lastName scalar
193                  map.put(id, lastName + ", " + firstName);
194               }
195             }                   
196         }
197       return map;
198     }
199
200     /** Obtains role name by ID */
201     public static String getRoleName(String roleId) {
202         Map<String, Long> params = new HashMap<String, Long>();
203         params.put("role_id", new Long(roleId));
204
205         List list = getDataAccessService().executeNamedQuery("getRoleNameById", params, null);
206
207         String roleName = "";
208
209         if (list != null) {
210             if (!list.isEmpty()) {
211                 roleName = (String) list.get(0); // name scalar
212             }
213         }
214
215         return roleName;
216     }
217
218     /** Obtains list of all roles (in IdNameValue objects) */
219     public static Map<Long, String> getAllRolesUsingCustomizedQuery(String customizedQuery, String param, boolean isAdmin) {
220         List roles = null;
221
222         Map<Long, String> map = new LinkedHashMap<Long, String>();
223
224         if(customizedQuery.length()>0  && !isAdmin) {
225
226                 roles = getDataAccessService().executeSQLQuery(customizedQuery, IdName.class, null);
227
228                 if (roles != null) {                    
229                         Iterator i = roles.iterator();
230                         while (i.hasNext()) {
231                                 IdName item = (IdName)i.next();
232                                 map.put(item.getId(), item.getName());
233                         }
234                 }
235         } else {
236
237                 roles = getDataAccessService().executeNamedQuery("getAllRoles", null, null);      
238
239                 if (roles != null) {
240                         Iterator i = roles.iterator();
241                         while (i.hasNext()) {
242                                 Object[]    role = (Object[])i.next();
243                                 Long          id = (Long)role[0];   // id scalar
244                                 String name = (String)role[1]; // firstName scalar
245                                 map.put(id, name);
246                         }
247                 }               
248         }
249
250         return map;
251     }
252
253     public static Set getUserRoles(HttpServletRequest request) {
254         return UserUtils.getRoles(request).keySet();
255     }
256     
257     public static Set getUserRoles(String userId) {
258         Set     userRoles                       = new HashSet<Long>();
259 //        Map usersRolesMap                     = new LinkedHashMap<Long, Set>();
260 //        Map<String, Long> params      = new HashMap<String, Long>();
261 //        
262 //        params.put("user_id", new Long(userId));
263 //        
264 //      List usersRolesList             = getDataAccessService().executeNamedQuery("getAllUsersRoles", params, null);
265 //      Iterator    i                           = usersRolesList.iterator();
266 //        while (i.hasNext()) {
267 //              Object[] userRole = (Object[]) i.next();
268 //
269 //              Long roleId = (Long) userRole[1]; // role id scalar
270 //              userRoles.add(roleId);
271 //
272 //        }
273         userRoles = getActiveUsersRoleIds(new Long(userId));
274
275         
276         return userRoles;
277     }
278
279         /** this is used to get role for the current user. **/
280     public static synchronized boolean isCurrentUserInRole(HttpServletRequest request, String roleId) { 
281         HttpSession session = request.getSession(false);
282         if(session!=null && session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME))!=null)
283                 return UserUtils.hasRole(request, roleId);
284         else
285                 return false;
286     }
287
288     /** Obtains menu label by ID */
289     public static String getMenuLabel(String menuId) {
290         return ((Menu) getDataAccessService().getDomainObject(MenuData.class, new Long(menuId), null)).getLabel();
291     }
292   
293     public static String formatUserDateForDBTimeZone(String dateValue,String inPattern, 
294                 Long userId, String outPattern)throws Exception{
295         return DateUtils.formatUserDateForDBTimeZone(dateValue,inPattern,userId,outPattern);
296     }
297     
298     public static String getCurrentDBDateForUser(String inPattern,Long userId)throws Exception{
299         return DateUtils.getCurrentDBDateForUser(inPattern, userId);
300     }
301     
302         public static Set<Long> getActiveUsersRoleIds(Long userId) {
303                 Set<Role> allActiveUserRoles = getActiveUserRoles(userId);
304                 Iterator<Role> allActiveUserRolesIterator = allActiveUserRoles.iterator();
305                 Set<Long> allActiveUserRoleIds = new TreeSet<Long>();
306                 while(allActiveUserRolesIterator.hasNext()){
307                         Role role = allActiveUserRolesIterator.next();
308                         allActiveUserRoleIds.add(role.getId());
309                 }
310
311                 return allActiveUserRoleIds;
312         }
313         
314         public static Set<Long> getActiveUserRoleIds(Long userId) {
315                 Set<Role> allActiveUserRoles = getActiveUserRoles(userId);
316                 Iterator<Role> allActiveUserRolesIterator = allActiveUserRoles.iterator();
317                 Set<Long> allActiveUserRoleIds = new TreeSet<Long>();
318                 while(allActiveUserRolesIterator.hasNext()){
319                         Role role = allActiveUserRolesIterator.next();
320                         allActiveUserRoleIds.add(role.getId());
321                 }
322
323                 return allActiveUserRoleIds;
324         }
325         
326         public static Set<RoleFunction> getActiveRoleFunctions(Long userId) {
327                 Set<Role> allActiveUserRoles = getActiveUserRoles(userId);
328                 Iterator<Role> allActiveUserRolesIterator = allActiveUserRoles.iterator();
329                 Set<RoleFunction> allActiveRoleFunctions = new TreeSet<RoleFunction>();
330                 while(allActiveUserRolesIterator.hasNext()){
331                         Role role = allActiveUserRolesIterator.next();
332                         allActiveRoleFunctions.addAll(role.getRoleFunctions());
333                 }
334
335                 return allActiveRoleFunctions;
336         }
337
338         public static Set<Role> getActiveUserRoles(Long userId) {
339                 User user = (User)getDataAccessService().getDomainObject(User.class,userId,null);
340                 Set<Role> allActiveUserRoles = new TreeSet<Role>();
341                 allActiveUserRoles.addAll(user.getRoles());
342                 Iterator<Role> userRolesIterator = user.getRoles().iterator();
343                 while(userRolesIterator.hasNext()){
344                         getAllChildRoles( userRolesIterator.next(),allActiveUserRoles);
345                 }
346                 
347                 Iterator<Role> allActiveUserRolesIterator = allActiveUserRoles.iterator();
348                 while(allActiveUserRolesIterator.hasNext()){
349                         Role role = allActiveUserRolesIterator.next();
350                         if(!role.getActive()){
351                                 allActiveUserRolesIterator.remove();
352                         }
353                 }
354
355                 return allActiveUserRoles;
356         }
357         
358         public static Set<Role> getAllChildRoles(Role role, Set<Role> allchildRoles) {
359                 Set<Role> childRoles = role.getChildRoles();
360                 allchildRoles.addAll(childRoles);
361                 Iterator<Role> childRolesIterator = childRoles.iterator();
362                 while (childRolesIterator.hasNext()) {
363                         getAllChildRoles(childRolesIterator.next(),allchildRoles);
364                 }
365                 return allchildRoles;
366         }
367
368
369         public static DataAccessService getDataAccessService() {
370                 return org.onap.portalsdk.core.web.support.AppUtils.getDataAccessService();
371         }
372
373
374         public static void setDataAccessService(DataAccessService dataAccessService) {
375                 dataAccessService = dataAccessService;
376         }
377         
378         
379
380 }