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