summaryrefslogtreecommitdiffstats
path: root/ecomp-sdk/epsdk-fw/src/main/java/org/onap/portalsdk/core/onboarding/crossapi/PortalRestAPIProxy.java
blob: 71f66168559d0cfb288e92efdd50d8121294e8ea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
/*
 * ============LICENSE_START==========================================
 * ONAP Portal SDK
 * ===================================================================
 * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
 * ===================================================================
 *
 * Unless otherwise specified, all software contained herein is licensed
 * under the Apache License, Version 2.0 (the "License");
 * you may not use this software except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *             http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Unless otherwise specified, all documentation contained herein is licensed
 * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
 * you may not use this documentation except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *             https://creativecommons.org/licenses/by/4.0/
 *
 * Unless required by applicable law or agreed to in writing, documentation
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * ============LICENSE_END============================================
 *
 * 
 */
package org.onap.portalsdk.core.onboarding.crossapi;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.onap.portalsdk.core.onboarding.exception.PortalAPIException;
import org.onap.portalsdk.core.onboarding.listener.PortalTimeoutHandler;
import org.onap.portalsdk.core.onboarding.rest.RestWebServiceClient;
import org.onap.portalsdk.core.onboarding.util.PortalApiConstants;
import org.onap.portalsdk.core.onboarding.util.PortalApiProperties;
import org.onap.portalsdk.core.restful.domain.EcompRole;
import org.onap.portalsdk.core.restful.domain.EcompRoleFunction;
import org.onap.portalsdk.core.restful.domain.EcompUser;
import org.owasp.esapi.ESAPI;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * This servlet performs the functions described below. It listens on a path
 * like "/api" (see {@link PortalApiConstants#API_PREFIX}). The servlet checks
 * for authorized access and rejects unauthorized requests.
 * <OL>
 * <LI>Proxies user (i.e., browser) requests for web analytics. The GET method
 * fetches javascript from the Portal and returns it. The POST method forwards
 * data sent by the browser on to Portal. These requests are checked for a valid
 * User UID in a header; these requests do NOT use the application
 * username-password header.</LI>
 * <LI>Responds to ECOMP Portal API requests to query and update user, role and
 * user-role information. The servlet proxies all requests on to a local Java
 * class that implements {@link IPortalRestAPIService}. These requests must have
 * the application username-password header.</LI>
 * </OL>
 * This servlet will not start if the required portal.properties file is not
 * found on the classpath.
 */

@WebServlet(urlPatterns = { PortalApiConstants.API_PREFIX + "/*" })
public class PortalRestAPIProxy extends HttpServlet implements IPortalRestAPIService {
	
	private static final long serialVersionUID = 1L;

	private static final String APPLICATION_JSON = "application/json";

	private static final Log logger = LogFactory.getLog(PortalRestAPIProxy.class);

	/**
	 * Mapper for JSON to object etc.
	 */
	private final ObjectMapper mapper = new ObjectMapper();

	/**
	 * Client-supplied class that implements our interface.
	 */
	private static IPortalRestAPIService portalRestApiServiceImpl;
	private static final String isAccessCentralized = PortalApiProperties
			.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED);
	private static final String errorMessage = "Access Management is not allowed for Centralized applications." ;
	private static final String isCentralized = "remote";


	public PortalRestAPIProxy() {
		// Ensure that any additional fields sent by the Portal
		// will be ignored when creating objects.
		mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	}

	@Override
	public void init() throws ServletException {
		String className = PortalApiProperties.getProperty(PortalApiConstants.PORTAL_API_IMPL_CLASS);
		if (className == null)
			throw new ServletException(
					"init: Failed to find class name property " + PortalApiConstants.PORTAL_API_IMPL_CLASS);
		try {
			logger.debug("init: creating instance of class " + className);
			Class<?> implClass = Class.forName(className);
			if (!isCentralized.equals(isAccessCentralized))
				portalRestApiServiceImpl = (IPortalRestAPIService) (implClass.getConstructor().newInstance());
			else {
				portalRestApiServiceImpl = new PortalRestAPICentralServiceImpl();				
			}
		} catch (Exception ex) {
			throw new ServletException("init: Failed to find or instantiate class " + className, ex);
		}
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		if (portalRestApiServiceImpl == null) {
			// Should never happen due to checks in init()
			logger.error("doPost: no service class instance");
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			response.getWriter().write(buildJsonResponse(false, "Misconfigured - no instance of service class"));
			return;
		}
		
	
		String requestUri = request.getRequestURI();
		String responseJson = "";
		String storeAnalyticsContextPath = "/storeAnalytics";
		if (requestUri.endsWith(PortalApiConstants.API_PREFIX + storeAnalyticsContextPath)) {
			String userId;
			try {
				userId = getUserId(request);
			} catch (PortalAPIException e) {
				logger.error("Issue with invoking getUserId implemenation !!! ", e);
				throw new ServletException(e);
			}
			if (userId == null || userId.length() == 0) {
				logger.debug("doPost: userId is null or empty");
				response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
				responseJson = buildJsonResponse(false, "Not authorized for " + storeAnalyticsContextPath);
			} else {
				// User ID obtained from request
				try {
					String appUserName = "";
					String appPassword = "";
					String appName = "";

					for (Map.Entry<String, String> entry : getCredentials().entrySet()) {

						if (entry.getKey().equalsIgnoreCase("username")) {
							appUserName = entry.getValue();
						} else if (entry.getKey().equalsIgnoreCase("password")) {
							appPassword = entry.getValue();
						} else {
							appName = entry.getValue();
						}
					}
					
					String credential = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
					// for now lets also pass uebkey as user name and password
					String requestBody = readRequestBody(request);
					@SuppressWarnings("unchecked")
					Map<String, String> bodyMap = mapper.readValue(requestBody, Map.class);
					// add user ID
					bodyMap.put("userid", userId);
					requestBody = mapper.writeValueAsString(bodyMap);
					logger.debug("doPost:  StoreAnalytics requestbody: "+ requestBody);
					responseJson = RestWebServiceClient.getInstance().postPortalContent(storeAnalyticsContextPath,
							userId, appName, null, appUserName, appPassword, "application/json", requestBody, true);
					logger.debug("doPost: postPortalContent returns " + responseJson);
					response.setStatus(HttpServletResponse.SC_OK);
				} catch (Exception ex) {
					logger.error("doPost: " + storeAnalyticsContextPath + " caught exception", ex);
					responseJson = buildJsonResponse(ex);
					response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
				}
			}
			writeAndFlush(response, APPLICATION_JSON, responseJson);
			return;
		} // post analytics

		boolean secure = false;
		try {
			secure = isAppAuthenticated(request);
		} catch (PortalAPIException ex) {
			logger.error("doPost: isAppAuthenticated threw exception", ex);
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			response.getWriter().write(buildJsonResponse(false, "Failed to authenticate request"));
			return;
		}
		if (!secure) {
			logger.debug("doPost: isAppAuthenticated answered false");
			response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
			writeAndFlush(response, APPLICATION_JSON, buildJsonResponse(false, "Not authorized"));
			return;
		}
		

		try {
			String requestBody = readRequestBody(request);
			if (logger.isDebugEnabled())
				logger.debug("doPost: URI =  " + requestUri + ", payload = " + requestBody);

			/*
			 * All APIs:
			 * 
			 * 1. /user <-- save user
			 * 
			 * 2. /user/{loginId} <-- edit user
			 * 
			 * 3. /user/{loginId}/roles <-- save roles for user
			 */

			// On success return the empty string.

			if (requestUri.endsWith("/updateSessionTimeOuts")) {
				if (updateSessionTimeOuts(requestBody)) {
					logger.debug("doPost: updated session timeouts");
					response.setStatus(HttpServletResponse.SC_OK);
				} else {
					String msg = "Failed to update session time outs";
					logger.error("doPost: " + msg);
					responseJson = buildJsonResponse(false, msg);
					response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
				}
			} else if (requestUri.endsWith("/timeoutSession")) {
				String portalJSessionId = request.getParameter("portalJSessionId");
				if (portalJSessionId == null) {
					portalJSessionId = "";
				}
				if (timeoutSession(portalJSessionId)) {
					logger.debug("doPost: timed out session");
					response.setStatus(HttpServletResponse.SC_OK);
				} else {
					String msg = "Failed to timeout session";
					logger.error("doPost: " + msg);
					responseJson = buildJsonResponse(false, msg);
					response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
				}
			} else
			// Example: /user <-- create user
			if (requestUri.endsWith(PortalApiConstants.API_PREFIX + "/user")) {
				try {
					EcompUser user = mapper.readValue(requestBody, EcompUser.class);
					logger.debug("doPost:  create user requestbody: "+ requestBody);
					Set<EcompRole> userEcompRoles = getEcompRolesOfUser(user);
					user.setRoles(userEcompRoles);
					pushUser(user);
					if (logger.isDebugEnabled())
						logger.debug("doPost: pushUser: success");
					responseJson = buildJsonResponse(true, "user saved successfully");
					response.setStatus(HttpServletResponse.SC_OK);
				} catch (Exception ex) {
					responseJson = buildJsonResponse(ex);
					response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
					logger.error("doPost: pushUser: caught exception", ex);
				}
			} else
			// Example: /user/abc <-- edit user abc 
			if (requestUri.contains(PortalApiConstants.API_PREFIX + "/user/") && !(requestUri.endsWith("/roles"))) {
				String loginId = requestUri.substring(requestUri.lastIndexOf('/') + 1);
				try {
					EcompUser user = mapper.readValue(requestBody, EcompUser.class);
					logger.debug("doPost:  update user requestbody: "+ requestBody);
					Set<EcompRole> userEcompRoles = getEcompRolesOfUser(user);
					user.setRoles(userEcompRoles);
					editUser(loginId, user);
					if (logger.isDebugEnabled())
						logger.debug("doPost: editUser: success");
					responseJson = buildJsonResponse(true, "user saved successfully");
					response.setStatus(HttpServletResponse.SC_OK);
				} catch (Exception ex) {
					responseJson = buildJsonResponse(ex);
					response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
					logger.error("doPost: editUser: caught exception", ex);
				}
			} else
			// Example: /user/{loginId}/roles <-- save roles for user
			if (requestUri.contains(PortalApiConstants.API_PREFIX + "/user/") && requestUri.endsWith("/roles")) {
				String loginId = requestUri.substring(requestUri.indexOf("/user/") + ("/user").length() + 1,
						requestUri.lastIndexOf('/'));
				try {
					if (isCentralized.equals(isAccessCentralized)) {
						responseJson = buildJsonResponse(true, errorMessage);
						response.setStatus(HttpServletResponse.SC_OK);
					} else {
						TypeReference<List<EcompRole>> typeRef = new TypeReference<List<EcompRole>>() {
						};
						List<EcompRole> roles = mapper.readValue(requestBody, typeRef);
						pushUserRole(loginId, roles);
						if (logger.isDebugEnabled())
							logger.debug("doPost: pushUserRole: success");
						responseJson = buildJsonResponse(true, "saveRoles is successful");
						response.setStatus(HttpServletResponse.SC_OK);
					}
				} catch (Exception ex) {
					responseJson = buildJsonResponse(ex);
					response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
					logger.error("doPost: pushUserRole: caught exception", ex);
				}
			} else {
				String msg = "doPost: no match for request " + requestUri;
				logger.warn( ESAPI.encoder().encodeForHTML(msg));
				responseJson = buildJsonResponse(false, msg);
				response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			}
		} catch (Exception ex) {
			logger.error("doPost: Failed to process request " + ESAPI.encoder().encodeForHTML(requestUri), ex);
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			responseJson = buildJsonResponse(ex);
		}

		writeAndFlush(response, APPLICATION_JSON, responseJson);

	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {

		if (portalRestApiServiceImpl == null) {
			// Should never happen due to checks in init()
			logger.error("doGet: no service class instance");
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			writeAndFlush(response, APPLICATION_JSON,
					buildJsonResponse(false, "Misconfigured - no instance of service class"));
			return;
		}
		

		String requestUri = request.getRequestURI();
		String contentType = APPLICATION_JSON;
		String webAnalyticsContextPath = "/analytics";
		if (requestUri.endsWith(PortalApiConstants.API_PREFIX + webAnalyticsContextPath)) {
			String responseString;
			String userId;
			try {
				userId = getUserId(request);
			} catch (PortalAPIException e) {
				logger.error("Issue with invoking getUserId implemenation !!! ", e);
				throw new ServletException(e);
			}
			if (userId == null || userId.length() == 0) {
				logger.debug("doGet: userId is null or empty");
				response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
				responseString = buildJsonResponse(false, "Not authorized for " + webAnalyticsContextPath);
			} else {
				// User ID obtained from request
				try {
					String appUserName = "";
					String appPassword = "";
					String appName = "";

					for (Map.Entry<String, String> entry : getCredentials().entrySet()) {

						if (entry.getKey().equalsIgnoreCase("username")) {
							appUserName = entry.getValue();
						} else if (entry.getKey().equalsIgnoreCase("password")) {
							appPassword = entry.getValue();
						} else {
							appName = entry.getValue();
						}
					}
					String credential = PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY);
					// for now lets also pass uebkey as user name and password
					contentType = "text/javascript";

					responseString = RestWebServiceClient.getInstance().getPortalContent(webAnalyticsContextPath,
							userId, appName, null, appUserName, appPassword, true);
					
					if (logger.isDebugEnabled())
						logger.debug("doGet: " + webAnalyticsContextPath + ": " + responseString);
					response.setStatus(HttpServletResponse.SC_OK);
				} catch (Exception ex) {
					responseString = buildJsonResponse(ex);
					response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
					logger.error("doGet: " + webAnalyticsContextPath + " caught exception", ex);
				}
			}
			writeAndFlush(response, contentType, responseString);
			return;
		}

		boolean secure = false;
		try {
			secure = isAppAuthenticated(request);
		} catch (PortalAPIException ex) {
			logger.error("doGet: isAppAuthenticated threw exception", ex);
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			writeAndFlush(response, APPLICATION_JSON, buildJsonResponse(false, "Failed to authenticate request"));
			return;
		}

		if (!secure) {
			if (logger.isDebugEnabled())
				logger.debug("doGet: isAppAuthenticated answered false");
			response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
			writeAndFlush(response, APPLICATION_JSON, buildJsonResponse(false, "Not authorized"));
			return;
		}
		String responseJson = null;
		try {
			// Ignore any request body in a GET.
			logger.debug("doGet: URI =  " + requestUri);

			/*
			 * 1. /roles <-- get roles
			 * 
			 * 2. /user/{loginId} <-- get user
			 * 
			 * 3. /users <-- get all users
			 * 
			 * 4. /user/{loginId}/roles <-- get roles for user
			 */

			if (requestUri.endsWith("/sessionTimeOuts")) {
				try  {
					responseJson = getSessionTimeOuts();
					logger.debug("doGet: got session timeouts");
					response.setStatus(HttpServletResponse.SC_OK);
				} catch(Exception ex) {
					String msg = "Failed to get session time outs";
					logger.error("doGet: " + msg);
					responseJson = buildJsonResponse(false, msg);
					response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
				}
			} else
			// Example: /users <-- get all users
			if (requestUri.endsWith(PortalApiConstants.API_PREFIX + "/users")) {
				try {
					List<EcompUser> users = getUsers();
					responseJson = mapper.writeValueAsString(users);
					if (logger.isDebugEnabled())
						logger.debug("doGet: getUsers: " + responseJson);
				} catch (Exception ex) {
					responseJson = buildShortJsonResponse(ex);
					response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
					logger.error("doGet: getUsers: caught exception", ex);
				}
			} else
			// Example: /roles <-- get all roles

			if (requestUri.endsWith(PortalApiConstants.API_PREFIX + "/roles")) {
				try {
					List<EcompRole> roles = getAvailableRoles(getUserId(request));
					responseJson = mapper.writeValueAsString(roles);
					if (logger.isDebugEnabled())
						logger.debug("doGet: getAvailableRoles: " + responseJson);
				} catch (Exception ex) {
					responseJson = buildJsonResponse(ex);
					response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
					logger.error("doGet: getAvailableRoles: caught exception", ex);
				}
			} else
			// Example: /user/abc <-- get user abc
			if (requestUri.contains(PortalApiConstants.API_PREFIX + "/user/") && !requestUri.endsWith("/roles")) {
				String loginId = requestUri.substring(requestUri.lastIndexOf('/') + 1);
				try {
					EcompUser user = getUser(loginId);
					responseJson = mapper.writeValueAsString(user);
					if (logger.isDebugEnabled())
						logger.debug("doGet: getUser: " + responseJson);
				} catch (Exception ex) {
					responseJson = buildJsonResponse(ex);
					response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
					logger.error("doGet: getUser: caught exception", ex);
				}
			}
			// Example: /user/abc/roles <-- get roles for user abc
			else if (requestUri.contains(PortalApiConstants.API_PREFIX + "/user/") && requestUri.endsWith("/roles")) {
				String loginId = requestUri.substring(requestUri.indexOf("/user/") + ("/user").length() + 1,
						requestUri.lastIndexOf('/'));
				try {
					List<EcompRole> roles = getUserRoles(loginId);
					responseJson = mapper.writeValueAsString(roles);
					if (logger.isDebugEnabled())
						logger.debug("doGet: getUserRoles: " + responseJson);
				} catch (Exception ex) {
					responseJson = buildJsonResponse(ex);
					response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
					logger.error("doGet: getUserRoles: caught exception", ex);
				}
			}
			else {
				logger.warn("doGet: no match found for request");
				responseJson = buildJsonResponse(false, "No match for request");
				response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			}
		} catch (Exception ex) {
			logger.error("doGet: Failed to process request", ex);
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			responseJson = buildJsonResponse(ex);
		}
		writeAndFlush(response, APPLICATION_JSON, responseJson);
	}

	public String getSessionTimeOuts() {
		return PortalTimeoutHandler.gatherSessionExtensions();
	}

	public boolean timeoutSession(String portalJSessionId) {
		return PortalTimeoutHandler.invalidateSession(portalJSessionId);
	}

	public boolean updateSessionTimeOuts(String sessionMap) {
		return PortalTimeoutHandler.updateSessionExtensions(sessionMap);
	}

	@Override
	public void pushUser(EcompUser user) throws PortalAPIException {
		portalRestApiServiceImpl.pushUser(user);
	}

	@Override
	public void editUser(String loginId, EcompUser user) throws PortalAPIException {
		portalRestApiServiceImpl.editUser(loginId, user);
	}

	@Override
	public EcompUser getUser(String loginId) throws PortalAPIException {
		return portalRestApiServiceImpl.getUser(loginId);
	}

	@Override
	public List<EcompUser> getUsers() throws PortalAPIException {
		return portalRestApiServiceImpl.getUsers();
	}

	@Override
	public List<EcompRole> getAvailableRoles(String requestedLoginId) throws PortalAPIException {
		return portalRestApiServiceImpl.getAvailableRoles(requestedLoginId);
	}

	@Override
	public void pushUserRole(String loginId, List<EcompRole> roles) throws PortalAPIException {
		portalRestApiServiceImpl.pushUserRole(loginId, roles);
	}

	@Override
	public List<EcompRole> getUserRoles(String loginId) throws PortalAPIException {
		return portalRestApiServiceImpl.getUserRoles(loginId);
	}

	@Override
	public boolean isAppAuthenticated(HttpServletRequest request) throws PortalAPIException {
		return portalRestApiServiceImpl.isAppAuthenticated(request);
	}

	/**
	 * Sets the content type and writes the response.
	 * 
	 * @param response
	 * @param contentType
	 * @param responseBody
	 * @throws IOException
	 */
	private void writeAndFlush(HttpServletResponse response, String contentType, String responseBody)
			throws IOException {
		response.setContentType(contentType);
		PrintWriter out = response.getWriter();
		out.print(responseBody);
		out.flush();
	}

	/**
	 * Reads the request body and closes the input stream.
	 * 
	 * @param request
	 * @return String read from the request, the empty string if nothing is read.
	 * @throws IOException
	 */
	private static String readRequestBody(HttpServletRequest request) throws IOException {

		String body = null;
		StringBuilder stringBuilder = new StringBuilder();

		try(InputStream inputStream = request.getInputStream()) {
			if (inputStream != null) {
				try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));){
					char[] charBuffer = new char[1024];
					int bytesRead = -1;
					while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
						stringBuilder.append(charBuffer, 0, bytesRead);
					}
				} catch(IOException e) {
					logger.error("readRequestBody", e);
					throw e;
				}
			} else {
				stringBuilder.append("");
			}
		} catch(IOException e) {
			logger.error("readRequestBody", e);
			throw e;
		}
		body = stringBuilder.toString();
		return body;
	}

	/**
	 * Builds JSON object with status + message response body.
	 * 
	 * @param success
	 *            True to indicate success, false to signal failure.
	 * @param msg
	 *            Message to include in the response object; ignored if null.
	 * @return
	 * 
	 *         <pre>
	 * { "status" : "ok" (or "error"), "message": "some explanation" }
	 *         </pre>
	 */
	private String buildJsonResponse(boolean success, String msg) {
		PortalAPIResponse response = new PortalAPIResponse(success, msg);
		String json = null;
		try {
			json = mapper.writeValueAsString(response);
		} catch (JsonProcessingException ex) {
			// Truly should never, ever happen
			logger.error("buildJsonResponse", ex);
			json = "{ \"status\": \"error\",\"message\":\"" + ex.toString() + "\" }";
		}
		return json;
	}

	/**
	 * Builds JSON object with status of error and message containing stack trace
	 * for the specified throwable.
	 * 
	 * @param t
	 *            Throwable with stack trace to use as message
	 * 
	 * @return
	 * 
	 *         <pre>
	 * { "status" : "error", "message": "some-big-stacktrace" }
	 *         </pre>
	 */
	private String buildJsonResponse(Throwable t) {
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		t.printStackTrace(pw);
		return buildJsonResponse(false, sw.toString());
	}
	
	private String buildShortJsonResponse(Throwable t)
	{
		String errorMessage = t.getMessage();
		return buildJsonResponse(false, errorMessage);
	}

	@Override
	public String getUserId(HttpServletRequest request) throws PortalAPIException {
		return portalRestApiServiceImpl.getUserId(request);
	}

	public static IPortalRestAPIService getPortalRestApiServiceImpl() {
		return portalRestApiServiceImpl;
	}

	public static void setPortalRestApiServiceImpl(IPortalRestAPIService portalRestApiServiceImpl) {
		PortalRestAPIProxy.portalRestApiServiceImpl = portalRestApiServiceImpl;
	}
	
	@Override
	public  Map<String, String> getCredentials() throws PortalAPIException {
		return portalRestApiServiceImpl.getCredentials();
	}

	private Set<EcompRole> getEcompRolesOfUser(EcompUser user) throws JsonProcessingException
	{
		
		Set<EcompRole> userEcompRoles = new TreeSet<>();
		Set<EcompRole> ecompRoles = user.getRoles();
		for (EcompRole role : ecompRoles) {
			Set roleFunctions = role.getRoleFunctions();
			Iterator<EcompRoleFunction> roleIter = roleFunctions.iterator();
			ObjectMapper mapper = new ObjectMapper();
			Set<EcompRoleFunction> EcompRoleFunctions = new TreeSet<>();
			while (roleIter.hasNext()) {
				String str = mapper.writeValueAsString(roleIter.next());

				String str1 = str.substring(1, str.length() - 1);
				Map<String, String> result = Arrays.stream(str1.split(",")).map(s -> s.split(":"))
						.collect(Collectors.toMap(a -> a[0], // key
								a -> a[1] // value
				));

				EcompRoleFunction roleFunction = new EcompRoleFunction();
				for (Map.Entry<String, String> set : result.entrySet()) {
					String key = set.getKey().replaceAll("\"", " ").trim();
					if (!key.isEmpty() && key.equalsIgnoreCase("action")) {
						roleFunction.setAction(set.getValue().replaceAll("\"", " ").trim());
					} else if (!key.isEmpty() && key.equalsIgnoreCase("type")) {
						roleFunction.setType(set.getValue().replaceAll("\"", " ").trim());

					} else if (!key.isEmpty() && key.equalsIgnoreCase("code")) {
						roleFunction.setCode(set.getValue().replaceAll("\"", " ").trim());

					} else if (!key.isEmpty() && key.equalsIgnoreCase("name")) {
						roleFunction.setName(set.getValue().replaceAll("\"", " ").trim());
					}
				}
				EcompRoleFunctions.add(roleFunction);
			}
			role.setRoleFunctions(EcompRoleFunctions);
			userEcompRoles.add(role);
		}
		return userEcompRoles;
	}
}