a8c3a5d6f8fb864e8c4e02211cdb93e78b6c98c9
[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.portalapp.controller.core;
39
40 import java.io.IOException;
41 import java.io.PrintWriter;
42 import java.util.ArrayList;
43 import java.util.HashMap;
44 import java.util.Iterator;
45 import java.util.List;
46 import java.util.Map;
47
48 import javax.naming.NamingException;
49 import javax.servlet.http.HttpServletRequest;
50 import javax.servlet.http.HttpServletResponse;
51
52 import org.json.JSONObject;
53 import org.onap.portalsdk.core.command.PostSearchBean;
54 import org.onap.portalsdk.core.command.support.SearchResult;
55 import org.onap.portalsdk.core.controller.RestrictedBaseController;
56 import org.onap.portalsdk.core.domain.Lookup;
57 import org.onap.portalsdk.core.domain.Profile;
58 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
59 import org.onap.portalsdk.core.service.LdapService;
60 import org.onap.portalsdk.core.service.PostSearchService;
61 import org.onap.portalsdk.core.service.ProfileService;
62 import org.onap.portalsdk.core.web.support.JsonMessage;
63 import org.onap.portalsdk.core.web.support.UserUtils;
64 import org.springframework.beans.factory.annotation.Autowired;
65 import org.springframework.stereotype.Controller;
66 import org.springframework.web.bind.annotation.ModelAttribute;
67 import org.springframework.web.bind.annotation.RequestMapping;
68 import org.springframework.web.bind.annotation.RequestMethod;
69 import org.springframework.web.servlet.ModelAndView;
70
71 import com.fasterxml.jackson.databind.DeserializationFeature;
72 import com.fasterxml.jackson.databind.JsonNode;
73 import com.fasterxml.jackson.databind.ObjectMapper;
74
75 @Controller
76 @RequestMapping("/")
77 public class PostSearchController extends RestrictedBaseController {
78
79         private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PostSearchController.class);
80
81         private static final String POST_SEARCH_BEAN = "postSearchBean";
82   private static final String UTF8 = "UTF-8";
83
84         @SuppressWarnings("rawtypes")
85         private static List sortByList = null;
86
87         @Autowired
88         private PostSearchService postSearchService;
89
90         @Autowired
91         private LdapService ldapService;
92
93         @Autowired
94         private ProfileService profileService;
95
96         @RequestMapping(value = { "/post_search" }, method = RequestMethod.GET)
97         public ModelAndView welcome(@ModelAttribute(POST_SEARCH_BEAN) PostSearchBean postSearchBean) {
98                 Map<String, Object> model = new HashMap<>();
99                 ObjectMapper mapper = new ObjectMapper();
100                 try {
101                         PostSearchBean postSearchBeanLocal = new PostSearchBean();
102                         model.put("profileList", mapper.writeValueAsString(postSearchBeanLocal.getSearchResult()));
103                         model.put(POST_SEARCH_BEAN, mapper.writeValueAsString(postSearchBeanLocal));
104                         model.put("existingUsers", mapper.writeValueAsString(getExistingUsers()));
105                         model.put("sortByList", mapper.writeValueAsString(getSortByList()));
106                 } catch (Exception ex) {
107                         logger.error(EELFLoggerDelegate.errorLogger, "welcome: failed to write JSON", ex);
108                 }
109
110                 return new ModelAndView(getViewName(), model);
111         }
112
113         @RequestMapping(value = { "/post_search_sample" }, method = RequestMethod.GET)
114         public void getPostSearchProfile(HttpServletResponse response,
115                         @ModelAttribute(POST_SEARCH_BEAN) PostSearchBean postSearchBean) {
116                 Map<String, Object> model = new HashMap<>();
117                 ObjectMapper mapper = new ObjectMapper();
118                 try {
119       PostSearchBean postSearchBeanLocal = new PostSearchBean();
120                         model.put("profileList", mapper.writeValueAsString(postSearchBeanLocal.getSearchResult()));
121                         model.put(POST_SEARCH_BEAN, mapper.writeValueAsString(postSearchBeanLocal));
122                         model.put("existingUsers", mapper.writeValueAsString(getExistingUsers()));
123                         model.put("sortByList", mapper.writeValueAsString(getSortByList()));
124                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
125                         JSONObject j = new JSONObject(msg);
126                         response.getWriter().write(j.toString());
127                 } catch (Exception ex) {
128                         logger.error(EELFLoggerDelegate.errorLogger, "getPostSearchProfile: failed to write JSON", ex);
129                 }
130         }
131
132         @SuppressWarnings({ "unchecked", "rawtypes" })
133         private HashMap getExistingUsers() throws IOException {
134                 HashMap existingUsers = new HashMap();
135
136                 // get the list of user ids in the system
137                 List<Profile> list = profileService.findAll();
138
139                 if (list != null) {
140                         Iterator<Profile> i = list.iterator();
141                         while (i.hasNext()) {
142                                 Profile user = i.next();
143                                 String orgUserId = user.getOrgUserId(); // userid scalar
144                                 Long id = user.getId(); // id scalar
145                                 if (orgUserId != null)
146                                         existingUsers.put(orgUserId, id);
147                         }
148                 }
149                 return existingUsers;
150         }
151
152         @RequestMapping(value = { "/post_search/search" }, method = RequestMethod.POST)
153         public ModelAndView search(HttpServletRequest request, HttpServletResponse response) {
154                 try {
155                         ObjectMapper mapper = new ObjectMapper();
156                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
157                         JsonNode root = mapper.readTree(request.getReader());
158                         PostSearchBean postSearchBean = mapper.readValue(root.get(POST_SEARCH_BEAN).toString(),
159                                         PostSearchBean.class);
160
161                         postSearchBean.setSearchResult(loadSearchResultData(request, postSearchBean));
162
163                         response.setCharacterEncoding(UTF8);
164                         response.setContentType("application / json");
165                         request.setCharacterEncoding(UTF8);
166
167                         PrintWriter out = response.getWriter();
168                         String responseString = mapper.writeValueAsString(postSearchBean);
169                         JSONObject j = new JSONObject("{postSearchBean: " + responseString + "}");
170
171                         out.write(j.toString());
172                 } catch (Exception ex) {
173                         logger.error(EELFLoggerDelegate.errorLogger, "search: failed to send search result", ex);
174                 }
175
176                 return null;
177         }
178
179         @SuppressWarnings({ "unchecked", "rawtypes" })
180         public static List getSortByList() {
181                 if (sortByList == null) {
182                         sortByList = new ArrayList();
183                         sortByList.add(new Lookup("Last Name", "last_name"));
184                         sortByList.add(new Lookup("First Name", "first_name"));
185                         sortByList.add(new Lookup("HRID", "hrid"));
186                         sortByList.add(new Lookup("SBCID", "sbcid"));
187                         sortByList.add(new Lookup("Organization", "org_code"));
188                         sortByList.add(new Lookup("Email", "email"));
189                 } // if
190
191                 return sortByList;
192         } // getSortByList
193
194         private SearchResult loadSearchResultData(HttpServletRequest request, PostSearchBean searchCriteria)
195                         throws NamingException {
196                 return ldapService.searchPost(searchCriteria.getUser(), searchCriteria.getSortBy1(),
197                                 searchCriteria.getSortBy2(), searchCriteria.getSortBy3(), searchCriteria.getPageNo(),
198                                 searchCriteria.getNewDataSize(), UserUtils.getUserSession(request).getId().intValue());
199         }
200
201         @RequestMapping(value = { "/post_search/process" }, method = RequestMethod.POST)
202         public ModelAndView process(HttpServletRequest request, HttpServletResponse response) throws Exception {
203                 ObjectMapper mapper = new ObjectMapper();
204                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
205                 mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
206                 JsonNode root = mapper.readTree(request.getReader());
207                 PostSearchBean postSearch = mapper.readValue(root.get(POST_SEARCH_BEAN).toString(), PostSearchBean.class);
208                 String errorMsg = "{}";
209                 try {
210                         postSearchService.process(request, postSearch);
211                         postSearch.setSearchResult(loadSearchResultData(request, postSearch));
212                 } catch (Exception e) {
213                         errorMsg = e.getMessage();
214                         logger.error(EELFLoggerDelegate.errorLogger,
215                                         "Exception occurred while performing PostSearchController.process. Details:", e);
216                 }
217                 logger.info(EELFLoggerDelegate.auditLogger, "Import new user from webphone ");
218                 response.setCharacterEncoding(UTF8);
219                 response.setContentType("application / json");
220                 request.setCharacterEncoding(UTF8);
221
222                 PrintWriter out = response.getWriter();
223                 String postSearchString = mapper.writeValueAsString(postSearch);
224                 JSONObject j = new JSONObject("{postSearchBean: " + postSearchString + ",existingUsers: "
225                                 + mapper.writeValueAsString(getExistingUsers()) + ",errorMsg:" + errorMsg + "}");
226
227                 out.write(j.toString());
228                 return null;
229         }
230 }