2909597069eaec0cc0b339efbc70fdbfb4f28b6e
[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.core.onboarding.crossapi;
39
40 import java.io.BufferedReader;
41 import java.io.IOException;
42 import java.io.InputStream;
43 import java.io.InputStreamReader;
44 import java.io.PrintWriter;
45 import java.io.StringWriter;
46 import java.util.Arrays;
47 import java.util.Iterator;
48 import java.util.List;
49 import java.util.Map;
50 import java.util.Set;
51 import java.util.TreeSet;
52 import java.util.stream.Collectors;
53
54 import javax.servlet.ServletException;
55 import javax.servlet.annotation.WebServlet;
56 import javax.servlet.http.HttpServlet;
57 import javax.servlet.http.HttpServletRequest;
58 import javax.servlet.http.HttpServletResponse;
59
60 import org.apache.commons.logging.Log;
61 import org.apache.commons.logging.LogFactory;
62 import org.onap.portalsdk.core.onboarding.exception.PortalAPIException;
63 import org.onap.portalsdk.core.onboarding.listener.PortalTimeoutHandler;
64 import org.onap.portalsdk.core.onboarding.rest.RestWebServiceClient;
65 import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
66 import org.onap.portalsdk.core.onboarding.util.PortalApiProperties;
67 import org.onap.portalsdk.core.restful.domain.EcompRole;
68 import org.onap.portalsdk.core.restful.domain.EcompRoleFunction;
69 import org.onap.portalsdk.core.restful.domain.EcompUser;
70 import org.owasp.esapi.ESAPI;
71
72 import com.fasterxml.jackson.core.JsonProcessingException;
73 import com.fasterxml.jackson.core.type.TypeReference;
74 import com.fasterxml.jackson.databind.DeserializationFeature;
75 import com.fasterxml.jackson.databind.ObjectMapper;
76
77 /**
78  * This servlet performs the functions described below. It listens on a path
79  * like "/api" (see {@link PortalApiConstants#API_PREFIX}). The servlet checks
80  * for authorized access and rejects unauthorized requests.
81  * <OL>
82  * <LI>Proxies user (i.e., browser) requests for web analytics. The GET method
83  * fetches javascript from the Portal and returns it. The POST method forwards
84  * data sent by the browser on to Portal. These requests are checked for a valid
85  * User UID in a header; these requests do NOT use the application
86  * username-password header.</LI>
87  * <LI>Responds to ECOMP Portal API requests to query and update user, role and
88  * user-role information. The servlet proxies all requests on to a local Java
89  * class that implements {@link IPortalRestAPIService}. These requests must have
90  * the application username-password header.</LI>
91  * </OL>
92  * This servlet will not start if the required portal.properties file is not
93  * found on the classpath.
94  */
95
96 @WebServlet(urlPatterns = { PortalApiConstants.API_PREFIX + "/*" })
97 public class PortalRestAPIProxy extends HttpServlet implements IPortalRestAPIService {
98         
99         private static final long serialVersionUID = 1L;
100
101         private static final String APPLICATION_JSON = "application/json";
102
103         private static final Log logger = LogFactory.getLog(PortalRestAPIProxy.class);
104
105         /**
106          * Mapper for JSON to object etc.
107          */
108         private final ObjectMapper mapper = new ObjectMapper();
109
110         /**
111          * Client-supplied class that implements our interface.
112          */
113         private static IPortalRestAPIService portalRestApiServiceImpl;
114         private static final String isAccessCentralized = PortalApiProperties
115                         .getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED);
116         private static final String errorMessage = "Access Management is not allowed for Centralized applications." ;
117         private static final String isCentralized = "remote";
118
119
120         public PortalRestAPIProxy() {
121                 // Ensure that any additional fields sent by the Portal
122                 // will be ignored when creating objects.
123                 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
124         }
125
126         @Override
127         public void init() throws ServletException {
128                 String className = PortalApiProperties.getProperty(PortalApiConstants.PORTAL_API_IMPL_CLASS);
129                 if (className == null)
130                         throw new ServletException(
131                                         "init: Failed to find class name property " + PortalApiConstants.PORTAL_API_IMPL_CLASS);
132                 try {
133                         logger.debug("init: creating instance of class " + className);
134                         Class<?> implClass = Class.forName(className);
135                         if (!isCentralized.equals(isAccessCentralized))
136                                 portalRestApiServiceImpl = (IPortalRestAPIService) (implClass.getConstructor().newInstance());
137                         else {
138                                 portalRestApiServiceImpl = new PortalRestAPICentralServiceImpl();                               
139                         }
140                 } catch (Exception ex) {
141                         throw new ServletException("init: Failed to find or instantiate class " + className, ex);
142                 }
143         }
144
145         @Override
146         protected void doPost(HttpServletRequest request, HttpServletResponse response)
147                         throws IOException, ServletException {
148                 if (portalRestApiServiceImpl == null) {
149                         // Should never happen due to checks in init()
150                         logger.error("doPost: no service class instance");
151                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
152                         response.getWriter().write(buildJsonResponse(false, "Misconfigured - no instance of service class"));
153                         return;
154                 }
155                 
156         
157                 String requestUri = request.getRequestURI();
158                 String responseJson = "";
159                 String storeAnalyticsContextPath = "/storeAnalytics";
160                 if (requestUri.endsWith(PortalApiConstants.API_PREFIX + storeAnalyticsContextPath)) {
161                         String userId;
162                         try {
163                                 userId = getUserId(request);
164                         } catch (PortalAPIException e) {
165                                 logger.error("Issue with invoking getUserId implemenation !!! ", e);
166                                 throw new ServletException(e);
167                         }
168                         if (userId == null || userId.length() == 0) {
169                                 logger.debug("doPost: userId is null or empty");
170                                 response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
171                                 responseJson = buildJsonResponse(false, "Not authorized for " + storeAnalyticsContextPath);
172                         } else {
173                                 // User ID obtained from request
174                                 try {
175                                         String appUserName = "";
176                                         String appPassword = "";
177                                         String appName = "";
178
179                                         for (Map.Entry<String, String> entry : getCredentials().entrySet()) {
180
181                                                 if (entry.getKey().equalsIgnoreCase("username")) {
182                                                         appUserName = entry.getValue();
183                                                 } else if (entry.getKey().equalsIgnoreCase("password")) {
184                                                         appPassword = entry.getValue();
185                                                 } else {
186                                                         appName = entry.getValue();
187                                                 }
188                                         }
189                                         
190                                         String credential = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
191                                         // for now lets also pass uebkey as user name and password
192                                         String requestBody = readRequestBody(request);
193                                         @SuppressWarnings("unchecked")
194                                         Map<String, String> bodyMap = mapper.readValue(requestBody, Map.class);
195                                         // add user ID
196                                         bodyMap.put("userid", userId);
197                                         requestBody = mapper.writeValueAsString(bodyMap);
198                                         logger.debug("doPost:  StoreAnalytics requestbody: "+ requestBody);
199                                         responseJson = RestWebServiceClient.getInstance().postPortalContent(storeAnalyticsContextPath,
200                                                         userId, appName, null, appUserName, appPassword, "application/json", requestBody, true);
201                                         logger.debug("doPost: postPortalContent returns " + responseJson);
202                                         response.setStatus(HttpServletResponse.SC_OK);
203                                 } catch (Exception ex) {
204                                         logger.error("doPost: " + storeAnalyticsContextPath + " caught exception", ex);
205                                         responseJson = buildShortJsonResponse(ex);
206                                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
207                                 }
208                         }
209                         writeAndFlush(response, APPLICATION_JSON, responseJson);
210                         return;
211                 } // post analytics
212
213                 boolean secure = false;
214                 try {
215                         secure = isAppAuthenticated(request, getCredentials());
216                 } catch (PortalAPIException ex) {
217                         logger.error("doPost: isAppAuthenticated threw exception", ex);
218                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
219                         response.getWriter().write(buildJsonResponse(false, "Failed to authenticate request"));
220                         return;
221                 }
222                 if (!secure) {
223                         logger.debug("doPost: isAppAuthenticated answered false");
224                         response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
225                         writeAndFlush(response, APPLICATION_JSON, buildJsonResponse(false, "Not authorized"));
226                         return;
227                 }
228                 
229
230                 try {
231                         String requestBody = readRequestBody(request);
232                         if (logger.isDebugEnabled())
233                                 logger.debug("doPost: URI =  " + requestUri + ", payload = " + requestBody);
234
235                         /*
236                          * All APIs:
237                          * 
238                          * 1. /user <-- save user
239                          * 
240                          * 2. /user/{loginId} <-- edit user
241                          * 
242                          * 3. /user/{loginId}/roles <-- save roles for user
243                          */
244
245                         // On success return the empty string.
246
247                         if (requestUri.endsWith("/updateSessionTimeOuts")) {
248                                 if (updateSessionTimeOuts(requestBody)) {
249                                         logger.debug("doPost: updated session timeouts");
250                                         response.setStatus(HttpServletResponse.SC_OK);
251                                 } else {
252                                         String msg = "Failed to update session time outs";
253                                         logger.error("doPost: " + msg);
254                                         responseJson = buildJsonResponse(false, msg);
255                                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
256                                 }
257                         } else if (requestUri.endsWith("/timeoutSession")) {
258                                 String portalJSessionId = request.getParameter("portalJSessionId");
259                                 if (portalJSessionId == null) {
260                                         portalJSessionId = "";
261                                 }
262                                 if (timeoutSession(portalJSessionId)) {
263                                         logger.debug("doPost: timed out session");
264                                         response.setStatus(HttpServletResponse.SC_OK);
265                                 } else {
266                                         String msg = "Failed to timeout session";
267                                         logger.error("doPost: " + msg);
268                                         responseJson = buildJsonResponse(false, msg);
269                                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
270                                 }
271                         } else
272                         // Example: /user <-- create user
273                         if (requestUri.endsWith(PortalApiConstants.API_PREFIX + "/user")) {
274                                 try {
275                                         EcompUser user = mapper.readValue(requestBody, EcompUser.class);
276                                         logger.debug("doPost:  create user requestbody: "+ requestBody);
277                                         Set<EcompRole> userEcompRoles = getEcompRolesOfUser(user);
278                                         user.setRoles(userEcompRoles);
279                                         pushUser(user);
280                                         if (logger.isDebugEnabled())
281                                                 logger.debug("doPost: pushUser: success");
282                                         responseJson = buildJsonResponse(true, "user saved successfully");
283                                         response.setStatus(HttpServletResponse.SC_OK);
284                                 } catch (Exception ex) {
285                                         responseJson =  buildShortJsonResponse(ex);
286                                         response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
287                                         logger.error("doPost: pushUser: caught exception", ex);
288                                 }
289                         } else
290                         // Example: /user/abc <-- edit user abc 
291                         if (requestUri.contains(PortalApiConstants.API_PREFIX + "/user/") && !(requestUri.endsWith("/roles"))) {
292                                 String loginId = requestUri.substring(requestUri.lastIndexOf('/') + 1);
293                                 try {
294                                         EcompUser user = mapper.readValue(requestBody, EcompUser.class);
295                                         logger.debug("doPost:  update user requestbody: "+ requestBody);
296                                         Set<EcompRole> userEcompRoles = getEcompRolesOfUser(user);
297                                         user.setRoles(userEcompRoles);
298                                         editUser(loginId, user);
299                                         if (logger.isDebugEnabled())
300                                                 logger.debug("doPost: editUser: success");
301                                         responseJson = buildJsonResponse(true, "user saved successfully");
302                                         response.setStatus(HttpServletResponse.SC_OK);
303                                 } catch (Exception ex) {
304                                         responseJson =  buildShortJsonResponse(ex);
305                                         response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
306                                         logger.error("doPost: editUser: caught exception", ex);
307                                 }
308                         } else
309                         // Example: /user/{loginId}/roles <-- save roles for user
310                         if (requestUri.contains(PortalApiConstants.API_PREFIX + "/user/") && requestUri.endsWith("/roles")) {
311                                 String loginId = requestUri.substring(requestUri.indexOf("/user/") + ("/user").length() + 1,
312                                                 requestUri.lastIndexOf('/'));
313                                 try {
314                                         if (isCentralized.equals(isAccessCentralized)) {
315                                                 responseJson = buildJsonResponse(true, errorMessage);
316                                                 response.setStatus(HttpServletResponse.SC_OK);
317                                         } else {
318                                                 TypeReference<List<EcompRole>> typeRef = new TypeReference<List<EcompRole>>() {
319                                                 };
320                                                 List<EcompRole> roles = mapper.readValue(requestBody, typeRef);
321                                                 pushUserRole(loginId, roles);
322                                                 if (logger.isDebugEnabled())
323                                                         logger.debug("doPost: pushUserRole: success");
324                                                 responseJson = buildJsonResponse(true, "saveRoles is successful");
325                                                 response.setStatus(HttpServletResponse.SC_OK);
326                                         }
327                                 } catch (Exception ex) {
328                                         responseJson = buildShortJsonResponse(ex);
329                                         response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
330                                         logger.error("doPost: pushUserRole: caught exception", ex);
331                                 }
332                         } else {
333                                 String msg = "doPost: no match for request " + requestUri;
334                                 logger.warn( ESAPI.encoder().encodeForHTML(msg));
335                                 responseJson = buildJsonResponse(false, msg);
336                                 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
337                         }
338                 } catch (Exception ex) {
339                         logger.error("doPost: Failed to process request " + ESAPI.encoder().encodeForHTML(requestUri), ex);
340                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
341                         responseJson = buildJsonResponse(ex);
342                 }
343
344                 writeAndFlush(response, APPLICATION_JSON, responseJson);
345
346         }
347
348         @Override
349         protected void doGet(HttpServletRequest request, HttpServletResponse response)
350                         throws IOException, ServletException {
351
352                 if (portalRestApiServiceImpl == null) {
353                         // Should never happen due to checks in init()
354                         logger.error("doGet: no service class instance");
355                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
356                         writeAndFlush(response, APPLICATION_JSON,
357                                         buildJsonResponse(false, "Misconfigured - no instance of service class"));
358                         return;
359                 }
360                 
361
362                 String requestUri = request.getRequestURI();
363                 String contentType = APPLICATION_JSON;
364                 String webAnalyticsContextPath = "/analytics";
365                 if (requestUri.endsWith(PortalApiConstants.API_PREFIX + webAnalyticsContextPath)) {
366                         String responseString;
367                         String userId;
368                         try {
369                                 userId = getUserId(request);
370                         } catch (PortalAPIException e) {
371                                 logger.error("Issue with invoking getUserId implemenation !!! ", e);
372                                 throw new ServletException(e);
373                         }
374                         if (userId == null || userId.length() == 0) {
375                                 logger.debug("doGet: userId is null or empty");
376                                 response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
377                                 responseString = buildJsonResponse(false, "Not authorized for " + webAnalyticsContextPath);
378                         } else {
379                                 // User ID obtained from request
380                                 try {
381                                         String appUserName = "";
382                                         String appPassword = "";
383                                         String appName = "";
384
385                                         for (Map.Entry<String, String> entry : getCredentials().entrySet()) {
386
387                                                 if (entry.getKey().equalsIgnoreCase("username")) {
388                                                         appUserName = entry.getValue();
389                                                 } else if (entry.getKey().equalsIgnoreCase("password")) {
390                                                         appPassword = entry.getValue();
391                                                 } else {
392                                                         appName = entry.getValue();
393                                                 }
394                                         }
395                                         String credential = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
396                                         // for now lets also pass uebkey as user name and password
397                                         contentType = "text/javascript";
398
399                                         responseString = RestWebServiceClient.getInstance().getPortalContent(webAnalyticsContextPath,
400                                                         userId, appName, null, appUserName, appPassword, true);
401                                         
402                                         if (logger.isDebugEnabled())
403                                                 logger.debug("doGet: " + webAnalyticsContextPath + ": " + responseString);
404                                         response.setStatus(HttpServletResponse.SC_OK);
405                                 } catch (Exception ex) {
406                                         responseString = buildShortJsonResponse(ex);
407                                         response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
408                                         logger.error("doGet: " + webAnalyticsContextPath + " caught exception", ex);
409                                 }
410                         }
411                         writeAndFlush(response, contentType, responseString);
412                         return;
413                 }
414
415                 boolean secure = false;
416                 try {
417                         secure = isAppAuthenticated(request, getCredentials());
418                 } catch (PortalAPIException ex) {
419                         logger.error("doGet: isAppAuthenticated threw exception", ex);
420                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
421                         writeAndFlush(response, APPLICATION_JSON, buildJsonResponse(false, "Failed to authenticate request"));
422                         return;
423                 }
424
425                 if (!secure) {
426                         if (logger.isDebugEnabled())
427                                 logger.debug("doGet: isAppAuthenticated answered false");
428                         response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
429                         writeAndFlush(response, APPLICATION_JSON, buildJsonResponse(false, "Not authorized"));
430                         return;
431                 }
432                 String responseJson = null;
433                 try {
434                         // Ignore any request body in a GET.
435                         logger.debug("doGet: URI =  " + requestUri);
436
437                         /*
438                          * 1. /roles <-- get roles
439                          * 
440                          * 2. /user/{loginId} <-- get user
441                          * 
442                          * 3. /users <-- get all users
443                          * 
444                          * 4. /user/{loginId}/roles <-- get roles for user
445                          */
446
447                         if (requestUri.endsWith("/sessionTimeOuts")) {
448                                 try  {
449                                         responseJson = getSessionTimeOuts();
450                                         logger.debug("doGet: got session timeouts");
451                                         response.setStatus(HttpServletResponse.SC_OK);
452                                 } catch(Exception ex) {
453                                         String msg = "Failed to get session time outs";
454                                         logger.error("doGet: " + msg);
455                                         responseJson =  buildShortJsonResponse(ex);
456                                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
457                                 }
458                         } else
459                         // Example: /users <-- get all users
460                         if (requestUri.endsWith(PortalApiConstants.API_PREFIX + "/users")) {
461                                 try {
462                                         List<EcompUser> users = getUsers();
463                                         responseJson = mapper.writeValueAsString(users);
464                                         if (logger.isDebugEnabled())
465                                                 logger.debug("doGet: getUsers: " + responseJson);
466                                 } catch (Exception ex) {
467                                         responseJson = buildShortJsonResponse(ex);
468                                         response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
469                                         logger.error("doGet: getUsers: caught exception", ex);
470                                 }
471                         } else
472                         // Example: /roles <-- get all roles
473
474                         if (requestUri.endsWith(PortalApiConstants.API_PREFIX + "/roles")) {
475                                 try {
476                                         List<EcompRole> roles = getAvailableRoles(getUserId(request));
477                                         responseJson = mapper.writeValueAsString(roles);
478                                         if (logger.isDebugEnabled())
479                                                 logger.debug("doGet: getAvailableRoles: " + responseJson);
480                                 } catch (Exception ex) {
481                                         responseJson =  buildShortJsonResponse(ex);
482                                         response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
483                                         logger.error("doGet: getAvailableRoles: caught exception", ex);
484                                 }
485                         } else
486                         // Example: /user/abc <-- get user abc
487                         if (requestUri.contains(PortalApiConstants.API_PREFIX + "/user/") && !requestUri.endsWith("/roles")) {
488                                 String loginId = requestUri.substring(requestUri.lastIndexOf('/') + 1);
489                                 try {
490                                         EcompUser user = getUser(loginId);
491                                         responseJson = mapper.writeValueAsString(user);
492                                         if (logger.isDebugEnabled())
493                                                 logger.debug("doGet: getUser: " + responseJson);
494                                 } catch (Exception ex) {
495                                         responseJson =  buildShortJsonResponse(ex);
496                                         response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
497                                         logger.error("doGet: getUser: caught exception", ex);
498                                 }
499                         }
500                         // Example: /user/abc/roles <-- get roles for user abc
501                         else if (requestUri.contains(PortalApiConstants.API_PREFIX + "/user/") && requestUri.endsWith("/roles")) {
502                                 String loginId = requestUri.substring(requestUri.indexOf("/user/") + ("/user").length() + 1,
503                                                 requestUri.lastIndexOf('/'));
504                                 try {
505                                         List<EcompRole> roles = getUserRoles(loginId);
506                                         responseJson = mapper.writeValueAsString(roles);
507                                         if (logger.isDebugEnabled())
508                                                 logger.debug("doGet: getUserRoles: " + responseJson);
509                                 } catch (Exception ex) {
510                                         responseJson = buildShortJsonResponse(ex);
511                                         response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
512                                         logger.error("doGet: getUserRoles: caught exception", ex);
513                                 }
514                         }
515                         else {
516                                 logger.warn("doGet: no match found for request");
517                                 responseJson = buildJsonResponse(false, "No match for request");
518                                 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
519                         }
520                 } catch (Exception ex) {
521                         logger.error("doGet: Failed to process request", ex);
522                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
523                         responseJson = buildJsonResponse(ex);
524                 }
525                 writeAndFlush(response, APPLICATION_JSON, responseJson);
526         }
527
528         public String getSessionTimeOuts() {
529                 return PortalTimeoutHandler.gatherSessionExtensions();
530         }
531
532         public boolean timeoutSession(String portalJSessionId) {
533                 return PortalTimeoutHandler.invalidateSession(portalJSessionId);
534         }
535
536         public boolean updateSessionTimeOuts(String sessionMap) {
537                 return PortalTimeoutHandler.updateSessionExtensions(sessionMap);
538         }
539
540         @Override
541         public void pushUser(EcompUser user) throws PortalAPIException {
542                 portalRestApiServiceImpl.pushUser(user);
543         }
544
545         @Override
546         public void editUser(String loginId, EcompUser user) throws PortalAPIException {
547                 portalRestApiServiceImpl.editUser(loginId, user);
548         }
549
550         @Override
551         public EcompUser getUser(String loginId) throws PortalAPIException {
552                 return portalRestApiServiceImpl.getUser(loginId);
553         }
554
555         @Override
556         public List<EcompUser> getUsers() throws PortalAPIException {
557                 return portalRestApiServiceImpl.getUsers();
558         }
559
560         @Override
561         public List<EcompRole> getAvailableRoles(String requestedLoginId) throws PortalAPIException {
562                 return portalRestApiServiceImpl.getAvailableRoles(requestedLoginId);
563         }
564
565         @Override
566         public void pushUserRole(String loginId, List<EcompRole> roles) throws PortalAPIException {
567                 portalRestApiServiceImpl.pushUserRole(loginId, roles);
568         }
569
570         @Override
571         public List<EcompRole> getUserRoles(String loginId) throws PortalAPIException {
572                 return portalRestApiServiceImpl.getUserRoles(loginId);
573         }
574
575         @Override
576         public boolean isAppAuthenticated(HttpServletRequest request, Map<String,String> appCredentials) throws PortalAPIException {
577                 return portalRestApiServiceImpl.isAppAuthenticated(request, appCredentials);
578         }
579
580         /**
581          * Sets the content type and writes the response.
582          * 
583          * @param response
584          * @param contentType
585          * @param responseBody
586          * @throws IOException
587          */
588         private void writeAndFlush(HttpServletResponse response, String contentType, String responseBody)
589                         throws IOException {
590                 response.setContentType(contentType);
591                 PrintWriter out = response.getWriter();
592                 out.print(responseBody);
593                 out.flush();
594         }
595
596         /**
597          * Reads the request body and closes the input stream.
598          * 
599          * @param request
600          * @return String read from the request, the empty string if nothing is read.
601          * @throws IOException
602          */
603         private static String readRequestBody(HttpServletRequest request) throws IOException {
604
605                 String body = null;
606                 StringBuilder stringBuilder = new StringBuilder();
607
608                 try(InputStream inputStream = request.getInputStream()) {
609                         if (inputStream != null) {
610                                 try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));){
611                                         char[] charBuffer = new char[1024];
612                                         int bytesRead = -1;
613                                         while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
614                                                 stringBuilder.append(charBuffer, 0, bytesRead);
615                                         }
616                                 } catch(IOException e) {
617                                         logger.error("readRequestBody", e);
618                                         throw e;
619                                 }
620                         } else {
621                                 stringBuilder.append("");
622                         }
623                 } catch(IOException e) {
624                         logger.error("readRequestBody", e);
625                         throw e;
626                 }
627                 body = stringBuilder.toString();
628                 return body;
629         }
630
631         /**
632          * Builds JSON object with status + message response body.
633          * 
634          * @param success
635          *            True to indicate success, false to signal failure.
636          * @param msg
637          *            Message to include in the response object; ignored if null.
638          * @return
639          * 
640          *         <pre>
641          * { "status" : "ok" (or "error"), "message": "some explanation" }
642          *         </pre>
643          */
644         private String buildJsonResponse(boolean success, String msg) {
645                 PortalAPIResponse response = new PortalAPIResponse(success, msg);
646                 String json = null;
647                 try {
648                         json = mapper.writeValueAsString(response);
649                 } catch (JsonProcessingException ex) {
650                         // Truly should never, ever happen
651                         logger.error("buildJsonResponse", ex);
652                         json = "{ \"status\": \"error\",\"message\":\"" + ex.toString() + "\" }";
653                 }
654                 return json;
655         }
656
657         /**
658          * Builds JSON object with status of error and message containing stack trace
659          * for the specified throwable.
660          * 
661          * @param t
662          *            Throwable with stack trace to use as message
663          * 
664          * @return
665          * 
666          *         <pre>
667          * { "status" : "error", "message": "some-big-stacktrace" }
668          *         </pre>
669          */
670         private String buildJsonResponse(Throwable t) {
671                 StringWriter sw = new StringWriter();
672                 PrintWriter pw = new PrintWriter(sw);
673                 t.printStackTrace(pw);
674                 return buildJsonResponse(false, sw.toString());
675         }
676         
677         private String buildShortJsonResponse(Throwable t)
678         {
679                 String errorMessage = t.getMessage();
680                 return buildJsonResponse(false, errorMessage);
681         }
682
683         @Override
684         public String getUserId(HttpServletRequest request) throws PortalAPIException {
685                 return portalRestApiServiceImpl.getUserId(request);
686         }
687
688         public static IPortalRestAPIService getPortalRestApiServiceImpl() {
689                 return portalRestApiServiceImpl;
690         }
691
692         public static void setPortalRestApiServiceImpl(IPortalRestAPIService portalRestApiServiceImpl) {
693                 PortalRestAPIProxy.portalRestApiServiceImpl = portalRestApiServiceImpl;
694         }
695         
696         @Override
697         public  Map<String, String> getCredentials() throws PortalAPIException {
698                 return portalRestApiServiceImpl.getCredentials();
699         }
700
701         private Set<EcompRole> getEcompRolesOfUser(EcompUser user) throws JsonProcessingException
702         {
703                 
704                 Set<EcompRole> userEcompRoles = new TreeSet<>();
705                 Set<EcompRole> ecompRoles = user.getRoles();
706                 for (EcompRole role : ecompRoles) {
707                         Set roleFunctions = role.getRoleFunctions();
708                         Iterator<EcompRoleFunction> roleIter = roleFunctions.iterator();
709                         ObjectMapper mapper = new ObjectMapper();
710                         Set<EcompRoleFunction> EcompRoleFunctions = new TreeSet<>();
711                         while (roleIter.hasNext()) {
712                                 String str = mapper.writeValueAsString(roleIter.next());
713
714                                 String str1 = str.substring(1, str.length() - 1);
715                                 Map<String, String> result = Arrays.stream(str1.split(",")).map(s -> s.split(":"))
716                                                 .collect(Collectors.toMap(a -> a[0], // key
717                                                                 a -> a[1] // value
718                                 ));
719
720                                 EcompRoleFunction roleFunction = new EcompRoleFunction();
721                                 for (Map.Entry<String, String> set : result.entrySet()) {
722                                         String key = set.getKey().replaceAll("\"", " ").trim();
723                                         if (!key.isEmpty() && key.equalsIgnoreCase("action")) {
724                                                 roleFunction.setAction(set.getValue().replaceAll("\"", " ").trim());
725                                         } else if (!key.isEmpty() && key.equalsIgnoreCase("type")) {
726                                                 roleFunction.setType(set.getValue().replaceAll("\"", " ").trim());
727
728                                         } else if (!key.isEmpty() && key.equalsIgnoreCase("code")) {
729                                                 roleFunction.setCode(set.getValue().replaceAll("\"", " ").trim());
730
731                                         } else if (!key.isEmpty() && key.equalsIgnoreCase("name")) {
732                                                 roleFunction.setName(set.getValue().replaceAll("\"", " ").trim());
733                                         }
734                                 }
735                                 EcompRoleFunctions.add(roleFunction);
736                         }
737                         role.setRoleFunctions(EcompRoleFunctions);
738                         userEcompRoles.add(role);
739                 }
740                 return userEcompRoles;
741         }
742 }