2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
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
13 * http://www.apache.org/licenses/LICENSE-2.0
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.
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
26 * https://creativecommons.org/licenses/by/4.0/
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.
34 * ============LICENSE_END============================================
38 package org.onap.portalsdk.core.onboarding.crossapi;
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;
51 import java.util.TreeSet;
52 import java.util.stream.Collectors;
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;
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;
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;
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.
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>
92 * This servlet will not start if the required portal.properties file is not
93 * found on the classpath.
96 @WebServlet(urlPatterns = { PortalApiConstants.API_PREFIX + "/*" })
97 public class PortalRestAPIProxy extends HttpServlet implements IPortalRestAPIService {
99 private static final long serialVersionUID = 1L;
101 private static final String APPLICATION_JSON = "application/json";
103 private static final Log logger = LogFactory.getLog(PortalRestAPIProxy.class);
106 * Mapper for JSON to object etc.
108 private final ObjectMapper mapper = new ObjectMapper();
111 * Client-supplied class that implements our interface.
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";
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);
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);
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());
138 portalRestApiServiceImpl = new PortalRestAPICentralServiceImpl();
140 } catch (Exception ex) {
141 throw new ServletException("init: Failed to find or instantiate class " + className, ex);
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"));
157 String requestUri = request.getRequestURI();
158 String responseJson = "";
159 String storeAnalyticsContextPath = "/storeAnalytics";
160 if (requestUri.endsWith(PortalApiConstants.API_PREFIX + storeAnalyticsContextPath)) {
163 userId = getUserId(request);
164 } catch (PortalAPIException e) {
165 logger.error("Issue with invoking getUserId implemenation !!! ", e);
166 throw new ServletException(e);
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);
173 // User ID obtained from request
175 String appUserName = "";
176 String appPassword = "";
179 for (Map.Entry<String, String> entry : getCredentials().entrySet()) {
181 if (entry.getKey().equalsIgnoreCase("username")) {
182 appUserName = entry.getValue();
183 } else if (entry.getKey().equalsIgnoreCase("password")) {
184 appPassword = entry.getValue();
186 appName = entry.getValue();
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);
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);
209 writeAndFlush(response, APPLICATION_JSON, responseJson);
213 boolean secure = false;
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"));
223 logger.debug("doPost: isAppAuthenticated answered false");
224 response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
225 writeAndFlush(response, APPLICATION_JSON, buildJsonResponse(false, "Not authorized"));
231 String requestBody = readRequestBody(request);
232 if (logger.isDebugEnabled())
233 logger.debug("doPost: URI = " + requestUri + ", payload = " + requestBody);
238 * 1. /user <-- save user
240 * 2. /user/{loginId} <-- edit user
242 * 3. /user/{loginId}/roles <-- save roles for user
245 // On success return the empty string.
247 if (requestUri.endsWith("/updateSessionTimeOuts")) {
248 if (updateSessionTimeOuts(requestBody)) {
249 logger.debug("doPost: updated session timeouts");
250 response.setStatus(HttpServletResponse.SC_OK);
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);
257 } else if (requestUri.endsWith("/timeoutSession")) {
258 String portalJSessionId = request.getParameter("portalJSessionId");
259 if (portalJSessionId == null) {
260 portalJSessionId = "";
262 if (timeoutSession(portalJSessionId)) {
263 logger.debug("doPost: timed out session");
264 response.setStatus(HttpServletResponse.SC_OK);
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);
272 // Example: /user <-- create user
273 if (requestUri.endsWith(PortalApiConstants.API_PREFIX + "/user")) {
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);
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);
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);
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);
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('/'));
314 if (isCentralized.equals(isAccessCentralized)) {
315 responseJson = buildJsonResponse(true, errorMessage);
316 response.setStatus(HttpServletResponse.SC_OK);
318 TypeReference<List<EcompRole>> typeRef = new TypeReference<List<EcompRole>>() {
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);
327 } catch (Exception ex) {
328 responseJson = buildShortJsonResponse(ex);
329 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
330 logger.error("doPost: pushUserRole: caught exception", ex);
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);
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);
344 writeAndFlush(response, APPLICATION_JSON, responseJson);
349 protected void doGet(HttpServletRequest request, HttpServletResponse response)
350 throws IOException, ServletException {
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"));
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;
369 userId = getUserId(request);
370 } catch (PortalAPIException e) {
371 logger.error("Issue with invoking getUserId implemenation !!! ", e);
372 throw new ServletException(e);
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);
379 // User ID obtained from request
381 String appUserName = "";
382 String appPassword = "";
385 for (Map.Entry<String, String> entry : getCredentials().entrySet()) {
387 if (entry.getKey().equalsIgnoreCase("username")) {
388 appUserName = entry.getValue();
389 } else if (entry.getKey().equalsIgnoreCase("password")) {
390 appPassword = entry.getValue();
392 appName = entry.getValue();
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";
399 responseString = RestWebServiceClient.getInstance().getPortalContent(webAnalyticsContextPath,
400 userId, appName, null, appUserName, appPassword, true);
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);
411 writeAndFlush(response, contentType, responseString);
415 boolean secure = false;
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"));
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"));
432 String responseJson = null;
434 // Ignore any request body in a GET.
435 logger.debug("doGet: URI = " + requestUri);
438 * 1. /roles <-- get roles
440 * 2. /user/{loginId} <-- get user
442 * 3. /users <-- get all users
444 * 4. /user/{loginId}/roles <-- get roles for user
447 if (requestUri.endsWith("/sessionTimeOuts")) {
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);
459 // Example: /users <-- get all users
460 if (requestUri.endsWith(PortalApiConstants.API_PREFIX + "/users")) {
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);
472 // Example: /roles <-- get all roles
474 if (requestUri.endsWith(PortalApiConstants.API_PREFIX + "/roles")) {
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);
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);
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);
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('/'));
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);
516 logger.warn("doGet: no match found for request");
517 responseJson = buildJsonResponse(false, "No match for request");
518 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
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);
525 writeAndFlush(response, APPLICATION_JSON, responseJson);
528 public String getSessionTimeOuts() {
529 return PortalTimeoutHandler.gatherSessionExtensions();
532 public boolean timeoutSession(String portalJSessionId) {
533 return PortalTimeoutHandler.invalidateSession(portalJSessionId);
536 public boolean updateSessionTimeOuts(String sessionMap) {
537 return PortalTimeoutHandler.updateSessionExtensions(sessionMap);
541 public void pushUser(EcompUser user) throws PortalAPIException {
542 portalRestApiServiceImpl.pushUser(user);
546 public void editUser(String loginId, EcompUser user) throws PortalAPIException {
547 portalRestApiServiceImpl.editUser(loginId, user);
551 public EcompUser getUser(String loginId) throws PortalAPIException {
552 return portalRestApiServiceImpl.getUser(loginId);
556 public List<EcompUser> getUsers() throws PortalAPIException {
557 return portalRestApiServiceImpl.getUsers();
561 public List<EcompRole> getAvailableRoles(String requestedLoginId) throws PortalAPIException {
562 return portalRestApiServiceImpl.getAvailableRoles(requestedLoginId);
566 public void pushUserRole(String loginId, List<EcompRole> roles) throws PortalAPIException {
567 portalRestApiServiceImpl.pushUserRole(loginId, roles);
571 public List<EcompRole> getUserRoles(String loginId) throws PortalAPIException {
572 return portalRestApiServiceImpl.getUserRoles(loginId);
576 public boolean isAppAuthenticated(HttpServletRequest request, Map<String,String> appCredentials) throws PortalAPIException {
577 return portalRestApiServiceImpl.isAppAuthenticated(request, appCredentials);
581 * Sets the content type and writes the response.
585 * @param responseBody
586 * @throws IOException
588 private void writeAndFlush(HttpServletResponse response, String contentType, String responseBody)
590 response.setContentType(contentType);
591 PrintWriter out = response.getWriter();
592 out.print(responseBody);
597 * Reads the request body and closes the input stream.
600 * @return String read from the request, the empty string if nothing is read.
601 * @throws IOException
603 private static String readRequestBody(HttpServletRequest request) throws IOException {
606 StringBuilder stringBuilder = new StringBuilder();
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];
613 while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
614 stringBuilder.append(charBuffer, 0, bytesRead);
616 } catch(IOException e) {
617 logger.error("readRequestBody", e);
621 stringBuilder.append("");
623 } catch(IOException e) {
624 logger.error("readRequestBody", e);
627 body = stringBuilder.toString();
632 * Builds JSON object with status + message response body.
635 * True to indicate success, false to signal failure.
637 * Message to include in the response object; ignored if null.
641 * { "status" : "ok" (or "error"), "message": "some explanation" }
644 private String buildJsonResponse(boolean success, String msg) {
645 PortalAPIResponse response = new PortalAPIResponse(success, msg);
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() + "\" }";
658 * Builds JSON object with status of error and message containing stack trace
659 * for the specified throwable.
662 * Throwable with stack trace to use as message
667 * { "status" : "error", "message": "some-big-stacktrace" }
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());
677 private String buildShortJsonResponse(Throwable t)
679 String errorMessage = t.getMessage();
680 return buildJsonResponse(false, errorMessage);
684 public String getUserId(HttpServletRequest request) throws PortalAPIException {
685 return portalRestApiServiceImpl.getUserId(request);
688 public static IPortalRestAPIService getPortalRestApiServiceImpl() {
689 return portalRestApiServiceImpl;
692 public static void setPortalRestApiServiceImpl(IPortalRestAPIService portalRestApiServiceImpl) {
693 PortalRestAPIProxy.portalRestApiServiceImpl = portalRestApiServiceImpl;
697 public Map<String, String> getCredentials() throws PortalAPIException {
698 return portalRestApiServiceImpl.getCredentials();
701 private Set<EcompRole> getEcompRolesOfUser(EcompUser user) throws JsonProcessingException
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());
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
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());
728 } else if (!key.isEmpty() && key.equalsIgnoreCase("code")) {
729 roleFunction.setCode(set.getValue().replaceAll("\"", " ").trim());
731 } else if (!key.isEmpty() && key.equalsIgnoreCase("name")) {
732 roleFunction.setName(set.getValue().replaceAll("\"", " ").trim());
735 EcompRoleFunctions.add(roleFunction);
737 role.setRoleFunctions(EcompRoleFunctions);
738 userEcompRoles.add(role);
740 return userEcompRoles;