[PORTAL-16 PORTAL-18] Widget ms; staging
[portal.git] / ecomp-portal-BE-common / src / main / java / org / openecomp / portalapp / portal / service / EPLdapServiceImpl.java
1 /*-
2  * ================================================================================
3  * ECOMP Portal
4  * ================================================================================
5  * Copyright (C) 2017 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  * ================================================================================
19  */
20 package org.openecomp.portalapp.portal.service;
21
22 import java.util.ArrayList;
23 import java.util.Collections;
24 import java.util.List;
25
26 import javax.naming.NamingEnumeration;
27 import javax.naming.NamingException;
28 import javax.naming.directory.Attribute;
29 import javax.naming.directory.Attributes;
30 import javax.naming.directory.DirContext;
31 import javax.naming.directory.SearchControls;
32
33 import org.slf4j.MDC;
34 import org.springframework.beans.factory.annotation.Autowired;
35 import org.springframework.context.annotation.EnableAspectJAutoProxy;
36 import org.springframework.stereotype.Service;
37 import org.springframework.transaction.annotation.Transactional;
38
39 import org.openecomp.portalsdk.core.command.support.SearchResult;
40 import org.openecomp.portalsdk.core.domain.support.DomainVo;
41 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
42 import org.openecomp.portalsdk.core.service.support.FusionService;
43 import org.openecomp.portalsdk.core.service.support.ServiceLocator;
44 import org.openecomp.portalsdk.core.util.SystemProperties;
45 import org.openecomp.portalapp.portal.domain.EPUser;
46 import org.openecomp.portalapp.portal.logging.aop.EPAuditLog;
47 import org.openecomp.portalapp.portal.logging.aop.EPMetricsLog;
48 import org.openecomp.portalapp.portal.utils.EPCommonSystemProperties;
49 import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
50
51 @Service("epLdapService")
52 @Transactional
53 @org.springframework.context.annotation.Configuration
54 @EnableAspectJAutoProxy
55 public class EPLdapServiceImpl extends FusionService implements EPLdapService {
56         @Autowired
57         private ServiceLocator serviceLocator;
58         
59         EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPLdapServiceImpl.class);
60
61         @EPAuditLog
62     @SuppressWarnings({ "rawtypes", "unchecked" })
63         public SearchResult searchPost(DomainVo searchCriteria, String sortBy1, String sortBy2, String sortBy3, 
64                 int pageNo, int dataSize, int userId) throws Exception {
65
66         String remoteHost = "";
67                         
68                 // initialize the directory context to access POST
69         DirContext dirContext = serviceLocator.getDirContext(SystemProperties.getProperty(SystemProperties.POST_INITIAL_CONTEXT_FACTORY),
70                                                                   SystemProperties.getProperty(SystemProperties.POST_PROVIDER_URL),
71                                                                   SystemProperties.getProperty(SystemProperties.POST_SECURITY_PRINCIPAL));
72         
73         SearchResult searchResult = new SearchResult();
74
75         try {
76         
77                 remoteHost = String.format("%s/%s", SystemProperties.getProperty(SystemProperties.POST_PROVIDER_URL), 
78                                                                         SystemProperties.getProperty(SystemProperties.POST_SECURITY_PRINCIPAL));
79                 MDC.put(EPCommonSystemProperties.FULL_URL, remoteHost);
80                 
81           String[] postAttributes =  {"nickname","givenName","initials","sn","employeeNumber","mail","telephoneNumber",
82                                 "departmentNumber","a1","street","roomNumber","l","st","postalCode","zip4","physicalDeliveryOfficeName","bc",
83                                 "friendlyCountryName","bd","bdname","bu","buname","jtname","mgrid","a2","compcode","compdesc",
84                                 "costcenter","silo","b2"};
85
86           SearchControls searchControls = new SearchControls();
87           searchControls.setTimeLimit(5000);
88           searchControls.setReturningAttributes(postAttributes);
89
90           StringBuffer filterClause = new StringBuffer("(&(objectClass=*)");
91
92           EPUser user = (EPUser)searchCriteria;
93
94           if(Utilities.nvl(user.getFirstName()).length() > 0) {
95             filterClause.append("(givenName=").append(user.getFirstName()).append("*)");
96           }
97           if(Utilities.nvl(user.getLastName()).length() > 0) {
98             filterClause.append("(sn=").append(user.getLastName()).append("*)");
99           }
100           if(Utilities.nvl(user.getHrid()).length() > 0) {
101             filterClause.append("(employeeNumber=").append(user.getHrid()).append("*)");
102           }
103           if(Utilities.nvl(user.getOrgManagerUserId()).length() > 0) {
104               filterClause.append("(mgrid=").append(user.getOrgManagerUserId()).append("*)");
105             }
106           if(Utilities.nvl(user.getOrgCode()).length() > 0) {
107             filterClause.append("(departmentNumber=").append(user.getOrgCode()).append("*)");
108           }
109           if(Utilities.nvl(user.getEmail()).length() > 0) {
110             filterClause.append("(mail=").append(user.getEmail()).append("*)");
111           }
112           if(Utilities.nvl(user.getOrgUserId()).length() > 0) {
113             filterClause.append("(a1=").append(user.getOrgUserId()).append("*)");
114           }
115           filterClause.append("(c3=N)"); // this has been added to filter CP09 entries on the LDAP server that are duplicates of existing individuals
116           filterClause.append(")");
117
118           List list = new ArrayList();
119           if (!filterClause.toString().equals("(&(objectClass=*))")) {
120                   NamingEnumeration e = dirContext.search(SystemProperties.getProperty(SystemProperties.POST_PROVIDER_URL) + "/" +
121                                                       SystemProperties.getProperty(SystemProperties.POST_SECURITY_PRINCIPAL),
122                                                       filterClause.toString(),
123                                                       searchControls);
124                   list = processResults(e);
125           }
126           
127           Collections.sort(list);
128
129           searchResult = new SearchResult(list);
130           searchResult.setPageNo(pageNo);
131           if(dataSize >= 0) {
132             searchResult.setDataSize(dataSize);
133           }
134           else {
135             searchResult.setDataSize(list.size());
136           }
137         } catch(NamingException ne) {
138                 String stackTrace = EcompPortalUtils.getStackTrace(ne);
139                 logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing the LDAP search. Details: " + stackTrace);
140         } catch(Exception e) {
141                 String stackTrace = EcompPortalUtils.getStackTrace(e);
142                 logger.error(EELFLoggerDelegate.errorLogger, "Exception occurred while performing the LDAP search. Details: " + stackTrace);
143         }
144         finally {
145                 dirContext.close();
146         }
147
148         return searchResult;
149     }
150
151
152     @SuppressWarnings({ "rawtypes", "unchecked" })
153     @EPMetricsLog
154         private ArrayList processResults(NamingEnumeration e) throws NamingException {
155       ArrayList results = new ArrayList();
156       int count = 0;
157
158       while (e.hasMore()) {
159         javax.naming.directory.SearchResult searchResult = (javax.naming.directory.SearchResult)e.next();
160         results.add(processAttributes(searchResult.getAttributes()));
161         count++;
162
163         if(count > Integer.parseInt(SystemProperties.getProperty(SystemProperties.POST_MAX_RESULT_SIZE))) {
164           break;
165         }
166       }
167       return results;
168     }
169
170
171     @SuppressWarnings("rawtypes")
172     @EPMetricsLog
173         private DomainVo processAttributes(Attributes resultAttributes) throws NamingException {
174       EPUser user = new EPUser();
175
176       try {
177         if (resultAttributes == null) {
178           logger.debug(EELFLoggerDelegate.debugLogger, "This result has no attributes");
179         } else {
180           for (NamingEnumeration e = resultAttributes.getAll(); e.hasMore();) { //why the nested loop?
181             Attribute attribute = (Attribute)e.next();
182             for (NamingEnumeration ie = attribute.getAll(); ie.hasMore();) {
183               if (attribute.getID().equalsIgnoreCase("nickname")) {
184                   user.setFirstName((String) ie.next());
185               }
186               else if (attribute.getID().equalsIgnoreCase("initials")) {
187                   user.setMiddleInitial((String) ie.next());
188               }
189               else if (attribute.getID().equalsIgnoreCase("sn")) {
190                   user.setLastName((String) ie.next());
191               }
192               else if (attribute.getID().equalsIgnoreCase("employeeNumber")) {
193                   user.setHrid((String) ie.next());
194               }
195               else if (attribute.getID().equalsIgnoreCase("mail")) {
196                   user.setEmail((String) ie.next());
197               }
198               else if (attribute.getID().equalsIgnoreCase("telephoneNumber")) {
199                   user.setPhone((String) ie.next());
200               }
201               else if (attribute.getID().equalsIgnoreCase("departmentNumber")) {
202                   user.setOrgCode((String) ie.next());
203               }
204               else if (attribute.getID().equalsIgnoreCase("a1")) {
205                   user.setOrgUserId((String) ie.next());
206               }
207               else if (attribute.getID().equalsIgnoreCase("street")) {
208                   user.setAddress1((String) ie.next());
209               }
210               else if (attribute.getID().equalsIgnoreCase("roomNumber")) {
211                   user.setAddress2((String) ie.next());
212               }
213               else if (attribute.getID().equalsIgnoreCase("l")) {
214                   user.setCity((String) ie.next());
215               }
216               else if (attribute.getID().equalsIgnoreCase("st")) {
217                   user.setState((String) ie.next());
218               }
219               else if (attribute.getID().equalsIgnoreCase("postalCode")) {
220                   user.setZipCode((String) ie.next());
221               }
222               else if (attribute.getID().equalsIgnoreCase("zip4")) {
223                   user.setZipCodeSuffix((String) ie.next());
224               }
225               else if (attribute.getID().equalsIgnoreCase("physicalDeliveryOfficeName")) {
226                   user.setLocationClli((String) ie.next());
227               }
228               else if (attribute.getID().equalsIgnoreCase("bc")) {
229                   user.setBusinessCountryCode((String) ie.next());
230               }
231               else if (attribute.getID().equalsIgnoreCase("friendlyCountryName")) {
232                   user.setBusinessCountryName((String) ie.next());
233               }
234               else if (attribute.getID().equalsIgnoreCase("bd")) {
235                   user.setDepartment((String) ie.next());
236               }
237               else if (attribute.getID().equalsIgnoreCase("bdname")) {
238                   user.setDepartmentName((String) ie.next());
239               }
240               else if (attribute.getID().equalsIgnoreCase("jtname")) {
241                   user.setJobTitle((String) ie.next());
242               }
243               else if (attribute.getID().equalsIgnoreCase("mgrid")) {
244                   user.setOrgManagerUserId((String) ie.next());
245               }
246               else if (attribute.getID().equalsIgnoreCase("a2")) {
247                   user.setCommandChain((String) ie.next());
248               }
249               else if (attribute.getID().equalsIgnoreCase("compcode")) {
250                   user.setCompanyCode((String) ie.next());
251               }
252               else if (attribute.getID().equalsIgnoreCase("compdesc")) {
253                   user.setCompany((String) ie.next());
254               }
255               else if (attribute.getID().equalsIgnoreCase("bu")) {
256                   user.setBusinessUnit((String)ie.next());
257               }
258               else if (attribute.getID().equalsIgnoreCase("buname")) {
259                   user.setBusinessUnitName((String)ie.next());
260               }
261               else if (attribute.getID().equalsIgnoreCase("silo")) {
262                   user.setSiloStatus((String)ie.next());
263               }
264               else if (attribute.getID().equalsIgnoreCase("costcenter")) {
265                   user.setCostCenter((String)ie.next());
266               }
267               else if (attribute.getID().equalsIgnoreCase("b2")) {
268                   user.setFinancialLocCode((String)ie.next());
269               }
270               else { //we don't care about returned attribute, let's move on
271                 ie.next();
272               }
273
274             }
275           }
276         }
277       } catch (NamingException e) {
278           String stackTrace = EcompPortalUtils.getStackTrace(e);
279           logger.error(EELFLoggerDelegate.errorLogger, "An error occurred while processing the following user from POST with an Organization User ID of " + user.getOrgUserId());
280           logger.error(EELFLoggerDelegate.errorLogger, "Exception occcurred while processing LDAP search results, Details: " + stackTrace);
281       } catch(Exception e) {
282           String stackTrace = EcompPortalUtils.getStackTrace(e);
283           logger.error(EELFLoggerDelegate.errorLogger, "Exception occcurred while processing LDAP search results, Details: " + stackTrace);
284       }
285       
286       return user;
287     }
288 }