Fix Security Vulnerabilities
[sdc.git] / catalog-ui / src / app / models / components / component.ts
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 'use strict';
22
23 import * as _ from "lodash";
24 import {AsdcComment, ArtifactModel, ArtifactGroupModel, IFileDownload, PropertyModel, PropertiesGroup, AttributeModel, AttributesGroup, ComponentInstance,
25     InputModel, DisplayModule, Module, IValidate, RelationshipModel, IMainCategory, RequirementsGroup, CapabilitiesGroup, AdditionalInformationModel,
26     Resource, IAppMenu, OperationModel, Service} from "../../models";
27
28 import {IComponentService} from "../../services/components/component-service";
29 import {CommonUtils} from "../../utils/common-utils";
30 import {QueueUtils} from "../../utils/functions";
31 import {ArtifactGroupType} from "../../utils/constants";
32 import {ComponentMetadata} from "../component-metadata";
33 import {Capability} from "../capability";
34 import {Requirement} from "../requirement";
35 import {Relationship} from "../graph/relationship";
36 import { PolicyInstance } from "app/models/graph/zones/policy-instance";
37 import { GroupInstance } from "../graph/zones/group-instance";
38 import { Metadata } from "app/models/metadata";
39
40
41 // import {}
42 export interface IComponent {
43
44     //---------------------------------------------- API CALLS ----------------------------------------------------//
45
46     //Component API
47     getComponent():ng.IPromise<Component>;
48     updateComponent():ng.IPromise<Component>;
49     createComponentOnServer():ng.IPromise<Component>;
50     changeLifecycleState(state:string, commentObj:AsdcComment):ng.IPromise<Component>;
51     validateName(newName:string):ng.IPromise<IValidate>;
52
53     //Artifacts API
54     addOrUpdateArtifact(artifact:ArtifactModel):ng.IPromise<ArtifactModel>;
55     deleteArtifact(artifactId:string, artifactLabel:string):ng.IPromise<ArtifactModel>;
56     downloadInstanceArtifact(artifactId:string):ng.IPromise<IFileDownload>;
57     downloadArtifact(artifactId:string):ng.IPromise<IFileDownload>;
58
59     //Property API
60     addOrUpdateProperty(property:PropertyModel):ng.IPromise<PropertyModel>;
61     deleteProperty(propertyId:string):ng.IPromise<PropertyModel>;
62
63     //Attribute API
64     deleteAttribute(attributeId:string):ng.IPromise<AttributeModel>;
65     addOrUpdateAttribute(attribute:AttributeModel):ng.IPromise<AttributeModel>;
66
67     //Modules
68     getModuleForDisplay(moduleId:string):ng.IPromise<DisplayModule>;
69     getModuleInstanceForDisplay(componentInstanceId:string, moduleId:string):ng.IPromise<DisplayModule>;
70     updateGroupMetadata(group:Module):ng.IPromise<Module>;
71
72     //---------------------------------------------- HELP FUNCTIONS ----------------------------------------------------//
73
74     getComponentSubType():string;
75     isAlreadyCertified():boolean;
76     isService():boolean;
77     isResource():boolean;
78     isComplex():boolean;
79     getAllVersionsAsSortedArray():Array<any>;
80     getStatus(sdcMenu:IAppMenu):string;
81 }
82
83
84 export abstract class Component implements IComponent {
85
86     //server data
87     public abstract:string;
88     public uniqueId:string;
89     public uuid:string;
90     public invariantUUID:string;
91     public name:string;
92     public version:string;
93     public creationDate:number;
94     public lastUpdateDate:number;
95     public description:string;
96     public lifecycleState:string;
97     public tags:Array<string>;
98     public icon:string;
99     public contactId:string;
100     public allVersions:any;
101     public creatorUserId:string;
102     public creatorFullName:string;
103     public lastUpdaterUserId:string;
104     public lastUpdaterFullName:string;
105     public componentType:string;
106     public deploymentArtifacts:ArtifactGroupModel;
107     public artifacts:ArtifactGroupModel;
108     public toscaArtifacts:ArtifactGroupModel;
109     public interfaceOperations:Array<OperationModel>;
110     public distributionStatus:string;
111     public categories:Array<IMainCategory>;
112     public categoryNormalizedName: string;
113     public subCategoryNormalizedName: string;
114     public componentInstancesProperties:PropertiesGroup;
115     public componentInstancesAttributes:AttributesGroup;
116     public componentInstancesRelations:Array<RelationshipModel>;
117     public componentInstances:Array<ComponentInstance>;
118     public inputs:Array<InputModel>;
119     public capabilities:CapabilitiesGroup;
120     public requirements:RequirementsGroup;
121     public additionalInformation:any;
122     public properties:Array<PropertyModel>;
123     public attributes:Array<AttributeModel>;
124     public highestVersion:boolean;
125     public vendorName:string;
126     public vendorRelease:string;
127     public derivedList:Array<any>;
128     public interfaces:any;
129     public normalizedName:string;
130     public systemName:string;
131     public policies:Array<PolicyInstance>;
132     public groupInstances:Array<GroupInstance>
133     public modules:Array<Module>;
134     //custom properties
135     public componentService:IComponentService;
136     public filterTerm:string;
137     public iconSprite:string;
138     public selectedInstance:ComponentInstance;
139     public mainCategory:string;
140     public subCategory:string;
141     public selectedCategory:string;
142     public showMenu:boolean;
143     public archived:boolean;
144     public vspArchived: boolean;
145     public componentMetadata: ComponentMetadata;
146     public categorySpecificMetadata: Metadata = new Metadata();
147
148     constructor(componentService:IComponentService, protected $q:ng.IQService, component?:Component) {
149         if (component) {
150             this.abstract = component.abstract;
151             this.uniqueId = component.uniqueId;
152             this.uuid = component.uuid;
153             this.invariantUUID = component.invariantUUID;
154             this.additionalInformation = component.additionalInformation;
155             this.artifacts = new ArtifactGroupModel(component.artifacts);
156             this.toscaArtifacts = new ArtifactGroupModel(component.toscaArtifacts);
157             this.interfaceOperations = component.interfaceOperations;
158             this.contactId = component.contactId;
159             this.categories = component.categories;
160             this.categoryNormalizedName = component.categoryNormalizedName;
161             this.subCategoryNormalizedName = component.subCategoryNormalizedName;
162             this.creatorUserId = component.creatorUserId;
163             this.creationDate = component.creationDate;
164             this.creatorFullName = component.creatorFullName;
165             this.description = component.description;
166             this.icon = component.icon;
167             this.lastUpdateDate = component.lastUpdateDate;
168             this.lastUpdaterUserId = component.lastUpdaterUserId;
169             this.lastUpdaterFullName = component.lastUpdaterFullName;
170             this.lifecycleState = component.lifecycleState;
171             this.componentInstancesRelations = CommonUtils.initComponentInstanceRelations(component.componentInstancesRelations);
172             this.componentInstancesProperties = new PropertiesGroup(component.componentInstancesProperties);
173             this.componentInstancesAttributes = new AttributesGroup(component.componentInstancesAttributes);
174             this.name = component.name;
175             this.version = component.version;
176             this.tags = [];
177             angular.copy(component.tags, this.tags);
178             this.capabilities = new CapabilitiesGroup(component.capabilities);
179             this.requirements = new RequirementsGroup(component.requirements);
180             this.allVersions = component.allVersions;
181             this.deploymentArtifacts = new ArtifactGroupModel(component.deploymentArtifacts);
182             this.componentType = component.componentType;
183             this.distributionStatus = component.distributionStatus;
184             this.highestVersion = component.highestVersion;
185             this.vendorName = component.vendorName;
186             this.vendorRelease = component.vendorRelease;
187             this.derivedList = component.derivedList;
188             this.interfaces = component.interfaces;
189             this.normalizedName = component.normalizedName;
190             this.systemName = component.systemName;
191             this.inputs = component.inputs;
192             this.componentInstances = CommonUtils.initComponentInstances(component.componentInstances);
193             this.properties = CommonUtils.initProperties(component.properties, this.uniqueId);
194             this.attributes = CommonUtils.initAttributes(component.attributes, this.uniqueId);
195             this.selectedInstance = component.selectedInstance;
196             this.iconSprite = component.iconSprite;
197             this.showMenu = true;
198             this.modules = component.modules;
199             this.groupInstances = component.groupInstances;
200             this.policies = component.policies;
201             this.archived = component.archived;
202             this.vspArchived = component.vspArchived;
203
204             if (component.categorySpecificMetadata && component.categories && component.categories[0]){
205                 this.copyCategoryMetadata(component);
206                 this.copySubcategoryMetadata(component);
207             }
208         }
209
210         //custom properties
211         this.componentService = componentService;
212     }
213
214     private copyCategoryMetadata = (component:Component):void => {
215         if (component.categories[0].metadataKeys){
216             for (let key of Object.keys(component.categorySpecificMetadata)) {
217                 if (component.categories[0].metadataKeys.some(metadataKey => metadataKey.name == key)) {
218                     this.categorySpecificMetadata[key] = component.categorySpecificMetadata[key];
219                 }
220             }
221         }
222     }
223     private copySubcategoryMetadata = (component:Component):void => {
224         if (component.categories[0].subcategories && component.categories[0].subcategories[0] && component.categories[0].subcategories[0].metadataKeys){
225             for (let key of Object.keys(component.categorySpecificMetadata)) {
226                 if (component.categories[0].subcategories[0].metadataKeys.some(metadataKey => metadataKey.name == key)) {
227                     this.categorySpecificMetadata[key] = component.categorySpecificMetadata[key];
228                 }
229             }
230         }
231     }
232
233     public setUniqueId = (uniqueId:string):void => {
234         this.uniqueId = uniqueId;
235     };
236
237     //------------------------------------------ API Calls ----------------------------------------------------------------//
238     public changeLifecycleState = (state:string, commentObj:AsdcComment):ng.IPromise<Component> => {
239         let deferred = this.$q.defer<Component>();
240         let onSuccess = (componentMetadata:ComponentMetadata):void => {
241             this.setComponentMetadata(componentMetadata);
242             // this.version = componentMetadata.version;
243             this.lifecycleState = componentMetadata.lifecycleState;
244
245             deferred.resolve(this);
246         };
247         let onError = (error:any):void => {
248             deferred.reject(error);
249         };
250         this.componentService.changeLifecycleState(this, state, commentObj).then(onSuccess, onError);
251         return deferred.promise;
252     };
253
254     public getComponent = ():ng.IPromise<Component> => {
255         return this.componentService.getComponent(this.uniqueId);
256     };
257
258     public createComponentOnServer = ():ng.IPromise<Component> => {
259         this.handleTags();
260         return this.componentService.createComponent(this);
261     };
262     
263     public importComponentOnServer = (): ng.IPromise<Component> => {
264         this.handleTags();
265         return this.componentService.importComponent(this);
266     };
267
268     public updateComponent = ():ng.IPromise<Component> => {
269         this.handleTags();
270         return this.componentService.updateComponent(this);
271     };
272
273     public validateName = (newName:string, subtype?:string):ng.IPromise<IValidate> => {
274         return this.componentService.validateName(newName, subtype);
275     };
276
277     public downloadArtifact = (artifactId: string): ng.IPromise<IFileDownload> => {
278         if(this.vendorName === 'IsService'){
279             return this.componentService.downloadArtifact(this.uniqueId, artifactId, this.vendorName);
280         }else{
281             return this.componentService.downloadArtifact(this.uniqueId, artifactId);
282         }
283     };
284
285     public addOrUpdateArtifact = (artifact:ArtifactModel):ng.IPromise<ArtifactModel> => {
286         let deferred = this.$q.defer<ArtifactModel>();
287         let onSuccess = (artifactObj:ArtifactModel):void => {
288             let newArtifact = new ArtifactModel(artifactObj);
289             let artifacts = this.getArtifactsByType(artifactObj.artifactGroupType);
290             artifacts[artifactObj.artifactLabel] = newArtifact;
291             deferred.resolve(newArtifact);
292         };
293         let onError = (error:any):void => {
294             deferred.reject(error);
295         };
296         this.componentService.addOrUpdateArtifact(this.uniqueId, artifact).then(onSuccess, onError);
297         return deferred.promise;
298     };
299
300     public deleteArtifact = (artifactId:string, artifactLabel:string):ng.IPromise<ArtifactModel> => {
301         let deferred = this.$q.defer<ArtifactModel>();
302         let onSuccess = (artifactObj:ArtifactModel):void => {
303             let newArtifact = new ArtifactModel(artifactObj);
304             let artifacts = this.getArtifactsByType(artifactObj.artifactGroupType);
305             if (newArtifact.mandatory || newArtifact.serviceApi) {
306                 artifacts[newArtifact.artifactLabel] = newArtifact;
307             }
308             else {
309                 delete artifacts[artifactLabel];
310             }
311             deferred.resolve(newArtifact);
312         };
313         this.componentService.deleteArtifact(this.uniqueId, artifactId, artifactLabel).then(onSuccess);
314         return deferred.promise;
315     };
316
317     public addOrUpdateProperty = (property:PropertyModel):ng.IPromise<PropertyModel> => {
318         let deferred = this.$q.defer<PropertyModel>();
319
320         let onError = (error:any):void => {
321             deferred.reject(error);
322         };
323
324         if (!property.uniqueId) {
325             let onSuccess = (property:PropertyModel):void => {
326                 let newProperty = new PropertyModel(property);
327                 this.properties.push(newProperty);
328                 deferred.resolve(newProperty);
329             };
330             this.componentService.addProperty(this.uniqueId, property).then(onSuccess, onError);
331         }
332         else {
333             let onSuccess = (newProperty:PropertyModel):void => {
334                 // find exist instance property in parent component for update the new value ( find bu uniqueId )
335                 let existProperty:PropertyModel = <PropertyModel>_.find(this.properties, {uniqueId: newProperty.uniqueId});
336                 let propertyIndex = this.properties.indexOf(existProperty);
337                 this.properties[propertyIndex] = newProperty;
338                 deferred.resolve(newProperty);
339             };
340             this.componentService.updateProperty(this.uniqueId, property).then(onSuccess, onError);
341         }
342         return deferred.promise;
343     };
344
345     public addOrUpdateAttribute = (attribute:AttributeModel):ng.IPromise<AttributeModel> => {
346         let deferred = this.$q.defer<AttributeModel>();
347
348         let onError = (error:any):void => {
349             deferred.reject(error);
350         };
351
352         if (!attribute.uniqueId) {
353             let onSuccess = (attribute:AttributeModel):void => {
354                 let newAttribute = new AttributeModel(attribute);
355                 this.attributes.push(newAttribute);
356                 deferred.resolve(newAttribute);
357             };
358             this.componentService.addAttribute(this.uniqueId, attribute).then(onSuccess, onError);
359         }
360         else {
361             let onSuccess = (newAttribute:AttributeModel):void => {
362                 let existAttribute:AttributeModel = <AttributeModel>_.find(this.attributes, {uniqueId: newAttribute.uniqueId});
363                 let attributeIndex = this.attributes.indexOf(existAttribute);
364                 newAttribute.readonly = this.uniqueId != newAttribute.parentUniqueId;
365                 this.attributes[attributeIndex] = newAttribute;
366                 deferred.resolve(newAttribute);
367             };
368             this.componentService.updateAttribute(this.uniqueId, attribute).then(onSuccess, onError);
369         }
370         return deferred.promise;
371     };
372
373     public deleteProperty = (propertyId:string):ng.IPromise<PropertyModel> => {
374         let deferred = this.$q.defer<PropertyModel>();
375         let onSuccess = ():void => {
376             console.log("Property deleted");
377             delete _.remove(this.properties, {uniqueId: propertyId})[0];
378             deferred.resolve();
379         };
380         let onFailed = ():void => {
381             console.log("Failed to delete property");
382             deferred.reject();
383         };
384         this.componentService.deleteProperty(this.uniqueId, propertyId).then(onSuccess, onFailed);
385         return deferred.promise;
386     };
387
388     public deleteAttribute = (attributeId:string):ng.IPromise<AttributeModel> => {
389         let deferred = this.$q.defer<AttributeModel>();
390         let onSuccess = ():void => {
391             console.log("Attribute deleted");
392             delete _.remove(this.attributes, {uniqueId: attributeId})[0];
393         };
394         let onFailed = ():void => {
395             console.log("Failed to delete attribute");
396         };
397         this.componentService.deleteAttribute(this.uniqueId, attributeId).then(onSuccess, onFailed);
398         return deferred.promise;
399     };
400
401     public downloadInstanceArtifact = (artifactId:string):ng.IPromise<IFileDownload> => {
402         return this.componentService.downloadInstanceArtifact(this.uniqueId, this.selectedInstance.uniqueId, artifactId);
403     };
404
405     public getModuleForDisplay = (moduleId:string):ng.IPromise<DisplayModule> => {
406
407         let deferred = this.$q.defer<DisplayModule>();
408         let onSuccess = (response:DisplayModule):void => {
409             deferred.resolve(response);
410         };
411         let onFailed = (error:any):void => {
412             deferred.reject(error);
413         };
414         this.componentService.getModuleForDisplay(this.uniqueId, moduleId).then(onSuccess, onFailed);
415         return deferred.promise;
416     };
417
418     public getModuleInstanceForDisplay = (componentInstanceId:string, moduleId:string):ng.IPromise<DisplayModule> => {
419
420         let deferred = this.$q.defer<DisplayModule>();
421         let onSuccess = (response:DisplayModule):void => {
422             deferred.resolve(response);
423         };
424         let onFailed = (error:any):void => {
425             deferred.reject(error);
426         };
427         this.componentService.getComponentInstanceModule(this.uniqueId, componentInstanceId, moduleId).then(onSuccess, onFailed);
428         return deferred.promise;
429     };
430
431     public updateGroupMetadata = (module:Module):ng.IPromise<Module> => {
432
433         let deferred = this.$q.defer<Module>();
434
435         let onSuccess = (updatedModule:Module):void => {
436             let groupIndex:number = _.indexOf(this.modules, _.find(this.modules, (module:Module) => {
437                 return module.uniqueId === updatedModule.uniqueId;
438             }));
439
440             if (groupIndex !== -1) {
441                 this.modules[groupIndex] = updatedModule;
442             }
443             deferred.resolve(updatedModule);
444         };
445         let onFailed = (error:any):void => {
446             deferred.reject(error);
447         };
448
449         this.componentService.updateGroupMetadata(this.uniqueId, module).then(onSuccess, onFailed);
450
451         return deferred.promise;
452     };
453
454     //------------------------------------------ Help Functions ----------------------------------------------------------------//
455
456     public isService = ():boolean => {
457         return this instanceof Service;
458     };
459
460     public isResource = ():boolean => {
461         return this instanceof Resource;
462     };
463
464     public getComponentSubType = ():string => {
465         return this.componentType;
466     };
467
468     public isAlreadyCertified = ():boolean => {
469         return parseInt(this.version) >= 1;
470     };
471
472     public isComplex = ():boolean => {
473         return true;
474     };
475
476     //sort string version value from hash to sorted version (i.e 1.9 before 1.11)
477     private sortVersions = (v1:string, v2:string):number => {
478         let ver1 = v1.split('.');
479         let ver2 = v2.split('.');
480         let diff = parseInt(_.first(ver1)) - parseInt(_.first(ver2));
481         if (!diff) {
482             return parseInt(_.last(ver1)) - parseInt(_.last(ver2));
483         }
484         return diff;
485     };
486
487     public getAllVersionsAsSortedArray = ():Array<any> => {
488         let res = [];
489         if (this.allVersions) {
490             let keys = Object.keys(this.allVersions).sort(this.sortVersions);
491             _.forEach(keys, (key)=> {
492                 res.push({
493                     versionNumber: key,
494                     versionId: this.allVersions[key]
495                 })
496             });
497         }
498         return res;
499     };
500
501     public isLatestVersion = ():boolean => {
502         if (this.allVersions) {
503             return this.version === _.last(Object.keys(this.allVersions).sort(this.sortVersions));
504         } else {
505             return true;
506         }
507
508     };
509
510
511     public handleTags = ():void => {
512         let isContainTag = _.find(this.tags, (tag)=> {
513             return tag === this.name;
514         });
515         if (!isContainTag) {
516             this.tags.push(this.name);
517         }
518     };
519
520     public getArtifactsByType = (artifactGroupType:string):ArtifactGroupModel => {
521         switch (artifactGroupType) {
522             case ArtifactGroupType.DEPLOYMENT:
523                 return this.deploymentArtifacts;
524             case ArtifactGroupType.INFORMATION:
525                 return this.artifacts;
526         }
527     };
528
529     public getStatus = (sdcMenu:IAppMenu):string => {
530         let status:string = sdcMenu.LifeCycleStatuses[this.lifecycleState].text;
531         if (this.lifecycleState == "CERTIFIED" && sdcMenu.DistributionStatuses[this.distributionStatus]) {
532             status = sdcMenu.DistributionStatuses[this.distributionStatus].text;
533         }
534         return status;
535     };
536
537     public abstract setComponentDisplayData():void;
538     public abstract getTypeUrl():string;
539
540     public setComponentMetadata(componentMetadata: ComponentMetadata) {
541         this.abstract = componentMetadata.abstract;
542         this.uniqueId = componentMetadata.uniqueId;
543         this.uuid = componentMetadata.uuid;
544         this.invariantUUID = componentMetadata.invariantUUID;
545         this.contactId = componentMetadata.contactId;
546         this.categories = componentMetadata.categories;
547         this.creatorUserId = componentMetadata.creatorUserId;
548         this.creationDate = componentMetadata.creationDate;
549         this.creatorFullName = componentMetadata.creatorFullName;
550         this.description = componentMetadata.description;
551         this.icon = componentMetadata.icon;
552         this.lastUpdateDate = componentMetadata.lastUpdateDate;
553         this.lastUpdaterUserId = componentMetadata.lastUpdaterUserId;
554         this.lastUpdaterFullName = componentMetadata.lastUpdaterFullName;
555         this.lifecycleState = componentMetadata.lifecycleState;
556         this.name = componentMetadata.name;
557         this.version = componentMetadata.version;
558         this.tags = angular.copy(componentMetadata.tags, this.tags);
559         this.allVersions = componentMetadata.allVersions;
560         this.componentType = componentMetadata.componentType;
561         this.distributionStatus = componentMetadata.distributionStatus;
562         this.highestVersion = componentMetadata.highestVersion;
563         this.vendorName = componentMetadata.vendorName;
564         this.vendorRelease = componentMetadata.vendorRelease;
565         this.derivedList = componentMetadata.derivedList;
566         this.normalizedName = componentMetadata.normalizedName;
567         this.systemName = componentMetadata.systemName;
568         this.categories = componentMetadata.categories;
569         this.archived = componentMetadata.archived || false;
570         this.vspArchived = componentMetadata.vspArchived;
571         this.componentMetadata = componentMetadata;
572         if (componentMetadata.categorySpecificMetadata){
573             this.categorySpecificMetadata = componentMetadata.categorySpecificMetadata;
574         } else {
575             this.categorySpecificMetadata = new Metadata();
576         }
577     }
578
579     public toJSON = ():any => {
580         let temp = angular.copy(this);
581         temp.componentService = undefined;
582         temp.filterTerm = undefined;
583         temp.iconSprite = undefined;
584         temp.mainCategory = undefined;
585         temp.subCategory = undefined;
586         temp.selectedInstance = undefined;
587         temp.showMenu = undefined;
588         temp.$q = undefined;
589         temp.selectedCategory = undefined;
590         temp.modules = undefined
591         temp.groupInstances = undefined;
592         temp.policies = undefined;
593         return temp;
594     };
595 }
596