summaryrefslogtreecommitdiffstats
path: root/dcaedt_catalog/asdc/src/main/java/org/onap/sdc/dcae/catalog/asdc/ASDC.java
blob: 08383eaabbf853709f44c76323dd6e0869e97806 (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
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
package org.onap.sdc.dcae.catalog.asdc;

import java.net.URI;
import java.net.URISyntaxException;

import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;

import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.Collections;

import java.util.function.UnaryOperator;

import javax.annotation.PostConstruct;

import org.onap.sdc.common.onaplog.OnapLoggerDebug;
import org.onap.sdc.common.onaplog.OnapLoggerError;
import org.onap.sdc.common.onaplog.Enums.LogLevel;
import org.onap.sdc.dcae.enums.ArtifactGroupType;
import org.onap.sdc.dcae.enums.ArtifactType;
import org.onap.sdc.dcae.composition.restmodels.sdc.ResourceDetailed;
import org.springframework.http.MediaType;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpEntity;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.AsyncClientHttpRequestExecution;
import org.springframework.http.client.AsyncClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.AsyncRestTemplate;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.http.converter.HttpMessageConverter;

import org.springframework.util.Base64Utils;
import org.apache.commons.codec.digest.DigestUtils;

import org.springframework.stereotype.Component;
import org.springframework.context.annotation.Scope;
import org.springframework.scheduling.annotation.Scheduled;

import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

import org.json.JSONObject;
import org.onap.sdc.dcae.catalog.commons.Action;
import org.onap.sdc.dcae.catalog.commons.Future;
import org.onap.sdc.dcae.catalog.commons.Futures;
import org.onap.sdc.dcae.catalog.commons.JSONHttpMessageConverter;
import org.json.JSONArray;

import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

@Component("asdc")
@Scope("singleton")
public class ASDC {

	private static final String TARGET = "target";
	private static final String ACTION = "action";
	private static final String ASSET_TYPE = "assetType";
	private static final String USER_ID = "USER_ID";
	public static final String ASSET_ID = "assetId";
	public static final String ARTIFACT_ID = "artifactId";
	public static final String LIST_FILTER = "listFilter";

	public enum AssetType {
		resource,
		service,
		product
	}

	public enum LifecycleState {
		Checkin,
		Checkout,
		Certify,
		undocheckout
	}


	protected static OnapLoggerError errLogger = OnapLoggerError.getInstance();
	protected static OnapLoggerDebug debugLogger = OnapLoggerDebug.getInstance();

	private static final String ARTIFACT_TYPE = "artifactType";
	private static final String ARTIFACT_GROUP_TYPE = "artifactGroupType";
	private static final String ARTIFACT_LABEL = "artifactLabel";
	private static final String ARTIFACT_NAME = "artifactName";
	private static final String DESCRIPTION = "description";
	private static final String PAYLOAD_DATA = "payloadData";

	private static final String[] artifactMandatoryEntries = new String[] {};

	private static final String[] updateMandatoryEntries = new String[] {ARTIFACT_NAME,
			ARTIFACT_TYPE, ARTIFACT_GROUP_TYPE, ARTIFACT_LABEL, DESCRIPTION, PAYLOAD_DATA};

	private static final String[] uploadMandatoryEntries = new String[] {ARTIFACT_NAME,
			ARTIFACT_TYPE, ARTIFACT_GROUP_TYPE, ARTIFACT_LABEL, DESCRIPTION, PAYLOAD_DATA};

	private URI rootUri;
	private String rootPath = "/sdc/v1/catalog/";
	private String user, passwd;
	private String instanceId;

	public void setUri(URI theUri) {
		String userInfo = theUri.getUserInfo();
		if (userInfo != null) {
			String[] userInfoParts = userInfo.split(":");
			setUser(userInfoParts[0]);
			if (userInfoParts.length > 1) {
				setPassword(userInfoParts[1]);
			}
		}
		String fragment = theUri.getFragment();
		if (fragment == null) {
			throw new IllegalArgumentException("The URI must contain a fragment specification, to be used as ASDC instance id");
		}
		setInstanceId(fragment);

		try {
			this.rootUri = new URI(theUri.getScheme(), null, theUri.getHost(), theUri.getPort(), theUri.getPath(), theUri.getQuery(), null);
		}
		catch (URISyntaxException urix) {
			throw new IllegalArgumentException("Invalid uri", urix);
		}
 	}

	public URI getUri() {
		return this.rootUri;	
	}

	public void setUser(String theUser) {
		this.user = theUser;
	}

	public String getUser() {
		return this.user;
	}

	public void setPassword(String thePassword) {
		this.passwd = thePassword;
	}

	public String getPassword() {
		return this.passwd;
	}

	public void setInstanceId(String theId) {
		this.instanceId = theId;
	}

    @Scheduled(fixedRateString = "${beans.context.scripts.updateCheckFrequency?:60000}")
	public void checkForUpdates() {
		// ffu
	}

	@PostConstruct
	public void initASDC() {
		// ffu
	}

	public <T> Future<T> getResources(Class<T> theType) {
		return getAssets(AssetType.resource, theType);
	}
	
	public Future<JSONArray> getResources() {
		return getAssets(AssetType.resource, JSONArray.class);
	}
	
	public <T> Future<T> getResources(Class<T> theType, String theCategory, String theSubCategory) {
		return getAssets(AssetType.resource, theType, theCategory, theSubCategory);
	}
	
	public Future<JSONArray> getResources(String category, String subCategory, String resourceType) {
		return getAssets(AssetType.resource, JSONArray.class, category, subCategory, resourceType);
	}

	public <T> Future<T> getServices(Class<T> theType) {
		return getAssets(AssetType.service, theType);
	}
	
	public Future<JSONArray> getServices() {
		return getAssets(AssetType.service, JSONArray.class);
	}
	
	public <T> Future<T> getServices(Class<T> theType, String theCategory, String theSubCategory) {
		return getAssets(AssetType.service, theType, theCategory, theSubCategory);
	}
	
	public Future<JSONArray> getServices(String theCategory, String theSubCategory) {
		return getAssets(AssetType.service, JSONArray.class, theCategory, theSubCategory);
	}

	public <T> Future<T> getAssets(AssetType theAssetType, Class<T> theType) {
		return fetch(refAssets(theAssetType), theType);
	}
	
	public <T> Action<T> getAssetsAction(AssetType theAssetType, Class<T> theType) {
		return () -> fetch(refAssets(theAssetType), theType);
	}
	
	public <T> Future<T> getAssets(AssetType theAssetType, Class<T> theType,
																 String theCategory, String theSubCategory) {
		return getAssets(theAssetType, theType, theCategory, theSubCategory, null);
	}

	public <T> Future<T> getAssets(AssetType theAssetType, Class<T> theType,
																 String theCategory, String theSubCategory, String theResourceType) {
		return fetch(refAssets(theAssetType) + filter(theCategory, theSubCategory, theResourceType), theType);
	}
	
	public <T> Action<T> getAssetsAction(AssetType theAssetType, Class<T> theType,
																 			 String theCategory, String theSubCategory, String theResourceType) {
		return () -> fetch(refAssets(theAssetType) + filter(theCategory, theSubCategory, theResourceType), theType);
	}
	
	protected String refAssets(AssetType theAssetType) {
		return this.rootPath + theAssetType + "s/";
	}

	private String filter(String theCategory, String theSubCategory, String theResourceType) {
		StringBuilder filter = null;
		if (theCategory != null) {
			filter = new StringBuilder();
			filter.append("?category=")
						.append(theCategory);
			if (theSubCategory != null) {
				filter.append("&subCategory=")
							.append(theSubCategory);
				if (theResourceType != null) {
					filter.append("&resourceType=")
								.append(theResourceType);
				}
			}
		}
		return filter == null ? "" : filter.toString();
	}

	protected String refAsset(AssetType theAssetType, UUID theId) {
		return this.rootPath + theAssetType + "s/" + theId;
	}
	
	public <T> Future<T> getResource(UUID theId, Class<T> theType) {
		return getAsset(AssetType.resource, theId, theType);
	}
	
	public Future<JSONObject> getResource(UUID theId) {
		return getAsset(AssetType.resource, theId, JSONObject.class);
	}

	public Future<ResourceDetailed> getSDCResource(UUID theId) {
		return getAsset(AssetType.resource, theId, ResourceDetailed.class);
	}


	public <T> Future<T> getService(UUID theId, Class<T> theType) {
		return getAsset(AssetType.service, theId, theType);
	}
	
	public Future<JSONObject> getService(UUID theId) {
		return getAsset(AssetType.service, theId, JSONObject.class);
	}

	public <T> Future<T> getAsset(AssetType theAssetType, UUID theId, Class<T> theType) {
		return fetch(refAsset(theAssetType, theId) + "/metadata", theType);
	}
	
	public <T> Action<T> getAssetAction(AssetType theAssetType, UUID theId, Class<T> theType) {
		return () -> fetch(refAsset(theAssetType, theId) + "/metadata", theType);
	}

	public Future<byte[]> getResourceArchive(UUID theId) {
		return getAssetArchive(AssetType.resource, theId);
	}

	public Future<byte[]> getServiceArchive(UUID theId) {
		return getAssetArchive(AssetType.service, theId);
	}

	public Future<byte[]> getAssetArchive(AssetType theAssetType, UUID theId) {
		return fetch(refAsset(theAssetType, theId) + "/toscaModel", byte[].class);
	}

	public Action<byte[]> getAssetArchiveAction(AssetType theAssetType, UUID theId) {
		return () -> fetch(refAsset(theAssetType, theId) + "/toscaModel", byte[].class);
	}

	public Future<JSONObject> checkinResource(UUID theId, String theUser, String theMessage) {
		return cycleAsset(AssetType.resource, theId, LifecycleState.Checkin, theUser, theMessage);
	}

	public Future<JSONObject> checkinService(UUID theId, String theUser, String theMessage) {
		return cycleAsset(AssetType.service, theId, LifecycleState.Checkin, theUser, theMessage);
	}

	public Future<JSONObject> checkoutResource(UUID theId, String theUser, String theMessage) {
		return cycleAsset(AssetType.resource, theId, LifecycleState.Checkout, theUser, theMessage);
	}

	public Future<JSONObject> checkoutService(UUID theId, String theUser, String theMessage) {
		return cycleAsset(AssetType.service, theId, LifecycleState.Checkout, theUser, theMessage);
	}
	
	public Future<JSONObject> certifyResource(UUID theId, String theUser, String theMessage) {
		return cycleAsset(AssetType.resource, theId, LifecycleState.Certify, theUser, theMessage);
	}

	public Future<JSONObject> certifyService(UUID theId, String theUser, String theMessage) {
		return cycleAsset(AssetType.service, theId, LifecycleState.Certify, theUser, theMessage);
	}

	/* Normally theMessage is mandatory (and we'd use put instead of putOpt) but .. not so for undocheckout ..
	 */
	public Future<JSONObject> cycleAsset(AssetType theAssetType, UUID theId, LifecycleState theState,
																			 String theUser, String theMessage) {
		return post(refAsset(theAssetType, theId)	+ "/lifecycleState/" + theState,
				headers -> prepareHeaders(headers).header(USER_ID, theUser), new JSONObject().putOpt("userRemarks", theMessage));
	}

	protected String refAssetInstanceArtifact(AssetType theAssetType, UUID theAssetId, String theAssetInstance, UUID theArtifactId) {
		return refAsset(theAssetType, theAssetId) + "/resourceInstances/" + theAssetInstance + "/artifacts" + (theArtifactId == null ? "" : ("/" + theArtifactId));
	}

	protected String refAssetArtifact(AssetType theAssetType, UUID theAssetId, UUID theArtifactId) {
		return refAsset(theAssetType, theAssetId) + "/artifacts" + (theArtifactId == null ? "" : ("/" + theArtifactId));
	}
	
	public <T> Future<T> getResourceArtifact(UUID theAssetId, UUID theArtifactId, Class<T> theType) {
		return getAssetArtifact(AssetType.resource, theAssetId, theArtifactId, theType);
	}
	
	public <T> Future<T> getServiceArtifact(UUID theAssetId, UUID theArtifactId, Class<T> theType) {
		return getAssetArtifact(AssetType.service, theAssetId, theArtifactId, theType);
	}
	
	public <T> Future<T> getResourceInstanceArtifact(UUID theAssetId, UUID theArtifactId, String theInstance, Class<T> theType) {
		return getAssetInstanceArtifact(AssetType.resource, theAssetId, theInstance, theArtifactId, theType);
	}
	
	public <T> Future<T> getServiceInstanceArtifact(UUID theAssetId, UUID theArtifactId, String theInstance, Class<T> theType) {
		return getAssetInstanceArtifact(AssetType.service, theAssetId, theInstance, theArtifactId, theType);
	}

	public <T> Future<T> getAssetArtifact(AssetType theAssetType, UUID theAssetId, UUID theArtifactId, Class<T> theType) {
		return fetch(refAssetArtifact(theAssetType, theAssetId, theArtifactId), theType);
	}
	
	public <T> Action<T> getAssetArtifactAction(AssetType theAssetType, UUID theAssetId, UUID theArtifactId, Class<T> theType) {
		return () -> fetch(refAssetArtifact(theAssetType, theAssetId, theArtifactId), theType);
	}
	
	public <T> Future<T> getAssetInstanceArtifact(AssetType theAssetType, UUID theAssetId, String theInstance, UUID theArtifactId, Class<T> theType) {
		return fetch(refAssetInstanceArtifact(theAssetType, theAssetId, theInstance, theArtifactId), theType);
	}
	
	public <T> Action<T> getAssetInstanceArtifactAction(AssetType theAssetType, UUID theAssetId, String theInstance, UUID theArtifactId, Class<T> theType) {
		return () -> fetch(refAssetInstanceArtifact(theAssetType, theAssetId, theInstance, theArtifactId), theType);
	}
	
	public ArtifactUploadAction createResourceArtifact(UUID theAssetId) {
		return createAssetArtifact(AssetType.resource, theAssetId);
	}
	
	public ArtifactUploadAction createServiceArtifact(UUID theAssetId) {
		return createAssetArtifact(AssetType.service, theAssetId);
	}
	
	public ArtifactUploadAction createResourceInstanceArtifact(UUID theAssetId, String theInstance) {
		return createAssetInstanceArtifact(AssetType.resource, theAssetId, theInstance);
	}
	
	public ArtifactUploadAction createServiceInstanceArtifact(UUID theAssetId, String theInstance) {
		return createAssetInstanceArtifact(AssetType.service, theAssetId, theInstance);
	}

	public ArtifactUploadAction createAssetArtifact(AssetType theAssetType, UUID theAssetId) {
		return new ArtifactUploadAction()
									.ofAsset(theAssetType, theAssetId);
	}
	
	public ArtifactUploadAction createAssetInstanceArtifact(AssetType theAssetType, UUID theAssetId, String theInstance) {
		return new ArtifactUploadAction()
									.ofAssetInstance(theAssetType, theAssetId, theInstance);
	}

	public ArtifactUpdateAction updateResourceArtifact(UUID theAssetId, JSONObject theArtifactInfo) {
		return updateAssetArtifact(AssetType.resource, theAssetId, theArtifactInfo);
	}
	
	public ArtifactUpdateAction updateResourceInstanceArtifact(UUID theAssetId, String theInstance, JSONObject theArtifactInfo) {
		return updateAssetInstanceArtifact(AssetType.resource, theAssetId, theInstance, theArtifactInfo);
	}
	
	public ArtifactUpdateAction updateServiceArtifact(UUID theAssetId, JSONObject theArtifactInfo) {
		return updateAssetArtifact(AssetType.service, theAssetId, theArtifactInfo);
	}
	
	public ArtifactUpdateAction updateServiceInstanceArtifact(UUID theAssetId, String theInstance, JSONObject theArtifactInfo) {
		return updateAssetInstanceArtifact(AssetType.service, theAssetId, theInstance, theArtifactInfo);
	}

	public ArtifactUpdateAction updateAssetArtifact(AssetType theAssetType, UUID theAssetId, JSONObject theArtifactInfo) {
		return new ArtifactUpdateAction(theArtifactInfo)
									.ofAsset(theAssetType, theAssetId);
	}
	
	public ArtifactUpdateAction updateAssetInstanceArtifact(AssetType theAssetType, UUID theAssetId, String theInstance, JSONObject theArtifactInfo) {
		return new ArtifactUpdateAction(theArtifactInfo)
									.ofAssetInstance(theAssetType, theAssetId, theInstance);
	}

	public ArtifactDeleteAction deleteResourceArtifact(UUID theAssetId, UUID theArtifactId) {
		return deleteAssetArtifact(AssetType.resource, theAssetId, theArtifactId);
	}
	
	public ArtifactDeleteAction deleteResourceInstanceArtifact(UUID theAssetId, String theInstance, UUID theArtifactId) {
		return deleteAssetInstanceArtifact(AssetType.resource, theAssetId, theInstance, theArtifactId);
	}
	
	public ArtifactDeleteAction deleteServiceArtifact(UUID theAssetId, UUID theArtifactId) {
		return deleteAssetArtifact(AssetType.service, theAssetId, theArtifactId);
	}
	
	public ArtifactDeleteAction deleteServiceInstanceArtifact(UUID theAssetId, String theInstance, UUID theArtifactId) {
		return deleteAssetInstanceArtifact(AssetType.service, theAssetId, theInstance, theArtifactId);
	}

	public ArtifactDeleteAction deleteAssetArtifact(AssetType theAssetType, UUID theAssetId, UUID theArtifactId) {
		return new ArtifactDeleteAction(theArtifactId)
									.ofAsset(theAssetType, theAssetId);
	}
	
	public ArtifactDeleteAction deleteAssetInstanceArtifact(AssetType theAssetType, UUID theAssetId, String theInstance, UUID theArtifactId) {
		return new ArtifactDeleteAction(theArtifactId)
									.ofAssetInstance(theAssetType, theAssetId, theInstance);
	}

	
	public abstract class ASDCAction<A extends ASDCAction<A, T>, T> implements Action<T> { 

		protected JSONObject 	info; 				//info passed to asdc as request body
		protected String			operatorId;		//id of the SDC user performing the action

		protected ASDCAction(JSONObject theInfo) {
			this.info = theInfo;
		}
		
		protected abstract A self(); 

		protected ASDC asdc() {
			return ASDC.this;
		}
	
		protected A withInfo(JSONObject theInfo) {
			merge(this.info, theInfo);
			return self();
		}
	
		public A with(String theProperty, Object theValue) {
			info.put(theProperty, theValue);
			return self();
		}

		public A withOperator(String theOperator) {
			this.operatorId = theOperator;
			return self();			
		}
		
		protected abstract String[] mandatoryInfoEntries();
	
		protected void checkOperatorId() {
			if (this.operatorId == null) {
				throw new IllegalStateException("No operator id was provided");
			}
		}

		protected void checkMandatoryInfo() {
			for (String field: mandatoryInfoEntries()) {
				if (!info.has(field)) {
					throw new IllegalStateException("No '" + field + "' was provided");
				}
			}
		}
		
		protected void checkMandatory() {
			checkOperatorId();
			checkMandatoryInfo();
		}
	}


	/**
     * We use teh same API to operate on artifacts attached to assets or to their instances
	 */
	public abstract class ASDCArtifactAction<A extends ASDCArtifactAction<A>> extends ASDCAction<A, JSONObject> {

		protected AssetType		assetType;
		protected UUID				assetId;
		protected String			assetInstance;

		protected ASDCArtifactAction(JSONObject theInfo) {
			super(theInfo);
		}
		
		protected A ofAsset(AssetType theAssetType, UUID theAssetId) {
			this.assetType = theAssetType;
			this.assetId = theAssetId;
			return self();			
		}
		
		protected A ofAssetInstance(AssetType theAssetType, UUID theAssetId, String theInstance) {
			this.assetType = theAssetType;
			this.assetId = theAssetId;
			this.assetInstance = theInstance;
			return self();			
		}
		
		protected String normalizeInstanceName(String theName) {
			return StringUtils.removePattern(theName, "[ \\.\\-]+").toLowerCase();
		}
		
		protected String[] mandatoryInfoEntries() {
			return ASDC.this.artifactMandatoryEntries;
		}

		protected String ref(UUID theArtifactId) {
			return (this.assetInstance == null) ?
								refAssetArtifact(this.assetType, this.assetId, theArtifactId) :
								refAssetInstanceArtifact(this.assetType, this.assetId, normalizeInstanceName(this.assetInstance), theArtifactId);
		}
	}

	public class ArtifactUploadAction extends ASDCArtifactAction<ArtifactUploadAction> {

		public static final String PAYLOAD_DATA = ASDC.PAYLOAD_DATA;

		protected ArtifactUploadAction() {
			super(new JSONObject());
		}

		protected ArtifactUploadAction self() {
			return this;
		}
		
		public ArtifactUploadAction withContent(byte[] theContent) {
			return with(PAYLOAD_DATA, Base64Utils.encodeToString(theContent));
		}

		public ArtifactUploadAction withContent(File theFile) throws IOException {
			return withContent(FileUtils.readFileToByteArray(theFile));
		}

		public ArtifactUploadAction withLabel(String theLabel) {
			return with(ARTIFACT_LABEL, theLabel);
		}
		
		public ArtifactUploadAction withName(String theName) {
			return with(ARTIFACT_NAME, theName);
		}
		
		public ArtifactUploadAction withDisplayName(String theName) {
			return with("artifactDisplayName", theName);
		}

		public ArtifactUploadAction withType(ArtifactType theType) {
			return with(ARTIFACT_TYPE, theType.toString());
		}

		public ArtifactUploadAction withGroupType(ArtifactGroupType theGroupType) {
			return with(ARTIFACT_GROUP_TYPE, theGroupType.toString());
		}

		public ArtifactUploadAction withDescription(String theDescription) {
			return with(DESCRIPTION, theDescription);
		}

		@Override
		protected String[] mandatoryInfoEntries() {
			return ASDC.this.uploadMandatoryEntries;
		}

		public Future<JSONObject> execute() {
			checkMandatory();
			return ASDC.this.post(ref(null),
					headers -> prepareHeaders(headers).header(USER_ID, this.operatorId), this.info);
		}
	}



	/**
	 * In its current form the update relies on a previous artifact retrieval. One cannot build an update from scratch.
	 * The label, tye and group type must be submitted but cannot be updated
	 */
	public class ArtifactUpdateAction extends ASDCArtifactAction<ArtifactUpdateAction> {

		
		protected ArtifactUpdateAction(JSONObject theInfo) {
			super(theInfo);
		}
		
		protected ArtifactUpdateAction self() {
			return this;
		}
		
		public ArtifactUpdateAction withContent(byte[] theContent) {
			return with(PAYLOAD_DATA, Base64Utils.encodeToString(theContent));
		}

		public ArtifactUpdateAction withContent(File theFile) throws IOException {
			return withContent(FileUtils.readFileToByteArray(theFile));
		}

		public ArtifactUpdateAction withDescription(String theDescription) {
			return with(DESCRIPTION, theDescription);
		}
		
		public ArtifactUpdateAction withName(String theName) {
			return with(ARTIFACT_NAME, theName);
		}

		@Override
		protected String[] mandatoryInfoEntries() {
			return ASDC.this.updateMandatoryEntries;
		}

		/* The json object originates (normally) from a get so it will have entries we need to cleanup */
		protected void cleanupInfoEntries() {
			this.info.remove("artifactChecksum");
			this.info.remove("artifactUUID");
			this.info.remove("artifactVersion");
			this.info.remove("artifactURL");
			this.info.remove("artifactDescription");
		}
		
		public Future<JSONObject> execute() {
			UUID artifactUUID = UUID.fromString(this.info.getString("artifactUUID"));
			checkMandatory();
			cleanupInfoEntries();
			return ASDC.this.post(ref(artifactUUID),
					headers -> prepareHeaders(headers).header(USER_ID, this.operatorId),this.info);
		}
	}

	public class ArtifactDeleteAction extends ASDCArtifactAction<ArtifactDeleteAction> {

		private UUID		artifactId;
		
		protected ArtifactDeleteAction(UUID theArtifactId) {
			super(null);
			this.artifactId = theArtifactId;
		}
		
		protected ArtifactDeleteAction self() {
			return this;
		}
		
		public Future<JSONObject> execute() {
			checkMandatory();
			return ASDC.this.delete(ref(this.artifactId),
					headers -> prepareHeaders(headers).header(USER_ID, this.operatorId));
		}
	}




	private VFCMTCreateAction createVFCMT() {
		return new VFCMTCreateAction();
	}




	public class VFCMTCreateAction extends ASDCAction<VFCMTCreateAction, JSONObject> {

		private static final String CONTACT_ID = "contactId";
		private final String[] vfcmtMandatoryEntries = new String[] { "name", "vendorName", "vendorRelease", CONTACT_ID};

		protected VFCMTCreateAction() {

			super(new JSONObject());
			this
				.with("resourceType", "VFCMT")
				.with("category", "Template")
				.with("subcategory", "Monitoring Template")
				.with("icon", "defaulticon");
		}
		
		protected VFCMTCreateAction self() {
			return this;
		}

		public VFCMTCreateAction withName(String theName) {
			return with("name", theName);
		}

		public VFCMTCreateAction withDescription(String theDescription) {
			return with(DESCRIPTION, theDescription);
		}
		
		public VFCMTCreateAction withVendorName(String theVendorName) {
			return with("vendorName", theVendorName);
		}
		
		public VFCMTCreateAction withVendorRelease(String theVendorRelease) {
			return with("vendorRelease", theVendorRelease);
		}
		
		public VFCMTCreateAction withTags(String... theTags) {
			for (String tag: theTags) {
				this.info.append("tags", tag);
			}
			return this;			
		}
		
		public VFCMTCreateAction withIcon(String theIcon) {
			return with("icon", theIcon);
		}
		
		protected String[] mandatoryInfoEntries() {
			return vfcmtMandatoryEntries;
		}
		
		public VFCMTCreateAction withContact(String theContact) {
			return with(CONTACT_ID, theContact);
		}
		
		public Future<JSONObject> execute() {
		
			this.info.putOnce(CONTACT_ID, this.operatorId);
			this.info.append("tags", info.optString("name"));
			checkMandatory();
			return ASDC.this.post(refAssets(AssetType.resource),
					headers -> prepareHeaders(headers).header(USER_ID, this.operatorId), this.info);
		}

	}

	public static JSONObject merge(JSONObject theOriginal, JSONObject thePatch) {
		for (String key: (Set<String>)thePatch.keySet()) {
			if (!theOriginal.has(key)) {
				theOriginal.put(key, thePatch.get(key));
			}
		}
		return theOriginal;
	}

	protected URI refUri(String theRef) {
		try {
			return new URI(this.rootUri + theRef);
		}
		catch(URISyntaxException urisx) {
			throw new UncheckedIOException(new IOException(urisx));
		}
	}

	private HttpHeaders prepareHeaders() {
		HttpHeaders headers = new HttpHeaders();
		headers.add(HttpHeaders.AUTHORIZATION, "Basic " + Base64Utils.encodeToString((this.user + ":" + this.passwd).getBytes()));
		headers.add(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
		headers.add(HttpHeaders.ACCEPT, MediaType.APPLICATION_OCTET_STREAM_VALUE);
		headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE);
		headers.add("X-ECOMP-InstanceID", this.instanceId);

		return headers;
	}

	private RequestEntity.HeadersBuilder prepareHeaders(RequestEntity.HeadersBuilder theBuilder) {
		return theBuilder
			.header(HttpHeaders.AUTHORIZATION, "Basic " + Base64Utils.encodeToString((this.user + ":" + this.passwd).getBytes()))
			.header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
			.header(HttpHeaders.ACCEPT, MediaType.APPLICATION_OCTET_STREAM_VALUE)
			.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE)
			.header("X-ECOMP-InstanceID", this.instanceId);
	}

	public <T> Future<T> fetch(String theRef, Class<T> theContentType) {
		return exchange(theRef, HttpMethod.GET, new HttpEntity(prepareHeaders()), theContentType);
	}

	public Future<JSONObject> post(String theRef, JSONObject thePost) {
		return exchange(theRef, HttpMethod.POST, new HttpEntity<JSONObject>(thePost, prepareHeaders()), JSONObject.class);
	}
	
	public Future<JSONObject> post(String theRef, UnaryOperator<RequestEntity.HeadersBuilder> theHeadersBuilder, JSONObject thePost) {
		RequestEntity.BodyBuilder builder = RequestEntity.post(refUri(theRef));
		theHeadersBuilder.apply(builder);

		return exchange(theRef, HttpMethod.POST, builder.body(thePost), JSONObject.class);
	}
	
	public Future<JSONObject> delete(String theRef, UnaryOperator<RequestEntity.HeadersBuilder> theHeadersBuilder) {

		RequestEntity.HeadersBuilder builder = RequestEntity.delete(refUri(theRef));
		theHeadersBuilder.apply(builder);

		return exchange(theRef, HttpMethod.DELETE, builder.build(), JSONObject.class);
	}
	
	public <T> Future<T> exchange(String theRef, HttpMethod theMethod, HttpEntity theRequest, Class<T> theResponseType) {
		
		AsyncRestTemplate restTemplate = new AsyncRestTemplate();

		List<HttpMessageConverter<?>> converters = restTemplate.getMessageConverters();
		converters.add(0, new JSONHttpMessageConverter());
		restTemplate.setMessageConverters(converters);

		restTemplate.setInterceptors(Collections.singletonList(new ContentMD5Interceptor()));
		ASDCFuture<T> result = new ASDCFuture<T>();
		String uri = this.rootUri + theRef;
		try {
			restTemplate
				.exchange(uri, theMethod, theRequest, theResponseType)
					.addCallback(result.callback);
		}
		catch (RestClientException rcx) {
			errLogger.log(LogLevel.WARN, this.getClass().getName(), "Failed to fetch {} {}", uri, rcx);
			return Futures.failedFuture(rcx);
		}
		catch (Exception x) {
			errLogger.log(LogLevel.WARN, this.getClass().getName(), "Failed to fetch {} {}", uri, x);
			return Futures.failedFuture(x);
		}
	 
		return result;
	}



	public class ASDCFuture<T> extends Futures.BasicFuture<T> {

		ListenableFutureCallback<ResponseEntity<T>> callback = new ListenableFutureCallback<ResponseEntity<T>>() {

			public void	onSuccess(ResponseEntity<T> theResult) {
				ASDCFuture.this.result(theResult.getBody());
			}

			public void	onFailure(Throwable theError) {
				if (theError instanceof HttpClientErrorException) {
						ASDCFuture.this.cause(new ASDCException((HttpClientErrorException)theError));
				}
				else {
					ASDCFuture.this.cause(theError);
				}
			}
		};

	}

	public class ContentMD5Interceptor implements AsyncClientHttpRequestInterceptor {
		@Override
		public ListenableFuture<ClientHttpResponse> intercept(
				HttpRequest theRequest, byte[] theBody, AsyncClientHttpRequestExecution theExecution)
				throws IOException {
			if (HttpMethod.POST == theRequest.getMethod()) {
				HttpHeaders headers = theRequest.getHeaders();
				headers.add("Content-MD5", Base64Utils.encodeToString(DigestUtils.md5Hex(theBody).getBytes()));
			}
			return theExecution.executeAsync(theRequest, theBody);
		}
	}

	public static void main(String[] theArgs) throws Exception {

		CommandLineParser parser = new BasicParser();
		
		String userId = "jh0003";
		
		Options options = new Options();
		options.addOption(OptionBuilder
														  .withArgName(TARGET)
															.withLongOpt(TARGET)
                               .withDescription("target asdc system")
															.hasArg()
															.isRequired()
															.create('t') );
			
		options.addOption(OptionBuilder
														  .withArgName(ACTION)
															.withLongOpt(ACTION)
                              .withDescription("one of: list, get, getartifact, checkin, checkout")
															.hasArg()
															.isRequired()
															.create('a') );

		options.addOption(OptionBuilder
														  .withArgName(ASSET_TYPE)
															.withLongOpt(ASSET_TYPE)
                               .withDescription("one of resource, service, product")
															.hasArg()
															.isRequired()
															.create('k') ); //k for 'kind' ..

		options.addOption(OptionBuilder
														  .withArgName(ASSET_ID)
															.withLongOpt(ASSET_ID)
                               .withDescription("asset uuid")
															.hasArg()
															.create('u') ); //u for 'uuid'

		options.addOption(OptionBuilder
														  .withArgName(ARTIFACT_ID)
															.withLongOpt(ARTIFACT_ID)
                               .withDescription("artifact uuid")
															.hasArg()
															.create('s') ); //s for 'stuff'

		options.addOption(OptionBuilder
														  .withArgName(LIST_FILTER)
															.withLongOpt(LIST_FILTER)
                               .withDescription("filter for list operations")
															.hasArg()
															.create('f') ); //u for 'uuid'

		CommandLine line = null;
		try {
   		line = parser.parse(options, theArgs);
		}
		catch(ParseException exp) {
			errLogger.log(LogLevel.ERROR, ASDC.class.getName(), exp.getMessage());
			new HelpFormatter().printHelp("asdc", options);
			return;
		}

		ASDC asdc = new ASDC();
		asdc.setUri(new URI(line.getOptionValue(TARGET)));

		String action = line.getOptionValue(ACTION);
		if ("list".equals(action)) {
			JSONObject filterInfo = new JSONObject(
																			line.hasOption(LIST_FILTER) ?
																				line.getOptionValue(LIST_FILTER) : "{}");
			JSONArray assets = 
				asdc.getAssets(ASDC.AssetType.valueOf(line.getOptionValue(ASSET_TYPE)), JSONArray.class,
											 filterInfo.optString("category", null), filterInfo.optString("subCategory", null))
						.waitForResult();
			for (int i = 0; i < assets.length(); i++) {
				debugLogger.log(LogLevel.DEBUG, ASDC.class.getName(),"> {}", assets.getJSONObject(i).toString(2));
			}
		}
		else if ("get".equals(action)) {
			debugLogger.log(LogLevel.DEBUG, ASDC.class.getName(),
					asdc.getAsset(ASDC.AssetType.valueOf(line.getOptionValue(ASSET_TYPE)),
											UUID.fromString(line.getOptionValue(ASSET_ID)),
											JSONObject.class)
						.waitForResult()
						.toString(2)
			);
		}
		else if ("getartifact".equals(action)) {
			debugLogger.log(LogLevel.DEBUG, ASDC.class.getName(),
					asdc.getAssetArtifact(ASDC.AssetType.valueOf(line.getOptionValue(ASSET_TYPE)),
															UUID.fromString(line.getOptionValue(ASSET_ID)),
															UUID.fromString(line.getOptionValue(ARTIFACT_ID)),
															String.class)
						.waitForResult()
			);
		}
		else if ("checkin".equals(action)) {
			debugLogger.log(LogLevel.DEBUG, ASDC.class.getName(),
					asdc.cycleAsset(ASDC.AssetType.valueOf(line.getOptionValue(ASSET_TYPE)),
													UUID.fromString(line.getOptionValue(ASSET_ID)),
													ASDC.LifecycleState.Checkin,
													userId,
													"cli op")
							.waitForResult()
							.toString()
			);
		}
		else if ("checkout".equals(action)) {
			debugLogger.log(LogLevel.DEBUG, ASDC.class.getName(),
					asdc.cycleAsset(ASDC.AssetType.valueOf(line.getOptionValue(ASSET_TYPE)),
													UUID.fromString(line.getOptionValue(ASSET_ID)),
													ASDC.LifecycleState.Checkout,
													userId,
													"cli op")
							.waitForResult()
							.toString()
			);
		}
		else if ("cleanup".equals(action)) {
			JSONArray resources = asdc.getResources()
																	.waitForResult();
			debugLogger.log(LogLevel.DEBUG, ASDC.class.getName(),"Got {} resources", resources.length());

			vfcmtCleanup(userId, asdc, resources);
		}
		else {
			try {
				debugLogger.log(LogLevel.DEBUG, ASDC.class.getName(),
					asdc.createVFCMT()
							.withName("Clonator")
							.withDescription("Clone operation target 06192017")
							.withVendorName("CloneInc")
							.withVendorRelease("1.0")
							.withTags("clone")
							.withOperator(userId)
							.execute()
							.waitForResult()
							.toString()
				);
			}
			catch(Exception x) {
				debugLogger.log(LogLevel.DEBUG, ASDC.class.getName(),"Failed to create VFCMT: {}", x);
			}
		}
	}

	private static void vfcmtCleanup(String userId, ASDC asdc, JSONArray resources) {
		for (int i = 0; i < resources.length(); i++) {

            JSONObject resource = resources.getJSONObject(i);

            if ("VFCMT".equals(resource.getString("resourceType")) &&
                    resource.getString("name").contains("test")) {

                debugLogger.log(LogLevel.DEBUG, ASDC.class.getName(),"undocheckout for {}", resource.getString("uuid"));

                try {
                    asdc.cycleAsset(AssetType.resource, UUID.fromString(resource.getString("uuid")), LifecycleState.undocheckout, userId, null)
                        .waitForResult();
                }
                catch (Exception x) {
                    debugLogger.log(LogLevel.DEBUG, ASDC.class.getName(),"** {}", x);
                }
            }
        }
	}
}