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