aboutsummaryrefslogtreecommitdiffstats
path: root/ccsdk-app-common/src/main/java/org/onap/ccsdk/dashboard/controller/InventoryController.java
blob: bdbf6adef30b4fbf90f8abf047c35b2e8ee31f80 (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
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
/*******************************************************************************
 * =============LICENSE_START=========================================================
 *
 * =================================================================================
 *  Copyright (c) 2019 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file 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.
 * ============LICENSE_END=========================================================
 *
 *  ECOMP is a trademark and service mark of AT&T Intellectual Property.
 *******************************************************************************/

package org.onap.ccsdk.dashboard.controller;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.onap.ccsdk.dashboard.exceptions.inventory.BlueprintParseException;
import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeAlreadyDeactivatedException;
import org.onap.ccsdk.dashboard.exceptions.inventory.ServiceTypeNotFoundException;
import org.onap.ccsdk.dashboard.model.CloudifyDeployedTenant;
import org.onap.ccsdk.dashboard.model.CloudifyDeployedTenantList;
import org.onap.ccsdk.dashboard.model.CloudifyTenant;
import org.onap.ccsdk.dashboard.model.ECTransportModel;
import org.onap.ccsdk.dashboard.model.RestResponseError;
import org.onap.ccsdk.dashboard.model.RestResponsePage;
import org.onap.ccsdk.dashboard.model.inventory.Blueprint;
import org.onap.ccsdk.dashboard.model.inventory.Service;
import org.onap.ccsdk.dashboard.model.inventory.ServiceQueryParams;
import org.onap.ccsdk.dashboard.model.inventory.ServiceRefList;
import org.onap.ccsdk.dashboard.model.inventory.ServiceType;
import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeQueryParams;
import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeRequest;
import org.onap.ccsdk.dashboard.model.inventory.ServiceTypeServiceMap;
import org.onap.ccsdk.dashboard.rest.CloudifyClient;
import org.onap.ccsdk.dashboard.rest.InventoryClient;
import org.onap.ccsdk.dashboard.util.DashboardProperties;
import org.onap.portalsdk.core.domain.User;
import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
import org.onap.portalsdk.core.util.SystemProperties;
import org.onap.portalsdk.core.web.support.AppUtils;
import org.onap.portalsdk.core.web.support.UserUtils;
import org.slf4j.MDC;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.HttpStatusCodeException;

import com.fasterxml.jackson.core.JsonProcessingException;

/**
 * Controller for Inventory features: services, service types, services groupby.
 * Methods serve Ajax requests made by Angular scripts on pages that show
 * content.
 */
@RestController
@RequestMapping("/inventory")
public class InventoryController extends DashboardRestrictedBaseController {

	private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(InventoryController.class);
	
	/**
	 * Enum for selecting an item type.
	 */
	public enum InventoryDataItem {
		SERVICES, SERVICE_TYPES, SERVICES_GROUPBY;
	}
	
	private static Date begin, end;
	private static final String SERVICES_PATH = "dcae-services";
	private static final String SERVICE_TYPES_PATH = "dcae-service-types";
	private static final String VIEW_SERVICE_TYPE_BLUEPRINT_PATH = "dcae-service-type-blueprint";
	private static final String DEPLOY_ROLE = ".k8.dev";
	private static final String DEP_IDS_FOR_TYPE = "dcae-services/typeIds";

	/**
	 * ATT version with user role auth
	 * Gets one page of objects and supporting information via the REST client.
	 * On success, returns a PaginatedRestResponse object as String.
	 * 
	 * @param option
	 *            Specifies which item list type to get
	 * @param pageNum
	 *            Page number of results
	 * @param pageSize
	 *            Number of items per browser page
	 * @return JSON block as String, see above.
	 * @throws Exception
	 *             On any error; e.g., Network failure.
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private String getItemListForPageAuth(HttpServletRequest request, InventoryDataItem option, int pageNum, int pageSize, String sortBy, String searchBy)
			throws Exception {
		User appUser = UserUtils.getUserSession(request);
		if (appUser == null || appUser.getId() == null )
			throw new Exception("getControllerRestClient: Failed to get application user");
		InventoryClient inventoryClient = getInventoryClient(appUser.getId());

		HttpSession session = AppUtils.getSession(request);
		HashMap<String, Boolean> comp_deploy_tab = (HashMap<String, Boolean>)session.getAttribute("comp_access");
		String roleLevel = (String)session.getAttribute("role_level"); 

		if (roleLevel == null) {
			roleLevel = "app";
		}
		if (comp_deploy_tab == null) {
			comp_deploy_tab = new HashMap<String, Boolean>();
		}

		Set<String> userApps = (Set<String>)session.getAttribute("authComponents");
		if (userApps == null) {
			userApps = new TreeSet<String>();
		}

		List itemList = null;
		List<ServiceType> filterList = new ArrayList<ServiceType>();
		List<Service> authDepList = new ArrayList<Service>();
		switch (option) {
		case SERVICES:
			itemList = inventoryClient.getServices().collect(Collectors.toList());
			if (roleLevel.equals("app")) {
			for(String userRole : userApps) {
				logger.debug(">>>> check component type from deployment: " + userRole);
				for (Service cont: (List<Service>)itemList) {
					String deplRef = cont.getDeploymentRef().toLowerCase();
					logger.debug(">>>> container deployment name: " + deplRef);
					if (deplRef.contains(userRole)) {
						logger.debug(">>>> adding deployment item to filtered subset");
						authDepList.add(cont);
					}
				}
			}
			}

			if (searchBy != null) {		
				if (!roleLevel.equals("app")) {
					itemList = (List) itemList.stream().filter(s -> ((Service) s).contains(searchBy)).collect(Collectors.toList());
				} else {
					if (!authDepList.isEmpty()) {
						authDepList = (List) authDepList.stream().filter(s -> ((Service) s).contains(searchBy)).collect(Collectors.toList());
					}
				}
			}
			if (roleLevel.equals("app")) {
				logger.debug(">>>> update response with authorized content");
				itemList.clear();
				itemList.addAll(authDepList);
			} 
			
			// check for authorization to perform delete deployed blueprints
			
			if (!roleLevel.equals("ops")) {
				for (Service bp: (List<Service>)itemList) {
					String deplRef = bp.getDeploymentRef().split("_")[0].toLowerCase();
					logger.debug(">>>> deployment reference: " + deplRef);
					if (comp_deploy_tab.containsKey(deplRef) ) {
						boolean enableDeploy = comp_deploy_tab.get(deplRef);
						logger.debug(">>>> enable deploy button: " + enableDeploy);
						bp.setCanDeploy(Optional.of(enableDeploy));
					} else {
						bp.setCanDeploy(Optional.of(false));
					}
				}
			} else {
				for (Service bp: (List<Service>)itemList) {
					bp.setCanDeploy(Optional.of(true));
				}
			}

			if (sortBy != null) {
				if (sortBy.equals("deploymentRef")) {
					Collections.sort(itemList, serviceDeploymentRefComparator);
				}
				else if (sortBy.equals("serviceId")) {
					Collections.sort(itemList, serviceIdComparator);
				}
				else if (sortBy.equals("created")) {
					Collections.sort(itemList, serviceCreatedComparator);
				}
				else if (sortBy.equals("modified")) {
					Collections.sort(itemList, serviceModifiedComparator);
				}
			}
			break;
		case SERVICE_TYPES:
			ServiceTypeQueryParams serviceQueryParams = null;
			serviceQueryParams = new ServiceTypeQueryParams.Builder().onlyLatest(false).build();
			itemList = inventoryClient.getServiceTypes(serviceQueryParams).collect(Collectors.toList());
			if (roleLevel.equals("app")) {
			for(String userApp : userApps) {
				logger.debug(">>>> check component type from BP: " + userApp);
				for (ServiceType bp: (List<ServiceType>)itemList) {
					String bpComp = bp.getComponent();
					String bpOwner = bp.getOwner(); // for backward compatibility
					logger.debug(">>>> BP component name: " + bpComp);
					if ( (bpComp != null && bpComp.equalsIgnoreCase(userApp)) || bpOwner.contains(userApp) ) {
						logger.debug(">>>> adding item to filtered subset");
						filterList.add(bp);
					}
				}
			}
			}
			if (searchBy != null) {		
				if (!roleLevel.equals("app")) {
					itemList = (List) itemList.stream().filter(s -> ((ServiceType) s).contains(searchBy)).collect(Collectors.toList());
				} else {
					if (!filterList.isEmpty()) {
						filterList = (List) filterList.stream().filter(s -> ((ServiceType) s).contains(searchBy)).collect(Collectors.toList());
					}
				}
			}
			if (roleLevel.equals("app")) {
				logger.debug(">>>> update response with authorized content");
				itemList.clear();
				itemList.addAll(filterList);
			} 
			
			// check for authorization to perform update/delete/deploy blueprints
			if (!roleLevel.equals("ops")) {
				for (ServiceType bp: (List<ServiceType>)itemList) {
					String bpComp = bp.getComponent();
					if (bpComp != null && bpComp.length() > 0) {
						bpComp = bpComp.toLowerCase();
					} else {
						String bpOwner = bp.getOwner(); // for backward compatibility
						if (bpOwner != null && bpOwner.contains(":")) {
							bpComp = bp.getOwner().split(":")[0].toLowerCase();
						}
					}
					logger.debug(">>>> BP component name: " + bpComp);
					if (comp_deploy_tab.containsKey(bpComp) ) {
						boolean enableDeploy = comp_deploy_tab.get(bpComp);
						logger.debug(">>>> enable deploy button: " + enableDeploy);
						bp.setCanDeploy(Optional.of(enableDeploy));
					} else {
						bp.setCanDeploy(Optional.of(false));
					}
				}
			} else {
				for (ServiceType bp: (List<ServiceType>)itemList) {
					bp.setCanDeploy(Optional.of(true));
				}
			}
			
			if (sortBy != null) {
				if (sortBy.equals("owner")) {
					Collections.sort(itemList, serviceTypeOwnerComparator);
				}
				else if (sortBy.equals("typeId")) {
					Collections.sort(itemList, serviceTypeIdComparator);
				}
				else if (sortBy.equals("typeName")) {
					Collections.sort(itemList, serviceTypeNameComparator);
				}
				else if (sortBy.equals("typeVersion")) {
					Collections.sort(itemList, serviceTypeVersionComparator);
				}
				else if (sortBy.equals("created")) {
					Collections.sort(itemList, serviceTypeCreatedComparator);
				}
				else if (sortBy.equals("application")) {
					Collections.sort(itemList, serviceTypeApplComparator);
				}
				else if (sortBy.equals("component")) {
					Collections.sort(itemList, serviceTypeCompComparator);
				}
			}
			break;
		default:
			MDC.put(SystemProperties.STATUS_CODE, "ERROR");
			MDC.put("TargetEntity", "DCAE Inventory");
			MDC.put("TargetServiceName", "DCAE Inventory");
			MDC.put("ErrorCode", "300");
			MDC.put("ErrorCategory", "ERROR");
			MDC.put("ErrorDescription", "Getting page of items failed!");
			throw new Exception("getItemListForPage failed: unimplemented case: " + option.name());
		}
		
		// Shrink if needed
		final int totalItems = itemList.size();
		final int pageCount = (int) Math.ceil((double) totalItems / pageSize);
		if (totalItems > pageSize)
			itemList = getPageOfList(pageNum, pageSize, itemList);
		
		RestResponsePage<List> model = new RestResponsePage<>(totalItems, pageCount, itemList);
		String outboundJson = objectMapper.writeValueAsString(model);
		return outboundJson;
	}
	/**
	 * Gets one page of objects and supporting information via the REST client.
	 * On success, returns a PaginatedRestResponse object as String.
	 * 
	 * @param option
	 *            Specifies which item list type to get
	 * @param pageNum
	 *            Page number of results
	 * @param pageSize
	 *            Number of items per browser page
	 * @return JSON block as String, see above.
	 * @throws Exception
	 *             On any error; e.g., Network failure.
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private String getItemListForPage(HttpServletRequest request, InventoryDataItem option, int pageNum, int pageSize, String sortBy, String searchBy)
			throws Exception {
		User appUser = UserUtils.getUserSession(request);
		if (appUser == null || appUser.getId() == null )
			throw new Exception("getControllerRestClient: Failed to get application user");
		InventoryClient inventoryClient = getInventoryClient(appUser.getId());

		List itemList = null;
		switch (option) {
		case SERVICES:
			itemList = inventoryClient.getServices().collect(Collectors.toList());
			// Get the tenant names for all the deployments from Cloudify/API handler		
			ECTransportModel result = null;
			List<CloudifyDeployedTenant> tenantList = new ArrayList<CloudifyDeployedTenant>();
			try {
				CloudifyClient restClient = getCloudifyRestClient(request);
				List<CloudifyTenant> cldfyTen = restClient.getTenants().items;			
				for (CloudifyTenant ct: (List<CloudifyTenant>)cldfyTen) {
					result = restClient.getTenantInfoFromDeploy(ct.name);
					tenantList.addAll(((CloudifyDeployedTenantList)result).items);
				}
			} catch (HttpStatusCodeException e) {
				MDC.put(SystemProperties.STATUS_CODE, "ERROR");
				MDC.put("TargetEntity", "Cloudify Manager");
				MDC.put("TargetServiceName", "Cloudify Manager");
				MDC.put("ErrorCode", "300");
				MDC.put("ErrorCategory", "ERROR");
				MDC.put("ErrorDescription", "Getting deployments failed!");
				logger.error(EELFLoggerDelegate.errorLogger, "getTenantInfoFromDeploy caught exception");
				result = new RestResponseError(e.getResponseBodyAsString());
			} catch (Throwable t) {
				MDC.put(SystemProperties.STATUS_CODE, "ERROR");
				MDC.put("TargetEntity", "Cloudify Manager");
				MDC.put("TargetServiceName", "Cloudify Manager");
				MDC.put("ErrorCode", "300");
				MDC.put("ErrorCategory", "ERROR");
				MDC.put("ErrorDescription", "Getting deployments failed!");
				logger.error(EELFLoggerDelegate.errorLogger, "getDeploymentById caught exception");
				result = new RestResponseError("getTenantInfoFromDeploy failed", t);
			} finally {
				postLogAudit(request);
			}
			for (Service depl: (List<Service>)itemList) {
				for (CloudifyDeployedTenant deplTen: tenantList) {
					if (depl.getDeploymentRef().equals(deplTen.id)) {
						depl.setTenant(deplTen.tenant_name);
						break;
					}
				}
			}
			if (searchBy != null) {
				itemList = (List) itemList.stream().filter(s -> ((Service) s).contains(searchBy)).collect(Collectors.toList());
			}
			for (Service bp: (List<Service>)itemList) {
				bp.setCanDeploy(Optional.of(true));
			}
			if (sortBy != null) {
				if (sortBy.equals("deploymentRef")) {
					Collections.sort(itemList, serviceDeploymentRefComparator);
				}
				else if (sortBy.equals("serviceId")) {
					Collections.sort(itemList, serviceIdComparator);
				}
				else if (sortBy.equals("created")) {
					Collections.sort(itemList, serviceCreatedComparator);
				}
				else if (sortBy.equals("modified")) {
					Collections.sort(itemList, serviceModifiedComparator);
				}
			}
			break;
		case SERVICE_TYPES:
			itemList = inventoryClient.getServiceTypes().collect(Collectors.toList());
			if (searchBy != null) {
				itemList = (List) itemList.stream().filter(s -> ((ServiceType) s).contains(searchBy)).collect(Collectors.toList());
			}
			for (ServiceType bp: (List<ServiceType>)itemList) {
				bp.setCanDeploy(Optional.of(true));
			}
			if (sortBy != null) {
				if (sortBy.equals("owner")) {
					Collections.sort(itemList, serviceTypeOwnerComparator);
				}
				else if (sortBy.equals("typeId")) {
					Collections.sort(itemList, serviceTypeIdComparator);
				}
				else if (sortBy.equals("typeName")) {
					Collections.sort(itemList, serviceTypeNameComparator);
				}
				else if (sortBy.equals("typeVersion")) {
					Collections.sort(itemList, serviceTypeVersionComparator);
				}
				else if (sortBy.equals("created")) {
					Collections.sort(itemList, serviceTypeCreatedComparator);
				}
				else if (sortBy.equals("application")) {
					Collections.sort(itemList, serviceTypeApplComparator);
				}
				else if (sortBy.equals("component")) {
					Collections.sort(itemList, serviceTypeCompComparator);
				}
			}
			break;
		default:
			MDC.put(SystemProperties.STATUS_CODE, "ERROR");
			MDC.put("TargetEntity", "DCAE Inventory");
			MDC.put("TargetServiceName", "DCAE Inventory");
			MDC.put("ErrorCode", "300");
			MDC.put("ErrorCategory", "ERROR");
			MDC.put("ErrorDescription", "Getting page of items failed!");
			throw new Exception("getItemListForPage failed: unimplemented case: " + option.name());
		}
		
		// Shrink if needed
		final int totalItems = itemList.size();
		final int pageCount = (int) Math.ceil((double) totalItems / pageSize);
		if (totalItems > pageSize)
			itemList = getPageOfList(pageNum, pageSize, itemList);
		
		RestResponsePage<List> model = new RestResponsePage<>(totalItems, pageCount, itemList);
		String outboundJson = objectMapper.writeValueAsString(model);
		return outboundJson;
	}
	
	/**
	 * Gets one page of the specified items. This method traps exceptions and
	 * constructs an appropriate JSON block to report errors.
	 * 
	 * @param request
	 *            Inbound request
	 * @param option
	 *            Item type to get
	 * @return JSON with one page of objects; or an error.
	 */
	protected String getItemListForPageWrapper(HttpServletRequest request, InventoryDataItem option, String sortBy, String searchBy) {
		preLogAudit(request);
		String outboundJson = null;
		try {
			int pageNum = getRequestPageNumber(request);
			int pageSize = getRequestPageSize(request);
			String appEnv = "os";
			appEnv = getAppProperties().getPropertyDef(DashboardProperties.CONTROLLER_TYPE, "att");
			if (appEnv.equals("os")) {
				outboundJson = getItemListForPage(request, option, pageNum, pageSize, sortBy, searchBy);
			} else {
				outboundJson = getItemListForPageAuth(request, option, pageNum, pageSize, sortBy, searchBy);
			}
		} catch (Exception ex) {
			MDC.put(SystemProperties.STATUS_CODE, "ERROR");
			MDC.put("TargetEntity", "DCAE Inventory");
			MDC.put("TargetServiceName", "DCAE Inventory");
			MDC.put("ErrorCode", "300");
			MDC.put("ErrorCategory", "ERROR");
			MDC.put("ErrorDescription", "Getting page of items failed!");
			logger.error(EELFLoggerDelegate.errorLogger, "getItemListForPageWrapper caught exception");
			RestResponseError result = null;
			if (ex instanceof HttpStatusCodeException)
				result = new RestResponseError(((HttpStatusCodeException) ex).getResponseBodyAsString());
			else
				result = new RestResponseError("Failed to get " + option.name(), ex);
			try {
				outboundJson = objectMapper.writeValueAsString(result);
			} catch (JsonProcessingException jpe) {
				// Should never, ever happen
				outboundJson = "{ \"error\" : \"" + jpe.toString() + "\"}";
			}
		} finally {
			postLogAudit(request);
		}
		return outboundJson;
	}
	
	/**
	 * Supports sorting service types by owner
	 */
	private static Comparator<ServiceType> serviceTypeOwnerComparator = new Comparator<ServiceType>() {
		@Override
		public int compare(ServiceType o1, ServiceType o2) {
			return o1.getOwner().compareToIgnoreCase(o2.getOwner());
		}
	};

	/**
	 * Supports sorting service types by application
	 */
	private static Comparator<ServiceType> serviceTypeApplComparator = new Comparator<ServiceType>() {
		@Override
		public int compare(ServiceType o1, ServiceType o2) {
			return o1.getApplication().compareToIgnoreCase(o2.getApplication());
		}
	};
	
	/**
	 * Supports sorting service types by component
	 */
	private static Comparator<ServiceType> serviceTypeCompComparator = new Comparator<ServiceType>() {
		@Override
		public int compare(ServiceType o1, ServiceType o2) {
			return o1.getComponent().compareToIgnoreCase(o2.getComponent());
		}
	};
	
	/**
	 * Supports sorting service types by type id
	 */
	private static Comparator<ServiceType> serviceTypeIdComparator = new Comparator<ServiceType>() {
		@Override
		public int compare(ServiceType o1, ServiceType o2) {
			return o1.getTypeId().get().compareToIgnoreCase(o2.getTypeId().get());
		}
	};
	
	/**
	 * Supports sorting service types by type name
	 */
	private static Comparator<ServiceType> serviceTypeNameComparator = new Comparator<ServiceType>() {
		@Override
		public int compare(ServiceType o1, ServiceType o2) {
			return o1.getTypeName().compareToIgnoreCase(o2.getTypeName());
		}
	};
	
	/**
	 * Supports sorting service types by type version
	 */
	private static Comparator<ServiceType> serviceTypeVersionComparator = new Comparator<ServiceType>() {
		@Override
		public int compare(ServiceType o1, ServiceType o2) {
			return o1.getTypeVersion().compareTo(o2.getTypeVersion());
		}
	};
	
	/**
	 * Supports sorting service types by created date
	 */
	private static Comparator<ServiceType> serviceTypeCreatedComparator = new Comparator<ServiceType>() {
		@Override
		public int compare(ServiceType o1, ServiceType o2) {
			return o1.getCreated().get().compareToIgnoreCase(o2.getCreated().get());
		}
	};
	
	/**
	 * Supports sorting services by deploymentRef
	 */
	private static Comparator<Service> serviceDeploymentRefComparator = new Comparator<Service>() {
		@Override
		public int compare(Service o1, Service o2) {
			return o1.getDeploymentRef().compareToIgnoreCase(o2.getDeploymentRef());
		}
	};
	
	/**
	 * Supports sorting services by service id
	 */
	private static Comparator<Service> serviceIdComparator = new Comparator<Service>() {
		@Override
		public int compare(Service o1, Service o2) {
			return o1.getServiceId().compareToIgnoreCase(o2.getServiceId());
		}
	};
	
	/**
	 * Supports sorting services by created date
	 */
	private static Comparator<Service> serviceCreatedComparator = new Comparator<Service>() {
		@Override
		public int compare(Service o1, Service o2) {
			return o1.getCreated().compareToIgnoreCase(o2.getCreated());
		}
	};

	/**
	 * Supports sorting services by created date
	 */
	private static Comparator<Service> serviceModifiedComparator = new Comparator<Service>() {
		@Override
		public int compare(Service o1, Service o2) {
			return o1.getModified().compareToIgnoreCase(o2.getModified());
		}
	};
	
	/**
	 * Serves one page of service types
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @return List of ServiceTypes objects
	 */
	@RequestMapping(value = { SERVICE_TYPES_PATH }, method = RequestMethod.GET, produces = "application/json")
	@ResponseBody
	public String getServiceTypesByPage(HttpServletRequest request) {
		preLogAudit(request);
		String json = null;
		//json = getMockDataContent("/serviceTypesList.json");	
		json = 
				getItemListForPageWrapper(request, InventoryDataItem.SERVICE_TYPES, request.getParameter("sortBy"), request.getParameter("searchBy"));
		postLogAudit(request);
		return json;
	}
	

	private String getMockDataContent(final String path) {
		String result = null;
		try {
			InputStream is = getClass().getResourceAsStream(path);
			if (is == null)
				throw new Exception("Failed to find resource at path " + path);
			Scanner scanner = new Scanner(is, "UTF-8");
			result = scanner.useDelimiter("\\A").next();
			scanner.close();
			is.close();
		} catch (Exception ex) {
			logger.error("getMockDataContent failed", ex);
			throw new RuntimeException(ex);
		}
		return result;
	}

	/**
	 * Query Service objects matching a service type ID
	 * 
	 */
	@RequestMapping(value = { DEP_IDS_FOR_TYPE }, method = RequestMethod.POST, produces = "application/json")
	public String getServicesForType( HttpServletRequest request, 
			@RequestBody String[] typeList)
			throws Exception {
		preLogAudit(request);
		User appUser = UserUtils.getUserSession(request);
		if (appUser == null || appUser.getId() == null )
			throw new Exception("getControllerRestClient: Failed to get application user");
		InventoryClient inventoryClient = getInventoryClient(appUser.getId());
		List<ServiceTypeServiceMap> result = new ArrayList<ServiceTypeServiceMap>();
		for (String typeId: typeList) {
			ServiceQueryParams qryParams = new ServiceQueryParams.Builder().typeId(typeId).build();
			ServiceRefList srvcRefs = inventoryClient.getServicesForType(qryParams);
			ServiceTypeServiceMap srvcMap = new ServiceTypeServiceMap(typeId, srvcRefs);
			result.add(srvcMap);
		}
		return objectMapper.writeValueAsString(result);
	}
	
	/**
	 * Serves one page of services
	 *
	 * @param request
	 * 			HttpServletRequest
	 *
	 * @return List of Service objects
	 */
	@RequestMapping(value = { SERVICES_PATH }, method = RequestMethod.GET, produces = "application/json")
	@ResponseBody
	public String getServicesByPage(HttpServletRequest request) {
		//preLogAudit(request);
		String json = null;
		json = getItemListForPageWrapper(request, InventoryDataItem.SERVICES, request.getParameter("sortBy"), request.getParameter("searchBy"));
		postLogAudit(request);
		return json;
	}
	/**
	 * Gets the specified blueprint content for viewing.
	 * 
	 * @param id
	 *            Blueprint ID
	 * @param request
	 *            HttpServletRequest
	 * @return Blueprint as YAML; or error.
	 * @throws Exception
	 *             on serialization error
	 * 
	 */
	@RequestMapping(value = {
			VIEW_SERVICE_TYPE_BLUEPRINT_PATH + "/{typeid}" }, method = RequestMethod.GET, produces = "application/yaml")
	@ResponseBody
	public String viewServiceTypeBlueprintContentById(@PathVariable("typeid") String typeId, HttpServletRequest request) throws Exception {
		preLogAudit(request);
		String json = null;
		try {
			InventoryClient inventoryClient = getInventoryClient(request);
			json = objectMapper.writeValueAsString(inventoryClient.getServiceType(typeId).get());
		} catch (HttpStatusCodeException e) {
			MDC.put(SystemProperties.STATUS_CODE, "ERROR");
			MDC.put("TargetEntity", "DCAE Inventory");
			MDC.put("TargetServiceName", "DCAE Inventory");
			MDC.put("ErrorCode", "300");
			MDC.put("ErrorCategory", "ERROR");
			MDC.put("ErrorDescription", "Viewing service type " + typeId + " failed!");
			logger.error(EELFLoggerDelegate.errorLogger, "viewServiceTypeBlueprintContentById caught exception");
			json = objectMapper.writeValueAsString(new RestResponseError(e.getResponseBodyAsString()));
		} catch (JsonProcessingException jpe) {
			// Should never, ever happen
			MDC.put(SystemProperties.STATUS_CODE, "ERROR");
			MDC.put("TargetEntity", "DCAE Inventory");
			MDC.put("TargetServiceName", "DCAE Inventory");
			MDC.put("ErrorCode", "300");
			MDC.put("ErrorCategory", "ERROR");
			MDC.put("ErrorDescription", "Viewing service type " + typeId + " failed!");
			logger.error(EELFLoggerDelegate.errorLogger, "viewServiceTypeBlueprintContentById caught exception");
			json = "{ \"error\" : \"" + jpe.toString() + "\"}";
		} catch (Throwable t) {
			MDC.put(SystemProperties.STATUS_CODE, "ERROR");
			MDC.put("TargetEntity", "DCAE Inventory");
			MDC.put("TargetServiceName", "DCAE Inventory");
			MDC.put("ErrorCode", "300");
			MDC.put("ErrorCategory", "ERROR");
			MDC.put("ErrorDescription", "Viewing service type " + typeId + " failed!");
			logger.error(EELFLoggerDelegate.errorLogger, "viewServiceTypeBlueprintContentById caught exception");
			json = objectMapper.writeValueAsString(new RestResponseError("getBlueprintContentById failed", t));
		} finally {
			postLogAudit(request);
		}
		return json;
	}

	/**
	 * Deletes the specified blueprint.
	 *
	 * @param id
	 *            Blueprint ID
	 * @param request
	 *            HttpServletRequest
	 * @param response
	 *            HttpServletResponse
	 * @return status code on success; error on failure.
	 * @throws Exception
	 *             On serialization failure
	 */
	@RequestMapping(value = { SERVICE_TYPES_PATH + "/{typeid}" }, method = RequestMethod.DELETE, produces = "application/json")
	@ResponseBody
	public String deleteServiceType(@PathVariable("typeid") String typeid, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		preLogAudit(request);
		String json = "{\"202\": \"OK\"}";
		try {
			InventoryClient inventoryClient = getInventoryClient(request);
			inventoryClient.deleteServiceType(typeid);
		} catch (ServiceTypeNotFoundException e) {
			MDC.put(SystemProperties.STATUS_CODE, "ERROR");
			MDC.put("TargetEntity", "DCAE Inventory");
			MDC.put("TargetServiceName", "DCAE Inventory");
			MDC.put("ErrorCode", "300");
			MDC.put("ErrorCategory", "ERROR");
			MDC.put("ErrorDescription", "Deleting service type " + typeid + " failed!");
			logger.error(EELFLoggerDelegate.errorLogger, "deleteServiceType caught exception");
			json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage()));
		} catch (ServiceTypeAlreadyDeactivatedException e) {
			MDC.put(SystemProperties.STATUS_CODE, "ERROR");
			MDC.put("TargetEntity", "DCAE Inventory");
			MDC.put("TargetServiceName", "DCAE Inventory");
			MDC.put("ErrorCode", "300");
			MDC.put("ErrorCategory", "ERROR");
			MDC.put("ErrorDescription", "Deleting service type " + typeid + " failed!");
			logger.error(EELFLoggerDelegate.errorLogger, "deleteServiceType caught exception");
			json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage()));
		} catch (Throwable t) {
			MDC.put(SystemProperties.STATUS_CODE, "ERROR");
			MDC.put("TargetEntity", "DCAE Inventory");
			MDC.put("TargetServiceName", "DCAE Inventory");
			MDC.put("ErrorCode", "300");
			MDC.put("ErrorCategory", "ERROR");
			MDC.put("ErrorDescription", "Deleting service type " + typeid + " failed!");
			logger.error(EELFLoggerDelegate.errorLogger, "deleteServiceType caught exception");
			json = objectMapper.writeValueAsString(new RestResponseError("deleteDeployment failed", t));
		} finally {
			postLogAudit(request);
		}
		return json;
	}

	/**
	 * Deletes the specified service i.e. deployment from inventory
	 *
	 * @param id
	 *            Service ID
	 * @param request
	 *            HttpServletRequest
	 * @param response
	 *            HttpServletResponse
	 * @return status code on success; error on failure.
	 * @throws Exception
	 *             On serialization failure
	 */
	@RequestMapping(value = { SERVICES_PATH + "/{serviceId}" }, method = RequestMethod.DELETE, produces = "application/json")
	@ResponseBody
	public String deleteService(@PathVariable("serviceId") String serviceId, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		preLogAudit(request);
		String json = "{\"202\": \"OK\"}";
		try {
			InventoryClient inventoryClient = getInventoryClient(request);
			inventoryClient.deleteService(serviceId);
		} catch (ServiceTypeNotFoundException e) {
			MDC.put(SystemProperties.STATUS_CODE, "ERROR");
			MDC.put("TargetEntity", "DCAE Inventory");
			MDC.put("TargetServiceName", "DCAE Inventory");
			MDC.put("ErrorCode", "300");
			MDC.put("ErrorCategory", "ERROR");
			MDC.put("ErrorDescription", "Deleting service " + serviceId + " failed!");
			logger.error(EELFLoggerDelegate.errorLogger, "deleteServiceType caught exception");
			json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage()));
		} catch (ServiceTypeAlreadyDeactivatedException e) {
			MDC.put(SystemProperties.STATUS_CODE, "ERROR");
			MDC.put("TargetEntity", "DCAE Inventory");
			MDC.put("TargetServiceName", "DCAE Inventory");
			MDC.put("ErrorCode", "300");
			MDC.put("ErrorCategory", "ERROR");
			MDC.put("ErrorDescription", "Deleting service " + serviceId + " failed!");
			logger.error(EELFLoggerDelegate.errorLogger, "deleteServiceType caught exception");
			json = objectMapper.writeValueAsString(new RestResponseError(e.getMessage()));
		} catch (Throwable t) {
			MDC.put(SystemProperties.STATUS_CODE, "ERROR");
			MDC.put("TargetEntity", "DCAE Inventory");
			MDC.put("TargetServiceName", "DCAE Inventory");
			MDC.put("ErrorCode", "300");
			MDC.put("ErrorCategory", "ERROR");
			MDC.put("ErrorDescription", "Deleting service " + serviceId + " failed!");
			logger.error(EELFLoggerDelegate.errorLogger, "deleteServiceType caught exception");
			json = objectMapper.writeValueAsString(new RestResponseError("deleteDeployment failed", t));
		} finally {
			postLogAudit(request);
		}
		return json;
	}

	/**
	 * Processes request to update a blueprint currently existing in DCAE Inventory.
	 *
	 * @param request
	 *            HttpServletRequest
	 * @param blueprint
	 *            Cloudify blueprint
	 * @return Blueprint as uploaded; or error.
	 * @throws Exception
	 *             on serialization error
	 */
	@RequestMapping(value = { SERVICE_TYPES_PATH + "/update"}, method = RequestMethod.POST, produces = "application/json")
	@ResponseBody
	public String updateServiceTypeBlueprint(HttpServletRequest request, @RequestBody ServiceType serviceType)
			throws Exception {
		preLogAudit(request);
		String json = "{\"201\": \"OK\"}";
		try {
			// Verify that the Service Type can be parsed for inputs.
			Blueprint.parse(serviceType.getBlueprintTemplate());
			InventoryClient inventoryClient = getInventoryClient(request);
			inventoryClient.addServiceType(serviceType);
		} catch (BlueprintParseException e) {
			MDC.put(SystemProperties.STATUS_CODE, "ERROR");
			MDC.put("TargetEntity", "DCAE Inventory");
			MDC.put("TargetServiceName", "DCAE Inventory");
			MDC.put("ErrorCode", "300");
			MDC.put("ErrorCategory", "ERROR");
			MDC.put("ErrorDescription", "Updating service type failed!");
			logger.error(EELFLoggerDelegate.errorLogger, "updateServiceTypeBlueprint caught exception");
			json = objectMapper.writeValueAsString(new RestResponseError("Invalid blueprint format.", e));
		} catch (HttpStatusCodeException e) {
			MDC.put(SystemProperties.STATUS_CODE, "ERROR");
			MDC.put("TargetEntity", "DCAE Inventory");
			MDC.put("TargetServiceName", "DCAE Inventory");
			MDC.put("ErrorCode", "300");
			MDC.put("ErrorCategory", "ERROR");
			MDC.put("ErrorDescription", "Updating service type failed!");
			logger.error(EELFLoggerDelegate.errorLogger, "updateServiceTypeBlueprint caught exception");
			json = objectMapper.writeValueAsString(new RestResponseError(e.getResponseBodyAsString()));
		} catch (Throwable t) {
			MDC.put(SystemProperties.STATUS_CODE, "ERROR");
			MDC.put("TargetEntity", "DCAE Inventory");
			MDC.put("TargetServiceName", "DCAE Inventory");
			MDC.put("ErrorCode", "300");
			MDC.put("ErrorCategory", "ERROR");
			MDC.put("ErrorDescription", "Updating service type failed!");
			logger.error(EELFLoggerDelegate.errorLogger, "updateServiceTypeBlueprint caught exception");
			json = objectMapper.writeValueAsString(new RestResponseError("updateServiceTypeBlueprint failed", t));
		} finally {
			postLogAudit(request);
		}
		return json;
	}
	
	/**
	 * Processes request to update a blueprint currently existing in DCAE Inventory.
	 *
	 * @param request
	 *            HttpServletRequest
	 * @param blueprint
	 *            Cloudify blueprint
	 * @return Blueprint as uploaded; or error.
	 * @throws Exception
	 *             on serialization error
	 */
	@RequestMapping(value = { SERVICE_TYPES_PATH + "/upload" }, method = RequestMethod.POST, produces = "application/json")
	@ResponseBody
	public String uploadServiceTypeBlueprint(HttpServletRequest request, 
			@RequestBody ServiceTypeRequest serviceTypeRequest)
			throws Exception {
		preLogAudit(request);
		String json = "{\"201\": \"OK\"}";
		try {
			Blueprint.parse(serviceTypeRequest.getBlueprintTemplate());
			InventoryClient inventoryClient = getInventoryClient(request);
			inventoryClient.addServiceType(serviceTypeRequest);
		} catch (BlueprintParseException e) {
			MDC.put(SystemProperties.STATUS_CODE, "ERROR");
			MDC.put("TargetEntity", "DCAE Inventory");
			MDC.put("TargetServiceName", "DCAE Inventory");
			MDC.put("ErrorCode", "300");
			MDC.put("ErrorCategory", "ERROR");
			MDC.put("ErrorDescription", "Updating service type failed!");
			logger.error(EELFLoggerDelegate.errorLogger, "updateServiceTypeBlueprint caught exception");
			json = objectMapper.writeValueAsString(new RestResponseError("Invalid blueprint format.", e));
		} catch (HttpStatusCodeException e) {
			MDC.put(SystemProperties.STATUS_CODE, "ERROR");
			MDC.put("TargetEntity", "DCAE Inventory");
			MDC.put("TargetServiceName", "DCAE Inventory");
			MDC.put("ErrorCode", "300");
			MDC.put("ErrorCategory", "ERROR");
			MDC.put("ErrorDescription", "Updating service type failed!");
			logger.error(EELFLoggerDelegate.errorLogger, "updateServiceTypeBlueprint caught exception");
			json = objectMapper.writeValueAsString(new RestResponseError(e.getResponseBodyAsString()));
		} catch (Throwable t) {
			MDC.put(SystemProperties.STATUS_CODE, "ERROR");
			MDC.put("TargetEntity", "DCAE Inventory");
			MDC.put("TargetServiceName", "DCAE Inventory");
			MDC.put("ErrorCode", "300");
			MDC.put("ErrorCategory", "ERROR");
			MDC.put("ErrorDescription", "Updating service type failed!");
			logger.error(EELFLoggerDelegate.errorLogger, "updateServiceTypeBlueprint caught exception");
			json = objectMapper.writeValueAsString(new RestResponseError("updateServiceTypeBlueprint failed", t));
		} finally {
			postLogAudit(request);
		}
		return json;
	}

	public void preLogAudit(HttpServletRequest request) {
		begin = new Date();
		MDC.put(SystemProperties.AUDITLOG_BEGIN_TIMESTAMP, logDateFormat.format(begin));
		MDC.put(SystemProperties.METRICSLOG_BEGIN_TIMESTAMP, logDateFormat.format(begin));
		MDC.put(SystemProperties.STATUS_CODE, "COMPLETE");
		//logger.setRequestBasedDefaultsIntoGlobalLoggingContext(request, APP_NAME);
	}

	public void postLogAudit(HttpServletRequest request) {
		end = new Date();
		MDC.put("AlertSeverity", "0");
		MDC.put("TargetEntity", "DCAE Inventory");
		MDC.put("TargetServiceName", "DCAE Inventory");
		MDC.put(SystemProperties.AUDITLOG_END_TIMESTAMP, logDateFormat.format(end));
		MDC.put(SystemProperties.METRICSLOG_END_TIMESTAMP, logDateFormat.format(end));
		MDC.put(SystemProperties.MDC_TIMER, Long.toString((end.getTime() - begin.getTime())));
		logger.info(EELFLoggerDelegate.auditLogger, request.getMethod() + request.getRequestURI());
		logger.info(EELFLoggerDelegate.metricsLogger, request.getMethod() + request.getRequestURI());
	}
}