810771bd6f4df57adddbee18e4fdcf704a84461e
[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  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
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 credential = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
168                                         // for now lets also pass uebkey as user name and password
169                                         String requestBody = readRequestBody(request);
170                                         @SuppressWarnings("unchecked")
171                                         Map<String, String> bodyMap = mapper.readValue(requestBody, Map.class);
172                                         // add user ID
173                                         bodyMap.put("userid", userId);
174                                         requestBody = mapper.writeValueAsString(bodyMap);
175                                         responseJson = RestWebServiceClient.getInstance().postPortalContent(storeAnalyticsContextPath,
176                                                         userId, credential, null, credential, credential, "application/json", requestBody, true);
177                                         logger.debug("doPost: postPortalContent returns " + responseJson);
178                                         response.setStatus(HttpServletResponse.SC_OK);
179                                 } catch (Exception ex) {
180                                         logger.error("doPost: " + storeAnalyticsContextPath + " caught exception", ex);
181                                         responseJson = buildJsonResponse(ex);
182                                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
183                                 }
184                         }
185                         writeAndFlush(response, APPLICATION_JSON, responseJson);
186                         return;
187                 } // post analytics
188
189                 boolean secure = false;
190                 try {
191                         secure = isAppAuthenticated(request);
192                 } catch (PortalAPIException ex) {
193                         logger.error("doPost: isAppAuthenticated threw exception", ex);
194                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
195                         response.getWriter().write(buildJsonResponse(false, "Failed to authenticate request"));
196                         return;
197                 }
198                 if (!secure) {
199                         logger.debug("doPost: isAppAuthenticated answered false");
200                         response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
201                         writeAndFlush(response, APPLICATION_JSON, buildJsonResponse(false, "Not authorized"));
202                         return;
203                 }
204
205                 try {
206                         String requestBody = readRequestBody(request);
207                         if (logger.isDebugEnabled())
208                                 logger.debug("doPost: URI =  " + requestUri + ", payload = " + requestBody);
209
210                         /*
211                          * All APIs:
212                          * 
213                          * 1. /user <-- save user
214                          * 
215                          * 2. /user/{loginId} <-- edit user
216                          * 
217                          * 3. /user/{loginId}/roles <-- save roles for user
218                          */
219
220                         // On success return the empty string.
221
222                         if (requestUri.endsWith("/updateSessionTimeOuts")) {
223                                 if (updateSessionTimeOuts(requestBody)) {
224                                         logger.debug("doPost: updated session timeouts");
225                                         response.setStatus(HttpServletResponse.SC_OK);
226                                 } else {
227                                         String msg = "Failed to update session time outs";
228                                         logger.error("doPost: " + msg);
229                                         responseJson = buildJsonResponse(false, msg);
230                                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
231                                 }
232                         } else if (requestUri.endsWith("/timeoutSession")) {
233                                 String portalJSessionId = request.getParameter("portalJSessionId");
234                                 if (portalJSessionId == null) {
235                                         portalJSessionId = "";
236                                 }
237                                 if (timeoutSession(portalJSessionId)) {
238                                         logger.debug("doPost: timed out session");
239                                         response.setStatus(HttpServletResponse.SC_OK);
240                                 } else {
241                                         String msg = "Failed to timeout session";
242                                         logger.error("doPost: " + msg);
243                                         responseJson = buildJsonResponse(false, msg);
244                                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
245                                 }
246                         } else
247                         // Example: /user <-- create user
248                         if (requestUri.endsWith(PortalApiConstants.API_PREFIX + "/user")) {
249                                 try {
250                                         EcompUser user = mapper.readValue(requestBody, EcompUser.class);
251                                         pushUser(user);
252                                         if (logger.isDebugEnabled())
253                                                 logger.debug("doPost: pushUser: success");
254                                         responseJson = buildJsonResponse(true, null);
255                                         response.setStatus(HttpServletResponse.SC_OK);
256                                 } catch (Exception ex) {
257                                         responseJson = buildJsonResponse(ex);
258                                         response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
259                                         logger.error("doPost: pushUser: caught exception", ex);
260                                 }
261                         } else
262                         // Example: /user/abc <-- edit user abc 
263                         if (requestUri.contains(PortalApiConstants.API_PREFIX + "/user/") && !(requestUri.endsWith("/roles"))) {
264                                 String loginId = requestUri.substring(requestUri.lastIndexOf('/') + 1);
265                                 try {
266                                         EcompUser user = mapper.readValue(requestBody, EcompUser.class);
267                                         editUser(loginId, user);
268                                         if (logger.isDebugEnabled())
269                                                 logger.debug("doPost: editUser: success");
270                                         responseJson = buildJsonResponse(true, null);
271                                         response.setStatus(HttpServletResponse.SC_OK);
272                                 } catch (Exception ex) {
273                                         responseJson = buildJsonResponse(ex);
274                                         response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
275                                         logger.error("doPost: editUser: caught exception", ex);
276                                 }
277                         } else
278                         // Example: /user/{loginId}/roles <-- save roles for user
279                         if (requestUri.contains(PortalApiConstants.API_PREFIX + "/user/") && requestUri.endsWith("/roles")) {
280                                 String loginId = requestUri.substring(requestUri.indexOf("/user/") + ("/user").length() + 1,
281                                                 requestUri.lastIndexOf('/'));
282                                 try {
283                                         if (isCentralized.equals(isAccessCentralized)) {
284                                                 responseJson = buildJsonResponse(true, errorMessage);
285                                                 response.setStatus(HttpServletResponse.SC_OK);
286                                         } else {
287                                                 TypeReference<List<EcompRole>> typeRef = new TypeReference<List<EcompRole>>() {
288                                                 };
289                                                 List<EcompRole> roles = mapper.readValue(requestBody, typeRef);
290                                                 pushUserRole(loginId, roles);
291                                                 if (logger.isDebugEnabled())
292                                                         logger.debug("doPost: pushUserRole: success");
293                                                 responseJson = buildJsonResponse(true, null);
294                                                 response.setStatus(HttpServletResponse.SC_OK);
295                                         }
296                                 } catch (Exception ex) {
297                                         responseJson = buildJsonResponse(ex);
298                                         response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
299                                         logger.error("doPost: pushUserRole: caught exception", ex);
300                                 }
301                         } else {
302                                 String msg = "doPost: no match for request " + requestUri;
303                                 logger.warn( ESAPI.encoder().encodeForHTML(msg));
304                                 responseJson = buildJsonResponse(false, msg);
305                                 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
306                         }
307                 } catch (Exception ex) {
308                         logger.error("doPost: Failed to process request " + ESAPI.encoder().encodeForHTML(requestUri), ex);
309                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
310                         responseJson = buildJsonResponse(ex);
311                 }
312
313                 writeAndFlush(response, APPLICATION_JSON, responseJson);
314
315         }
316
317         @Override
318         protected void doGet(HttpServletRequest request, HttpServletResponse response)
319                         throws IOException, ServletException {
320
321                 if (portalRestApiServiceImpl == null) {
322                         // Should never happen due to checks in init()
323                         logger.error("doGet: no service class instance");
324                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
325                         writeAndFlush(response, APPLICATION_JSON,
326                                         buildJsonResponse(false, "Misconfigured - no instance of service class"));
327                         return;
328                 }
329
330                 String requestUri = request.getRequestURI();
331                 String contentType = APPLICATION_JSON;
332                 String webAnalyticsContextPath = "/analytics";
333                 if (requestUri.endsWith(PortalApiConstants.API_PREFIX + webAnalyticsContextPath)) {
334                         String responseString;
335                         String userId;
336                         try {
337                                 userId = getUserId(request);
338                         } catch (PortalAPIException e) {
339                                 logger.error("Issue with invoking getUserId implemenation !!! ", e);
340                                 throw new ServletException(e);
341                         }
342                         if (userId == null || userId.length() == 0) {
343                                 logger.debug("doGet: userId is null or empty");
344                                 response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
345                                 responseString = buildJsonResponse(false, "Not authorized for " + webAnalyticsContextPath);
346                         } else {
347                                 // User ID obtained from request
348                                 try {
349                                         String credential = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
350                                         // for now lets also pass uebkey as user name and password
351                                         contentType = "text/javascript";
352
353                                         responseString = RestWebServiceClient.getInstance().getPortalContent(webAnalyticsContextPath,
354                                                         userId, credential, null, credential, credential, true);
355                                         if (logger.isDebugEnabled())
356                                                 logger.debug("doGet: " + webAnalyticsContextPath + ": " + responseString);
357                                         response.setStatus(HttpServletResponse.SC_OK);
358                                 } catch (Exception ex) {
359                                         responseString = buildJsonResponse(ex);
360                                         response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
361                                         logger.error("doGet: " + webAnalyticsContextPath + " caught exception", ex);
362                                 }
363                         }
364                         writeAndFlush(response, contentType, responseString);
365                         return;
366                 }
367
368                 boolean secure = false;
369                 try {
370                         secure = isAppAuthenticated(request);
371                 } catch (PortalAPIException ex) {
372                         logger.error("doGet: isAppAuthenticated threw exception", ex);
373                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
374                         writeAndFlush(response, APPLICATION_JSON, buildJsonResponse(false, "Failed to authenticate request"));
375                         return;
376                 }
377
378                 if (!secure) {
379                         if (logger.isDebugEnabled())
380                                 logger.debug("doGet: isAppAuthenticated answered false");
381                         response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
382                         writeAndFlush(response, APPLICATION_JSON, buildJsonResponse(false, "Not authorized"));
383                         return;
384                 }
385
386                 String responseJson = null;
387                 try {
388                         // Ignore any request body in a GET.
389                         logger.debug("doGet: URI =  " + requestUri);
390
391                         /*
392                          * 1. /roles <-- get roles
393                          * 
394                          * 2. /user/{loginId} <-- get user
395                          * 
396                          * 3. /users <-- get all users
397                          * 
398                          * 4. /user/{loginId}/roles <-- get roles for user
399                          */
400
401                         if (requestUri.endsWith("/sessionTimeOuts")) {
402                                 try  {
403                                         responseJson = getSessionTimeOuts();
404                                         logger.debug("doGet: got session timeouts");
405                                         response.setStatus(HttpServletResponse.SC_OK);
406                                 } catch(Exception ex) {
407                                         String msg = "Failed to get session time outs";
408                                         logger.error("doGet: " + msg);
409                                         responseJson = buildJsonResponse(false, msg);
410                                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
411                                 }
412                         } else
413                         // Example: /users <-- get all users
414                         if (requestUri.endsWith(PortalApiConstants.API_PREFIX + "/users")) {
415                                 try {
416                                         List<EcompUser> users = getUsers();
417                                         responseJson = mapper.writeValueAsString(users);
418                                         if (logger.isDebugEnabled())
419                                                 logger.debug("doGet: getUsers: " + responseJson);
420                                 } catch (Exception ex) {
421                                         responseJson = buildShortJsonResponse(ex);
422                                         response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
423                                         logger.error("doGet: getUsers: caught exception", ex);
424                                 }
425                         } else
426                         // Example: /roles <-- get all roles
427
428                         if (requestUri.endsWith(PortalApiConstants.API_PREFIX + "/roles")) {
429                                 try {
430                                         List<EcompRole> roles = getAvailableRoles(getUserId(request));
431                                         responseJson = mapper.writeValueAsString(roles);
432                                         if (logger.isDebugEnabled())
433                                                 logger.debug("doGet: getAvailableRoles: " + responseJson);
434                                 } catch (Exception ex) {
435                                         responseJson = buildJsonResponse(ex);
436                                         response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
437                                         logger.error("doGet: getAvailableRoles: caught exception", ex);
438                                 }
439                         } else
440                         // Example: /user/abc <-- get user abc
441                         if (requestUri.contains(PortalApiConstants.API_PREFIX + "/user/") && !requestUri.endsWith("/roles")) {
442                                 String loginId = requestUri.substring(requestUri.lastIndexOf('/') + 1);
443                                 try {
444                                         EcompUser user = getUser(loginId);
445                                         responseJson = mapper.writeValueAsString(user);
446                                         if (logger.isDebugEnabled())
447                                                 logger.debug("doGet: getUser: " + responseJson);
448                                 } catch (Exception ex) {
449                                         responseJson = buildJsonResponse(ex);
450                                         response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
451                                         logger.error("doGet: getUser: caught exception", ex);
452                                 }
453                         }
454                         // Example: /user/abc/roles <-- get roles for user abc
455                         else if (requestUri.contains(PortalApiConstants.API_PREFIX + "/user/") && requestUri.endsWith("/roles")) {
456                                 String loginId = requestUri.substring(requestUri.indexOf("/user/") + ("/user").length() + 1,
457                                                 requestUri.lastIndexOf('/'));
458                                 try {
459                                         List<EcompRole> roles = getUserRoles(loginId);
460                                         responseJson = mapper.writeValueAsString(roles);
461                                         if (logger.isDebugEnabled())
462                                                 logger.debug("doGet: getUserRoles: " + responseJson);
463                                 } catch (Exception ex) {
464                                         responseJson = buildJsonResponse(ex);
465                                         response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
466                                         logger.error("doGet: getUserRoles: caught exception", ex);
467                                 }
468                         } else {
469                                 logger.warn("doGet: no match found for request");
470                                 responseJson = buildJsonResponse(false, "No match for request");
471                                 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
472                         }
473                 } catch (Exception ex) {
474                         logger.error("doGet: Failed to process request", ex);
475                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
476                         responseJson = buildJsonResponse(ex);
477                 }
478                 writeAndFlush(response, APPLICATION_JSON, responseJson);
479         }
480
481         public String getSessionTimeOuts() {
482                 return PortalTimeoutHandler.gatherSessionExtensions();
483         }
484
485         public boolean timeoutSession(String portalJSessionId) {
486                 return PortalTimeoutHandler.invalidateSession(portalJSessionId);
487         }
488
489         public boolean updateSessionTimeOuts(String sessionMap) {
490                 return PortalTimeoutHandler.updateSessionExtensions(sessionMap);
491         }
492
493         @Override
494         public void pushUser(EcompUser user) throws PortalAPIException {
495                 portalRestApiServiceImpl.pushUser(user);
496         }
497
498         @Override
499         public void editUser(String loginId, EcompUser user) throws PortalAPIException {
500                 portalRestApiServiceImpl.editUser(loginId, user);
501         }
502
503         @Override
504         public EcompUser getUser(String loginId) throws PortalAPIException {
505                 return portalRestApiServiceImpl.getUser(loginId);
506         }
507
508         @Override
509         public List<EcompUser> getUsers() throws PortalAPIException {
510                 return portalRestApiServiceImpl.getUsers();
511         }
512
513         @Override
514         public List<EcompRole> getAvailableRoles(String requestedLoginId) throws PortalAPIException {
515                 return portalRestApiServiceImpl.getAvailableRoles(requestedLoginId);
516         }
517
518         @Override
519         public void pushUserRole(String loginId, List<EcompRole> roles) throws PortalAPIException {
520                 portalRestApiServiceImpl.pushUserRole(loginId, roles);
521         }
522
523         @Override
524         public List<EcompRole> getUserRoles(String loginId) throws PortalAPIException {
525                 return portalRestApiServiceImpl.getUserRoles(loginId);
526         }
527
528         @Override
529         public boolean isAppAuthenticated(HttpServletRequest request) throws PortalAPIException {
530                 return portalRestApiServiceImpl.isAppAuthenticated(request);
531         }
532
533         /**
534          * Sets the content type and writes the response.
535          * 
536          * @param response
537          * @param contentType
538          * @param responseBody
539          * @throws IOException
540          */
541         private void writeAndFlush(HttpServletResponse response, String contentType, String responseBody)
542                         throws IOException {
543                 response.setContentType(contentType);
544                 PrintWriter out = response.getWriter();
545                 out.print(responseBody);
546                 out.flush();
547         }
548
549         /**
550          * Reads the request body and closes the input stream.
551          * 
552          * @param request
553          * @return String read from the request, the empty string if nothing is read.
554          * @throws IOException
555          */
556         private static String readRequestBody(HttpServletRequest request) throws IOException {
557
558                 String body = null;
559                 StringBuilder stringBuilder = new StringBuilder();
560                 BufferedReader bufferedReader = null;
561                 try {
562                         InputStream inputStream = request.getInputStream();
563                         if (inputStream != null) {
564                                 bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
565                                 char[] charBuffer = new char[1024];
566                                 int bytesRead = -1;
567                                 while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
568                                         stringBuilder.append(charBuffer, 0, bytesRead);
569                                 }
570                         } else {
571                                 stringBuilder.append("");
572                         }
573                 } finally {
574                         if (bufferedReader != null) {
575                                 try {
576                                         bufferedReader.close();
577                                 } catch (IOException ex) {
578                                         logger.error("readRequestBody", ex);
579                                 }
580                         }
581                 }
582                 body = stringBuilder.toString();
583                 return body;
584         }
585
586         /**
587          * Builds JSON object with status + message response body.
588          * 
589          * @param success
590          *            True to indicate success, false to signal failure.
591          * @param msg
592          *            Message to include in the response object; ignored if null.
593          * @return
594          * 
595          *         <pre>
596          * { "status" : "ok" (or "error"), "message": "some explanation" }
597          *         </pre>
598          */
599         private String buildJsonResponse(boolean success, String msg) {
600                 PortalAPIResponse response = new PortalAPIResponse(success, msg);
601                 String json = null;
602                 try {
603                         json = mapper.writeValueAsString(response);
604                 } catch (JsonProcessingException ex) {
605                         // Truly should never, ever happen
606                         logger.error("buildJsonResponse", ex);
607                         json = "{ \"status\": \"error\",\"message\":\"" + ex.toString() + "\" }";
608                 }
609                 return json;
610         }
611
612         /**
613          * Builds JSON object with status of error and message containing stack trace
614          * for the specified throwable.
615          * 
616          * @param t
617          *            Throwable with stack trace to use as message
618          * 
619          * @return
620          * 
621          *         <pre>
622          * { "status" : "error", "message": "some-big-stacktrace" }
623          *         </pre>
624          */
625         private String buildJsonResponse(Throwable t) {
626                 StringWriter sw = new StringWriter();
627                 PrintWriter pw = new PrintWriter(sw);
628                 t.printStackTrace(pw);
629                 return buildJsonResponse(false, sw.toString());
630         }
631         
632         private String buildShortJsonResponse(Throwable t)
633         {
634                 String errorMessage = t.getMessage();
635                 return buildJsonResponse(false, errorMessage);
636         }
637
638         @Override
639         public String getUserId(HttpServletRequest request) throws PortalAPIException {
640                 return portalRestApiServiceImpl.getUserId(request);
641         }
642
643         public static IPortalRestAPIService getPortalRestApiServiceImpl() {
644                 return portalRestApiServiceImpl;
645         }
646
647         public static void setPortalRestApiServiceImpl(IPortalRestAPIService portalRestApiServiceImpl) {
648                 PortalRestAPIProxy.portalRestApiServiceImpl = portalRestApiServiceImpl;
649         }
650
651 }