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.typeHasSchema(this.property.type) && this.property instanceof PropertyDeclareAPIModel &&
268 (<PropertyDeclareAPIModel> this.property).input instanceof DerivedFEProperty) || this.compositionMap) {
269 if(this.isComplexType(this.property.schemaType) && !this.compositionMap){
270 return (<PropertyDeclareAPIModel> this.property).input.type;
272 return this.property.schema.property.type;
275 return this.getType((<PropertyDeclareAPIModel>this.property).propertiesName.split("#").slice(1), this.property.type);
277 if (this.property.schemaType) {
278 return `${this.property.type} of ${this.property.schemaType}`;
280 return this.property.type;
283 private isSubProperty(): boolean{
284 return this.property instanceof PropertyDeclareAPIModel && (<PropertyDeclareAPIModel>this.property).propertiesName && (<PropertyDeclareAPIModel>this.property).propertiesName.length > 1;
287 private extractProperties(componentGenericResponse: ComponentGenericResponse): Array<PropertyBEModel | AttributeBEModel> {
288 if (this.isGetInput()) {
289 return componentGenericResponse.inputs;
291 const instanceId = this.instanceNameAndIdMap.get(this.propertySource.value);
292 if (this.isGetProperty()) {
293 if (this.isPropertySourceSelf()) {
294 return componentGenericResponse.properties;
296 return this.removeSelectedProperty(componentGenericResponse.componentInstancesProperties[instanceId]);
298 if (this.isPropertySourceSelf()) {
299 return [...(componentGenericResponse.attributes || []), ...(componentGenericResponse.properties || [])];
301 return [...(componentGenericResponse.componentInstancesAttributes[instanceId] || []),
302 ...(componentGenericResponse.componentInstancesProperties[instanceId] || [])];
305 private isPropertySourceSelf() {
306 return this.propertySource.value === PropertySource.SELF;
309 private getPropertyObservable(): Observable<ComponentGenericResponse> {
310 if (this.isGetInput()) {
311 return this.topologyTemplateService.getComponentInputsValues(this.componentMetadata.componentType, this.componentMetadata.uniqueId);
313 if (this.isGetProperty()) {
314 if (this.isPropertySourceSelf()) {
315 return this.topologyTemplateService.findAllComponentProperties(this.componentMetadata.componentType, this.componentMetadata.uniqueId);
317 return this.topologyTemplateService.getComponentInstanceProperties(this.componentMetadata.componentType, this.componentMetadata.uniqueId);
319 if (this.isGetAttribute()) {
320 if (this.isPropertySourceSelf()) {
321 return this.topologyTemplateService.findAllComponentAttributesAndProperties(this.componentMetadata.componentType, this.componentMetadata.uniqueId);
323 return this.topologyTemplateService.getComponentInstanceAttributesAndProperties(this.componentMetadata.uniqueId, this.componentMetadata.componentType);
327 private removeSelectedProperty(componentInstanceProperties: PropertyModel[]): PropertyModel[] {
328 if (!componentInstanceProperties) {
331 return componentInstanceProperties.filter(property =>
332 (property.uniqueId !== this.property.uniqueId) ||
333 (property.uniqueId === this.property.uniqueId && property.resourceInstanceUniqueId !== this.property.parentUniqueId)
337 private addPropertyToDropdown(propertyDropdownValue: PropertyDropdownValue): void {
338 this.propertyDropdownList.push(propertyDropdownValue);
339 this.propertyDropdownList.sort((a, b) => a.propertyLabel.localeCompare(b.propertyLabel));
342 private addPropertiesToDropdown(properties: Array<PropertyBEModel | AttributeBEModel>): void {
343 for (const property of properties) {
344 if (this.hasSameType(property)) {
345 this.addPropertyToDropdown({
346 propertyName: property.name,
347 propertyId: property.uniqueId,
348 propertyLabel: property.name,
349 propertyPath: [property.name]
351 } else if (this.isComplexType(property.type)) {
352 this.fillPropertyDropdownWithMatchingChildProperties(property);
357 private fillPropertyDropdownWithMatchingChildProperties(inputProperty: PropertyBEModel | AttributeBEModel,
358 parentPropertyList: Array<PropertyBEModel | AttributeBEModel> = []): void {
359 const dataTypeFound: DataTypeModel = this.dataTypeService.getDataTypeByModelAndTypeName(this.componentMetadata.model, inputProperty.type);
360 if (!dataTypeFound || !dataTypeFound.properties) {
363 parentPropertyList.push(inputProperty);
364 dataTypeFound.properties.forEach(dataTypeProperty => {
365 if (this.hasSameType(dataTypeProperty)) {
366 this.addPropertyToDropdown({
367 propertyName: dataTypeProperty.name,
368 propertyId: parentPropertyList[0].uniqueId,
369 propertyLabel: parentPropertyList.map(property => property.name).join('->') + '->' + dataTypeProperty.name,
370 propertyPath: [...parentPropertyList.map(property => property.name), dataTypeProperty.name]
372 } else if (this.isComplexType(dataTypeProperty.type)) {
373 this.fillPropertyDropdownWithMatchingChildProperties(dataTypeProperty, [...parentPropertyList])
378 private hasSameType(property: PropertyBEModel | AttributeBEModel): boolean {
379 if (this.typeHasSchema(this.property.type)) {
380 if ((this.property instanceof PropertyDeclareAPIModel && (<PropertyDeclareAPIModel> this.property).input instanceof DerivedFEProperty) || this.compositionMap) {
381 if(this.isComplexType(this.property.schemaType) && !this.compositionMap){
382 return property.type === (<PropertyDeclareAPIModel> this.property).input.type;
384 return property.type === this.property.schema.property.type;
387 if (!property.schema || !property.schema.property) {
390 return property.type === this.property.type && this.property.schema.property.type === property.schema.property.type;
392 if (this.property.schema.property.isDataType && this.property instanceof PropertyDeclareAPIModel && (<PropertyDeclareAPIModel>this.property).propertiesName){
393 let typeToMatch = this.getType((<PropertyDeclareAPIModel>this.property).propertiesName.split("#").slice(1), this.property.type);
394 return property.type === typeToMatch;
397 return property.type === this.property.type;
400 private getType(propertyPath:string[], type: string): string {
401 const dataTypeFound: DataTypeModel = this.dataTypeService.getDataTypeByModelAndTypeName(this.componentMetadata.model, type);
402 let nestedProperty = dataTypeFound.properties.find(property => property.name === propertyPath[0]);
403 if (propertyPath.length === 1){
404 return nestedProperty.type;
406 return this.getType(propertyPath.slice(1), nestedProperty.type);
409 private isGetProperty(): boolean {
410 return this.functionType === ToscaGetFunctionType.GET_PROPERTY;
413 private isGetAttribute(): boolean {
414 return this.functionType === ToscaGetFunctionType.GET_ATTRIBUTE;
417 private isGetInput(): boolean {
418 return this.functionType === ToscaGetFunctionType.GET_INPUT;
421 private isComplexType(propertyType: string): boolean {
422 return PROPERTY_DATA.SIMPLE_TYPES.indexOf(propertyType) === -1;
425 private typeHasSchema(propertyType: string): boolean {
426 return PROPERTY_TYPES.MAP === propertyType || PROPERTY_TYPES.LIST === propertyType;
429 private stopLoading(): void {
430 this.isLoading = false;
433 private startLoading(): void {
434 this.isLoading = true;
437 showPropertyDropdown(): boolean {
438 if (this.isGetProperty() || this.isGetAttribute()) {
439 return this.propertySource.valid && !this.isLoading && !this.dropDownErrorMsg;
442 return this.functionType && !this.isLoading && !this.dropDownErrorMsg;
445 onPropertySourceChange(): void {
446 this.selectedProperty.reset();
447 if (!this.functionType || !this.propertySource.valid) {
450 this.loadPropertyDropdown();
453 showPropertySourceDropdown(): boolean {
454 return this.isGetProperty() || this.isGetAttribute();
457 private setSelfPropertySource(): void {
458 this.propertySource.setValue(PropertySource.SELF);
461 private get propertySource(): FormControl {
462 return this.formGroup.get('propertySource') as FormControl;
465 private get selectedProperty(): FormControl {
466 return this.formGroup.get('selectedProperty') as FormControl;
471 export interface PropertyDropdownValue {
472 propertyName: string;
474 propertyLabel: string;
475 propertyPath: Array<string>;
478 export interface ToscaGetFunctionValidationEvent {
480 toscaGetFunction: ToscaGetFunction,