2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2021 Nordix Foundation
4 * ================================================================================
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 * SPDX-License-Identifier: Apache-2.0
17 * ============LICENSE_END=========================================================
20 import {Component, EventEmitter, Input, OnChanges, OnInit, Output, SimpleChanges} from '@angular/core';
21 import {AttributeBEModel, ComponentMetadata, DataTypeModel, PropertyBEModel, PropertyModel, PropertyDeclareAPIModel, DerivedFEProperty} from 'app/models';
22 import {TopologyTemplateService} from "../../../../services/component-services/topology-template.service";
23 import {WorkspaceService} from "../../../workspace/workspace.service";
24 import {PropertiesService} from "../../../../services/properties.service";
25 import {PROPERTY_DATA, PROPERTY_TYPES} from "../../../../../utils/constants";
26 import {DataTypeService} from "../../../../services/data-type.service";
27 import {ToscaGetFunctionType} from "../../../../../models/tosca-get-function-type";
28 import {TranslateService} from "../../../../shared/translator/translate.service";
29 import {ComponentGenericResponse} from '../../../../services/responses/component-generic-response';
30 import {Observable} from 'rxjs/Observable';
31 import {PropertySource} from "../../../../../models/property-source";
32 import {InstanceFeDetails} from "../../../../../models/instance-fe-details";
33 import {ToscaGetFunction} from "../../../../../models/tosca-get-function";
34 import {FormControl, FormGroup, Validators} from "@angular/forms";
35 import {ToscaGetFunctionTypeConverter} from "../../../../../models/tosca-get-function-type-converter";
38 selector: 'app-tosca-get-function',
39 templateUrl: './tosca-get-function.component.html',
40 styleUrls: ['./tosca-get-function.component.less']
42 export class ToscaGetFunctionComponent implements OnInit, OnChanges {
44 @Input() property: PropertyBEModel;
45 @Input() toscaGetFunction: ToscaGetFunction;
46 @Input() componentInstanceMap: Map<string, InstanceFeDetails> = new Map<string, InstanceFeDetails>();
47 @Input() functionType: ToscaGetFunctionType;
48 @Input() compositionMap: boolean;
49 @Input() compositionMapKey: string;
50 @Output() onValidFunction: EventEmitter<ToscaGetFunction> = new EventEmitter<ToscaGetFunction>();
51 @Output() onValidityChange: EventEmitter<ToscaGetFunctionValidationEvent> = new EventEmitter<ToscaGetFunctionValidationEvent>();
53 formGroup: FormGroup = new FormGroup({
54 'selectedProperty': new FormControl(undefined, Validators.required),
55 'propertySource': new FormControl(undefined, Validators.required)
58 isLoading: boolean = false;
59 propertyDropdownList: Array<PropertyDropdownValue> = [];
60 propertySourceList: Array<string> = [];
61 instanceNameAndIdMap: Map<string, string> = new Map<string, string>();
62 dropdownValuesLabel: string;
63 dropDownErrorMsg: string;
65 private isInitialized: boolean = false;
66 private componentMetadata: ComponentMetadata;
68 constructor(private topologyTemplateService: TopologyTemplateService,
69 private workspaceService: WorkspaceService,
70 private propertiesService: PropertiesService,
71 private dataTypeService: DataTypeService,
72 private translateService: TranslateService) {
76 this.componentMetadata = this.workspaceService.metadata;
77 this.formGroup.valueChanges.subscribe(() => {
78 if (!this.isInitialized) {
81 this.onValidityChange.emit({
82 isValid: this.formGroup.valid,
83 toscaGetFunction: this.formGroup.valid ? this.buildGetFunctionFromForm() : undefined
85 if (this.formGroup.valid) {
86 this.onValidFunction.emit(this.buildGetFunctionFromForm());
89 this.loadPropertySourceDropdown();
90 this.loadPropertyDropdownLabel();
91 this.initToscaGetFunction().subscribe(() => {
92 this.isInitialized = true;
97 ngOnChanges(_changes: SimpleChanges): void {
98 if (!this.isInitialized) {
101 this.isInitialized = false;
103 this.loadPropertySourceDropdown();
104 this.loadPropertyDropdownLabel();
105 this.initToscaGetFunction().subscribe(() => {
106 this.isInitialized = true;
110 private initToscaGetFunction(): Observable<void> {
111 return new Observable(subscriber => {
112 if (!this.toscaGetFunction) {
113 if (this.isGetInput()) {
114 this.setSelfPropertySource();
115 this.loadPropertyDropdown();
120 if (this.toscaGetFunction.propertySource == PropertySource.SELF) {
121 this.propertySource.setValue(PropertySource.SELF);
122 } else if (this.toscaGetFunction.propertySource == PropertySource.INSTANCE) {
124 .setValue(this.propertySourceList.find(source => this.toscaGetFunction.sourceName === source));
126 if (this.propertySource.valid) {
127 this.loadPropertyDropdown(() => {
128 this.selectedProperty
129 .setValue(this.propertyDropdownList.find(property => property.propertyName === this.toscaGetFunction.propertyName));
138 private buildGetFunctionFromForm() {
139 const toscaGetFunction = new ToscaGetFunction();
140 toscaGetFunction.type = ToscaGetFunctionTypeConverter.convertToToscaFunctionType(this.functionType);
141 toscaGetFunction.functionType = this.functionType;
142 const propertySource = this.propertySource.value;
143 if (this.isPropertySourceSelf()) {
144 toscaGetFunction.propertySource = propertySource
145 toscaGetFunction.sourceName = this.componentMetadata.name;
146 toscaGetFunction.sourceUniqueId = this.componentMetadata.uniqueId;
148 toscaGetFunction.propertySource = PropertySource.INSTANCE;
149 toscaGetFunction.sourceName = propertySource;
150 toscaGetFunction.sourceUniqueId = this.instanceNameAndIdMap.get(propertySource);
153 const selectedProperty: PropertyDropdownValue = this.selectedProperty.value;
154 toscaGetFunction.propertyUniqueId = selectedProperty.propertyId;
155 toscaGetFunction.propertyName = selectedProperty.propertyName;
156 toscaGetFunction.propertyPathFromSource = selectedProperty.propertyPath;
158 return toscaGetFunction;
161 private loadPropertySourceDropdown(): void {
162 if (this.isGetInput()) {
165 this.propertySourceList = [];
166 this.propertySourceList.push(PropertySource.SELF);
167 this.componentInstanceMap.forEach((value, key) => {
168 const instanceName = value.name;
169 this.instanceNameAndIdMap.set(instanceName, key);
170 if (instanceName !== PropertySource.SELF) {
171 this.addToPropertySource(instanceName);
176 private addToPropertySource(source: string): void {
177 this.propertySourceList.push(source);
178 this.propertySourceList.sort((a, b) => {
179 if (a === PropertySource.SELF) {
181 } else if (b === PropertySource.SELF) {
185 return a.localeCompare(b);
189 private loadPropertyDropdown(onComplete?: () => any): void {
190 this.loadPropertyDropdownLabel();
191 this.loadPropertyDropdownValues(onComplete);
194 private resetForm(): void {
195 this.formGroup.reset();
198 private loadPropertyDropdownLabel(): void {
199 if (!this.functionType) {
202 if (this.isGetInput()) {
203 this.dropdownValuesLabel = this.translateService.translate('INPUT_DROPDOWN_LABEL');
204 } else if (this.isGetProperty()) {
205 this.dropdownValuesLabel = this.translateService.translate('TOSCA_FUNCTION_PROPERTY_DROPDOWN_LABEL');
206 } else if (this.isGetAttribute()) {
207 this.dropdownValuesLabel = this.translateService.translate('TOSCA_FUNCTION_ATTRIBUTE_DROPDOWN_LABEL');
211 private loadPropertyDropdownValues(onComplete?: () => any): void {
212 if (!this.functionType) {
215 this.resetPropertyDropdown();
216 this.fillPropertyDropdownValues(onComplete);
219 private resetPropertyDropdown(): void {
220 this.dropDownErrorMsg = undefined;
221 this.selectedProperty.reset();
222 this.propertyDropdownList = [];
225 private fillPropertyDropdownValues(onComplete?: () => any): void {
227 const propertiesObservable: Observable<ComponentGenericResponse> = this.getPropertyObservable();
228 propertiesObservable.subscribe( (response: ComponentGenericResponse) => {
229 const properties: Array<PropertyBEModel | AttributeBEModel> = this.extractProperties(response);
230 if (!properties || properties.length === 0) {
231 const msgCode = this.getNotFoundMsgCode();
232 this.dropDownErrorMsg = this.translateService.translate(msgCode, {type: this.propertyTypeToString()});
235 this.addPropertiesToDropdown(properties);
236 if (this.propertyDropdownList.length == 0) {
237 const msgCode = this.getNotFoundMsgCode();
238 this.dropDownErrorMsg = this.translateService.translate(msgCode, {type: this.propertyTypeToString()});
241 console.error('An error occurred while loading properties.', error);
251 private getNotFoundMsgCode(): string {
252 if (this.isGetInput()) {
253 return 'TOSCA_FUNCTION_NO_INPUT_FOUND';
255 if (this.isGetAttribute()) {
256 return 'TOSCA_FUNCTION_NO_ATTRIBUTE_FOUND';
258 if (this.isGetProperty()) {
259 return 'TOSCA_FUNCTION_NO_PROPERTY_FOUND';
265 private propertyTypeToString() {
266 if (this.isSubProperty()){
267 if ((this.property instanceof PropertyDeclareAPIModel && (<PropertyDeclareAPIModel> this.property).input instanceof DerivedFEProperty)
268 || this.compositionMap) {
269 if(this.isComplexType(this.property.schemaType) && !this.compositionMap){
270 let mapChildProp : DerivedFEProperty = (<DerivedFEProperty> (<PropertyDeclareAPIModel> this.property).input);
271 let propertySchemaType = mapChildProp.type;
272 if (this.property.type == PROPERTY_TYPES.MAP || propertySchemaType == PROPERTY_TYPES.MAP) {
273 if (mapChildProp.mapKey != '' && mapChildProp.mapKey != null && mapChildProp.schema.property.type != null) {
274 propertySchemaType = mapChildProp.schema.property.type;
277 if ((propertySchemaType == PROPERTY_TYPES.MAP || (propertySchemaType == PROPERTY_TYPES.LIST && mapChildProp.schema.property.type == PROPERTY_TYPES.MAP))
278 && mapChildProp.isChildOfListOrMap) {
279 propertySchemaType = PROPERTY_TYPES.STRING;
281 return propertySchemaType;
283 return this.property.schema.property.type;
286 return this.getType((<PropertyDeclareAPIModel>this.property).propertiesName.split("#").slice(1), this.property.type);
288 if (this.property.schemaType) {
289 return `${this.property.type} of ${this.property.schemaType}`;
291 return this.property.type;
294 private isSubProperty(): boolean{
295 return this.property instanceof PropertyDeclareAPIModel && (<PropertyDeclareAPIModel>this.property).propertiesName && (<PropertyDeclareAPIModel>this.property).propertiesName.length > 1;
298 private extractProperties(componentGenericResponse: ComponentGenericResponse): Array<PropertyBEModel | AttributeBEModel> {
299 if (this.isGetInput()) {
300 return componentGenericResponse.inputs;
302 const instanceId = this.instanceNameAndIdMap.get(this.propertySource.value);
303 if (this.isGetProperty()) {
304 if (this.isPropertySourceSelf()) {
305 return componentGenericResponse.properties;
307 return this.removeSelectedProperty(componentGenericResponse.componentInstancesProperties[instanceId]);
309 if (this.isPropertySourceSelf()) {
310 return [...(componentGenericResponse.attributes || []), ...(componentGenericResponse.properties || [])];
312 return [...(componentGenericResponse.componentInstancesAttributes[instanceId] || []),
313 ...(componentGenericResponse.componentInstancesProperties[instanceId] || [])];
316 private isPropertySourceSelf() {
317 return this.propertySource.value === PropertySource.SELF;
320 private getPropertyObservable(): Observable<ComponentGenericResponse> {
321 if (this.isGetInput()) {
322 return this.topologyTemplateService.getComponentInputsValues(this.componentMetadata.componentType, this.componentMetadata.uniqueId);
324 if (this.isGetProperty()) {
325 if (this.isPropertySourceSelf()) {
326 return this.topologyTemplateService.findAllComponentProperties(this.componentMetadata.componentType, this.componentMetadata.uniqueId);
328 return this.topologyTemplateService.getComponentInstanceProperties(this.componentMetadata.componentType, this.componentMetadata.uniqueId);
330 if (this.isGetAttribute()) {
331 if (this.isPropertySourceSelf()) {
332 return this.topologyTemplateService.findAllComponentAttributesAndProperties(this.componentMetadata.componentType, this.componentMetadata.uniqueId);
334 return this.topologyTemplateService.getComponentInstanceAttributesAndProperties(this.componentMetadata.uniqueId, this.componentMetadata.componentType);
338 private removeSelectedProperty(componentInstanceProperties: PropertyModel[]): PropertyModel[] {
339 if (!componentInstanceProperties) {
342 return componentInstanceProperties.filter(property =>
343 (property.uniqueId !== this.property.uniqueId) ||
344 (property.uniqueId === this.property.uniqueId && property.resourceInstanceUniqueId !== this.property.parentUniqueId)
348 private addPropertyToDropdown(propertyDropdownValue: PropertyDropdownValue): void {
349 this.propertyDropdownList.push(propertyDropdownValue);
350 this.propertyDropdownList.sort((a, b) => a.propertyLabel.localeCompare(b.propertyLabel));
353 private addPropertiesToDropdown(properties: Array<PropertyBEModel | AttributeBEModel>): void {
354 for (const property of properties) {
355 if (this.hasSameType(property)) {
356 this.addPropertyToDropdown({
357 propertyName: property.name,
358 propertyId: property.uniqueId,
359 propertyLabel: property.name,
360 propertyPath: [property.name]
362 } else if (this.isComplexType(property.type)) {
363 this.fillPropertyDropdownWithMatchingChildProperties(property);
368 private fillPropertyDropdownWithMatchingChildProperties(inputProperty: PropertyBEModel | AttributeBEModel,
369 parentPropertyList: Array<PropertyBEModel | AttributeBEModel> = []): void {
370 const dataTypeFound: DataTypeModel = this.dataTypeService.getDataTypeByModelAndTypeName(this.componentMetadata.model, inputProperty.type);
371 if (!dataTypeFound || !dataTypeFound.properties) {
374 parentPropertyList.push(inputProperty);
375 dataTypeFound.properties.forEach(dataTypeProperty => {
376 if (this.hasSameType(dataTypeProperty)) {
377 this.addPropertyToDropdown({
378 propertyName: dataTypeProperty.name,
379 propertyId: parentPropertyList[0].uniqueId,
380 propertyLabel: parentPropertyList.map(property => property.name).join('->') + '->' + dataTypeProperty.name,
381 propertyPath: [...parentPropertyList.map(property => property.name), dataTypeProperty.name]
383 } else if (this.isComplexType(dataTypeProperty.type)) {
384 this.fillPropertyDropdownWithMatchingChildProperties(dataTypeProperty, [...parentPropertyList])
389 private hasSameType(property: PropertyBEModel | AttributeBEModel): boolean {
390 if (this.typeHasSchema(this.property.type)) {
391 if ((this.property instanceof PropertyDeclareAPIModel && (<PropertyDeclareAPIModel> this.property).input instanceof DerivedFEProperty) || this.compositionMap) {
392 let childObject : DerivedFEProperty = (<DerivedFEProperty>(<PropertyDeclareAPIModel> this.property).input);
393 let childSchemaType = this.property.schemaType != null ? this.property.schemaType : childObject.type;
394 if(this.isComplexType(childSchemaType) && !this.compositionMap){
395 if (childObject.type == PROPERTY_TYPES.MAP && childObject.isChildOfListOrMap) {
396 return property.type === PROPERTY_TYPES.STRING;
398 return property.type === childObject.type;
400 return property.type === this.property.schema.property.type;
403 if (!property.schema || !property.schema.property) {
406 return property.type === this.property.type && this.property.schema.property.type === property.schema.property.type;
408 if (this.property.schema.property.isDataType && this.property instanceof PropertyDeclareAPIModel && (<PropertyDeclareAPIModel>this.property).propertiesName){
409 let typeToMatch = (<PropertyDeclareAPIModel> this.property).input.type;
410 let childObject : DerivedFEProperty = (<DerivedFEProperty>(<PropertyDeclareAPIModel> this.property).input);
411 if (childObject.type == PROPERTY_TYPES.MAP && childObject.isChildOfListOrMap) {
412 typeToMatch = PROPERTY_TYPES.STRING;
414 return property.type === typeToMatch;
417 return property.type === this.property.type;
420 private getType(propertyPath:string[], type: string): string {
421 const dataTypeFound: DataTypeModel = this.dataTypeService.getDataTypeByModelAndTypeName(this.componentMetadata.model, type);
422 let nestedProperty = dataTypeFound.properties.find(property => property.name === propertyPath[0]);
423 if (propertyPath.length === 1){
424 return nestedProperty.type;
426 return this.getType(propertyPath.slice(1), nestedProperty.type);
429 private isGetProperty(): boolean {
430 return this.functionType === ToscaGetFunctionType.GET_PROPERTY;
433 private isGetAttribute(): boolean {
434 return this.functionType === ToscaGetFunctionType.GET_ATTRIBUTE;
437 private isGetInput(): boolean {
438 return this.functionType === ToscaGetFunctionType.GET_INPUT;
441 private isComplexType(propertyType: string): boolean {
442 return PROPERTY_DATA.SIMPLE_TYPES.indexOf(propertyType) === -1;
445 private typeHasSchema(propertyType: string): boolean {
446 return PROPERTY_TYPES.MAP === propertyType || PROPERTY_TYPES.LIST === propertyType;
449 private stopLoading(): void {
450 this.isLoading = false;
453 private startLoading(): void {
454 this.isLoading = true;
457 showPropertyDropdown(): boolean {
458 if (this.isGetProperty() || this.isGetAttribute()) {
459 return this.propertySource.valid && !this.isLoading && !this.dropDownErrorMsg;
462 return this.functionType && !this.isLoading && !this.dropDownErrorMsg;
465 onPropertySourceChange(): void {
466 this.selectedProperty.reset();
467 if (!this.functionType || !this.propertySource.valid) {
470 this.loadPropertyDropdown();
473 showPropertySourceDropdown(): boolean {
474 return this.isGetProperty() || this.isGetAttribute();
477 private setSelfPropertySource(): void {
478 this.propertySource.setValue(PropertySource.SELF);
481 private get propertySource(): FormControl {
482 return this.formGroup.get('propertySource') as FormControl;
485 private get selectedProperty(): FormControl {
486 return this.formGroup.get('selectedProperty') as FormControl;
491 export interface PropertyDropdownValue {
492 propertyName: string;
494 propertyLabel: string;
495 propertyPath: Array<string>;
498 export interface ToscaGetFunctionValidationEvent {
500 toscaGetFunction: ToscaGetFunction,